Re: Formatting a str as a number - Okay, one more related thing...

2024-08-31 Thread MRAB via Python-list

On 2024-08-31 06:31, Gilmeh Serda via Python-list wrote:

On Fri, 30 Aug 2024 05:22:17 GMT, Gilmeh Serda wrote:


f"{int(number):>20,}"


I can find "," (comma) and I can find "_" (underscore) but how about " "
(space)?

Or any other character, for that matter?

Any ideas?

Of course I can do f"{123456:>20_}".replace("_", " "), just thought there
might be something else my search mojo fails on.


The format is described here:

https://docs.python.org/3/library/string.html#formatspec

A space is counted as a fill character.
--
https://mail.python.org/mailman/listinfo/python-list


Re: new here

2024-08-25 Thread MRAB via Python-list

On 2024-08-26 02:29, AVI GROSS via Python-list wrote:

If everyone will pardon my curiosity, who and what purposes are these
smaller environments for and do many people use them?

I mean the price of a typical minimal laptop is not a big deal today. So are
these for some sort of embedded uses?

I read about them ages ago but wonder ...

A Raspberry Pi Pico W costs less than £5, is a lot smaller, and has a 
much lower power consumption than a laptop, so if it's good enough for 
the purpose (embedded controller), why use a laptop? That's overkill!


-Original Message-
From: Python-list  On
Behalf Of rbowman via Python-list
Sent: Friday, August 23, 2024 1:22 AM
To: python-list@python.org
Subject: Re: new here

On Fri, 23 Aug 2024 16:23:42 +1200, dn wrote:


Adding a display to the Pico-W is my next project... After that, gyros
(am thinking it may not go so well, on balance... hah!).


https://toptechboy.com/two-axis-tilt-meter-displaying-pitch-and-roll-
using-an-mpu6050-on-the-raspberry-pi-pico-w/

You might have to go back a lesson or two for the lead up. As he generally
says in the intro most of what he uses is from the Sunfounder Kepler kit.
It has a standard LCD display but he suggested buying the OLED separately
and used it for Lissajous patterns and other fancier stuff.

It's not a bad series although he can be long-winded and his Python style
definitely isn't PEP8 friendly.

https://toptechboy.com/

He switched to the Arduino Uno R4 after the IR controller/NeoPixel Pico
project and I don't know if he intends to go back to the Pico. He uses
Thonny but I use the MicroPython extension in VS Code. Lately I've been
using Code for everything. Mostly I work on Linux boxes but it's all the
same on Windows. There is a PlatformIO extension that works with Arduino
and other boards. PyLance upsets some because it's a MS product but it
works well too.  I've used PyCharm and like it but I also work on C, .NET,
Angular, and other projects and Code gives me a uniform IDE.


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


Re: Is there a better way? [combining f-string, thousands separator, right align]

2024-08-25 Thread MRAB via Python-list

On 2024-08-25 16:12, Gilmeh Serda via Python-list wrote:

Subject explains it, or ask.

This is a bloody mess:


s = "123456789" # arrives as str
f"{f'{int(s):,}': >20}"

' 123,456,789'


You don't need to format twice; you can combine them:

>>> s = "123456789"
>>> f'{int(s): >20,}'
' 123,456,789'

or if you rely on default behaviour:

>>> f'{int(s):20,}'
' 123,456,789'

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


Re: new here

2024-08-20 Thread MRAB via Python-list

On 2024-08-20 23:26, Daniel via Python-list wrote:

Hi folks -

New here. I've perused some posts and haven't seen a posting FAQ for
this NG. I'm learning python right now to realize some hobby goals I
have regarding some smolnet services. What are the NG standards on
pasting code in messages? Do yall prefer I post a pastebin link if it's
over a certain number of lines? I know this isn't IRC - just asking.


You'll find it rather quiet here because most activity has moved to here:

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


Re: Issue with pip Installation on My Laptop

2024-07-27 Thread MRAB via Python-list

On 2024-07-27 21:58, Mats Wichmann via Python-list wrote:

On 7/26/24 16:28, Thomas Passin via Python-list wrote:

On 7/26/2024 7:25 AM, Lizna Shah via Python-list wrote:
OSError: [WinError 225] Operation did not complete successfully 
because the

file contains a virus or potentially unwanted software


That part of the error message tells you the story.  Windows thinks some 
file in the install has been corrupted with malware.





The Windows installer comes with pip, there's no need to do an extra
install to get it:

python -m pip --version


On Windows it's recommended that you use the Python Launcher 'py':

py -m pip --version


If you can't find the pip *command*, that's a problem with yout PATH
settings.  The Python installer offers to add the location of Python
itself to PATH, and you've apparently taken it up on that offer, but
that's not the same directory that pip goes to.  Just use it as a module
and you should be fine.


===

The typical paths will be something like

C:\Users\you\AppData\Local\Programs\Python\Python310   # python executable
C:\Users\you\AppData\Local\Programs\Python\Python310\Scripts   # pip
"executable"


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


Re: Best (simplest) way to share data between processes

2024-07-07 Thread MRAB via Python-list

On 2024-07-07 23:27, Barry via Python-list wrote:




On 7 Jul 2024, at 22:13, Chris Green via Python-list  
wrote:

a simple file lock can then
be used to prevent simultaneous access (well, simultaneous access when
the writing process is writing).


There is a simple pattern to make this robust.

Write new values to a tmp file.
Close the tmp file.
Then use os.rename(tmpfile, productionfile).

This is guaranteed that any process that reads the file will only see all the 
old file contents or all the new file contents,  never a mix of both.

For clarity I'd recommend os.replace instead. This is because on Windows 
os.rename it would complain if the target file already exists, but 
os.replace has the same behaviour on both Linux and Windows.

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


Re: Decoding bytes to text strings in Python 2

2024-06-23 Thread MRAB via Python-list

On 2024-06-24 00:30, Chris Angelico via Python-list wrote:

On Mon, 24 Jun 2024 at 08:20, Rayner Lucas via Python-list
 wrote:


In article ,
ros...@gmail.com says...
>
> If you switch to a Linux system, it should work correctly, and you'll
> be able to migrate the rest of the way onto Python 3. Once you achieve
> that, you'll be able to operate on Windows or Linux equivalently,
> since Python 3 solved this problem. At least, I *think* it will; my
> current system has a Python 2 installed, but doesn't have tkinter
> (because I never bothered to install it), and it's no longer available
> from the upstream Debian repos, so I only tested it in the console.
> But the decoding certainly worked.

Thank you for the idea of trying it on a Linux system. I did so, and my
example code generated the error:

_tkinter.TclError: character U+1f40d is above the range (U+-U+)
allowed by Tcl

So it looks like the problem is ultimately due to a limitation of
Tcl/Tk.

Yep, that seems to be the case. Not sure if that's still true on a
more recent Python, but it does look like you won't get astral
characters in tkinter on the one you're using.


[snip]
Tkinter in recent versions of Python can handle astral characters, at 
least back to Python 3.8, the oldest I have on my Windows PC.

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


Re: Timezone in HH:MM Format

2024-06-18 Thread MRAB via Python-list

On 2024-06-19 00:32, Ivan "Rambius" Ivanov via Python-list wrote:

Hello,

How can I convert a date, usually datetime.now(), into a format where
the timezone is in hours:minutes format. I was able to get that format
in shell:

$ date +%Y-%m-%dT%H:%M:%S%:z
2024-06-18T19:24:09-04:00

The closest I got in python is

from datetime import datetime
from zoneinfo import ZoneInfo

s = datetime.strftime(datetime.now(ZoneInfo("America/New_York")),
"%Y-%m-%dT%H:%M:%S%z")
print(s)

This prints the same as the shell command above except the last column:
2024-06-18T19:28:56-0400

Starting from Python 3.12, you can use "%:z" in the format string. For 
earlier versions of Python, you need to do some string slicing.

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


Re: win32clipboard writing to clipboard on Windows 11

2024-06-17 Thread MRAB via Python-list

On 2024-06-17 20:27, Rob Cliffe via Python-list wrote:

Recently I acquired a new laptop running WIndows 11; my previous one
uses WIndows 10.  I encountered a strange problem:
I am using the win32clipboard backage (part of pywin32), and when I use
SetClipboardData() to write text which consists ***entirely of digits***
to the clipboard, I either get an error (not always the same error
message) or a program crash.  The problem does not appear if I use
SetClipboardText() instead.  The problem does not occur on my old
machine (where I used the feature extensively).

Sample program:

from win32clipboard import *
OpenClipboard()
SetClipboardData(CF_UNICODETEXT, "A")
SetClipboardData(CF_UNICODETEXT, "A0")
SetClipboardData(CF_UNICODETEXT, "0A")
SetClipboardText("0", CF_UNICODETEXT)
print("OK so far")
SetClipboardData(CF_UNICODETEXT, "0")
CloseClipboard()

Sample output:

OK so far
Traceback (most recent call last):
    File "C:\TEST*.PY", line 8, in 
      SetClipboardData(CF_UNICODETEXT, "0")
pywintypes.error: (0, 'SetClipboardData', 'No error message is available')

Can anyone shed light on this?
Best wishes
Rob Cliffe


I tried it on Windows 10 and got this:

>>> from win32clipboard import *
>>> OpenClipboard()
>>> SetClipboardData(CF_UNICODETEXT, "A")
1830508101640
>>> CloseClipboard()
>>> OpenClipboard()
>>> SetClipboardData(CF_UNICODETEXT, "0")
Traceback (most recent call last):
  File "", line 1, in 
pywintypes.error: (6, 'SetClipboardData', 'The handle is invalid.')
>>> CloseClipboard()

It looks like it's something to memory ownership:

https://stackoverflow.com/questions/1264137/how-to-copy-string-to-clipboard-in-c

If you're putting text on the clipboard, why not just use 
SetClipboardText()? That's what I do.

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


Re: Couldn't install numpy on Python 2.7

2024-06-12 Thread MRAB via Python-list

On 2024-06-12 17:31, AVI GROSS via Python-list wrote:

I am sure there is inertia to move from an older product and some people
need a reason like this where the old becomes untenable.

It seems Microsoft is having a problem where something lik 2/3 of Windows
users have not upgraded from Windows 10 after many years and have set a
deadline in a year or so for stopping updates. In that case, hardware was a
concern for some as Windows 11 did not work on their machines. With
upgrading python, the main concern is having to get someone to examine old
code and try to make it compatible.

In the case of Windows, my PC is over 10 years old yet performs 
perfectly well for my needs. It can't run Windows 11. Therefore, I'm in 
the process of migrating to Linux, and I still have over a year to 
achieve that before support ends.



But anyone doing new code in Python 2 in recent years should ...


Indeed...


-Original Message-
From: Python-list  On
Behalf Of Gordinator via Python-list
Sent: Wednesday, June 12, 2024 10:19 AM
To: python-list@python.org
Subject: Re: Couldn't install numpy on Python 2.7

On 12/06/2024 12:30, marc nicole wrote:

I am trying to install numpy library on Python 2.7.15 in PyCharm but the
error message I get is:

ERROR: Could not find a version that satisfies the requirement numpy (from

versions: none)
ERROR: No matching distribution found for numpy
c:\python27\lib\site-packages\pip\_vendor\urllib3\util\ssl_.py:164:
InsecurePlatformWarning: A true SSLContext object is not available. This
prevents urllib3 fro
m configuring SSL appropriately and may cause certain SSL connections to
fail. You can upgrade to a newer version of Python to solve this. For

more

information, see
https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
   InsecurePlatformWarning,



Any clues?


Why are you using Python 2? Come on, it's been 16 years. Ya gotta move
on at some point.


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


Re: in Python? -- Chunk -- (ChunkC '(a a b b b)), ==> ((a 2) (b 3))

2024-06-09 Thread MRAB via Python-list

On 2024-06-09 22:20, HenHanna via Python-list wrote:


Chunk, ChunkC -- nice simple way(s) to write these in Python?


(Chunk  '(a a   ba a a   b b))
  ==> ((a a) (b)  (a a a) (b b))


(Chunk  '(a a a a   b   c c   a a   d   e e e e))
  ==> ((a a a a) (b) (c c) (a a) (d) (e e e e))


(Chunk  '(2 2   foo   bar bar   j j j   k   baz baz))
  ==> ((2 2) (foo) (bar bar) (j j j) (k) (baz baz))

_

(ChunkC  '(a a   b b b))
   ==> ((a 2)  (b 3))

(ChunkC  '(a a   b  a a a   b b))
   ==> ((a 2)  (b 1)  (a 3)   (b 2))


You can make use of itertools.groupby.

--
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 MRAB via Python-list

On 2024-05-29 15:32, Thomas Passin via Python-list wrote:

On 5/29/2024 8:55 AM, Kevin M. Wilson wrote:
Please recall, I said the format for the email failed to retain the 
proper indents.

I'll attach a picture of the code!
Purpose; to uppercase every other letter in a string.

Thanks all, KMW


Simpler is good, and readability is good.  For a simple conversion that
has a little touch of generality:

s1 = 'this is a test'
def convert(i, ch):
  return ch.upper() if i % 2 else ch

result = ''.join([convert(i, ch) for i, ch in enumerate(s1)])
print(result)  # tHiS Is a tEsT


[snip]
Small mistake there. The original code converted to uppercase on even 
indexes, whereas your code does it on odd ones.



However, this has a weakness: what to do about spaces.  Should they be
counted among the characters to be uppercased? or should they not be
included in the count of the alternation?  If you want to uppercase
every other letter that is not a space, things become a little more
complicated.  And then do you want this to apply to all whitespace or
only spaces?

If you want to skip changing spaces, then you need to track the state of
converted characters in some way.  It would probably be easier (and more
readable) to use a "for x in t:" construction:

def convert(convert_this, ch):
  """Convert character ch if convert_this is True.
  Don't convert spaces.
  """
  if convert_this:
  if ch == ' ':
  return (convert_this, ch)
  elif convert_this:
  return (False, ch.upper())
  return (True, ch)

convert_next = False
result = ''
for ch in s1:
  convert_next, ch = convert(convert_next, ch)
  result += ch
print(result)  # tHiS Is A TeSt

There could be even more complications if you allow non-ascii characters
but you were asking about processing character by character so I won't
get into that.

(You haven't specified the problem in enough detail to answer questions
like those).


[snip]


--
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 MRAB via Python-list

On 2024-05-29 05:33, Kevin M. Wilson via Python-list wrote:

The following is my effort to understand how to process a string, letter, by 
letter:
def myfunc(name):        index = 0    howmax = len(name)    # while (index <= 
howmax):    while (index < howmax):        if (index % 2 == 0):            
print('letter to upper = {}, index {}!'.format(name[index], index))            name = 
name[index].upper()            print('if block {} and index {}'.format(name[index], 
index))        elif (index % 2 > 0):            print(index)            print('Start: 
elseif block, index is {}, letter is {}'.format(index, name))            # print('letter 
to lower = {}'.format(name[index]))            # print('Already lowercase do noting: 
name = {}'.format(name[index]))        index += 1        # index = name.upper()
     return name
myfunc('capitalism')
Error message:                        Not making sense, index is 1, letter s/b 
'a'letter to upper = c, index 0!
if block C and index 0
1
Start: elseif block, index is 1, letter is C
---
IndexErrorTraceback (most recent call last)
Cell In[27], line 21
  17 # index = name.upper()
  19 return name
---> 21 myfunc('capitalism')

Cell In[27], line 8, in myfunc(name)
   6 while (index < howmax):
   7 if (index % 2 == 0):
> 8 print('letter to upper = {}, index {}!'.format(name[index], 
index))
   9 name = name[index].upper()
  10 print('if block {} and index {}'.format(name[index], index))

IndexError: string index out of 
range***
So, I'm doing something... Stupid!!
***
"When you pass through the waters, I will be with you: and when you pass through the 
rivers, they will not sweep over you. When you walk through the fire, you will not be 
burned: the flames will not set you ablaze."
Isaiah 43:2


I think the code is this:

def myfunc(name):
index = 0
howmax = len(name)
# while (index <= howmax):
while (index < howmax):
if (index % 2 == 0):
print('letter to upper = {}, index {}!'.format(name[index], 
index))

name = name[index].upper()
print('if block {} and index {}'.format(name[index], index))
elif (index % 2 > 0):
print(index)
print('Start: elseif block, index is {}, letter is 
{}'.format(index, name))

# print('letter to lower = {}'.format(name[index]))
# print('Already lowercase do noting: name = 
{}'.format(name[index]))

index += 1
# index = name.upper()
return name

myfunc('capitalism')


What is:

name = name[index].upper()

meant to be doing?

What it's _actually_ doing is getting the character at a given index, 
converting it to uppercase, and then assigning it to `name`, so `name` 
is now 1 character long.


It doesn't this when 'index' is 0, so after the first iteration, `name` 
is a single-character string.


On the second iteration it raises IndexError because the string is only 
1 character long and you're asking for `name[1]`.


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


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

2024-05-19 Thread MRAB via Python-list

On 2024-05-19 19:13, Gilmeh Serda via Python-list wrote:

On Sun, 19 May 2024 08:32:46 +0100, Alan Gauld wrote:


I've honestly never experienced this "nightmare".
I install stuff and it just works.


Hear! Hear! Me too! And all that.

I'm on Manjaro, which is a tad finicky about other people touching its
Python since it's used for lots of things. I install things for myself
only.

Was there a reason they chose the name Pip?


[snip]
From https://pip.pypa.io/en/stable/:

"pip is the package installer for Python."

It's an acronym.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Version of NymPy

2024-05-15 Thread MRAB via Python-list

On 2024-05-15 19:42, Popov, Dmitry Yu via Python-list wrote:

What would be the easiest way to learn which version of NumPy I have with my 
Anaconda distribution?


Import numpy and print its '__version__' attribute.

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


Re: Running issues

2024-04-05 Thread MRAB via Python-list

On 2024-04-05 22: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.

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?

Any help you can offer is greatly appreciated. Thank you for your time.


Hope to hear from you soon.


That’s the installer. All it does is install the software.

There isn’t an IDE as such, although there is IDLE, which you should be 
able to find on the Start Menu under Python (assuming you’re using Windows).


There are a number of 3rd-party editors available that you can use when 
working with Python, or you can use Visual Studio Code from Microsoft.


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


Re: Can you help me with this memoization simple example?

2024-03-31 Thread MRAB via Python-list

On 2024-03-31 09:04, marc nicole wrote:

Thanks for the first comment which I incorporated

but when you say "You can't use a list as a key, but you can use a 
tuple as a key,

provided that the elements of the tuple are also immutable."

does it mean  the result of sum of the array is not convenient to use 
as key as I do?
Which tuple I should use to refer to the underlying list value as you 
suggest?



I was suggesting using `tuple` on the argument:

def memoize(f):
 cache = {}

 def g(*args):
 key = tuple(args[0]), args[1]

 if key not in cache:
 cache[key] = f(args[0], args[1])

 return cache[key]

 return g


Anything else is good in my code ?

Thanks

Le dim. 31 mars 2024 à 01:44, MRAB via Python-list 
 a écrit :


On 2024-03-31 00:09, marc nicole via Python-list wrote:
> I am creating a memoization example with a function that adds up
/ averages
> the elements of an array and compares it with the cached ones to
retrieve
> them in case they are already stored.
>
> In addition, I want to store only if the result of the function
differs
> considerably (passes a threshold e.g. 50 below).
>
> I created an example using a decorator to do so, the results
using the
> decorator is slightly faster than without the memoization which
is OK, but
> is the logic of the decorator correct ? anybody can tell me ?
>
> My code is attached below:
>
>
>
> import time
>
>
> def memoize(f):
>      cache = {}
>
>      def g(*args):
>          if args[1] == "avg":
>              sum_key_arr = sum(list(args[0])) / len(list(args[0]))

'list' will iterate over args[0] to make a list, and 'sum' will
iterate
over that list.

It would be simpler to just let 'sum' iterate over args[0].

>          elif args[1] == "sum":
>              sum_key_arr = sum(list(args[0]))
>          if sum_key_arr not in cache:
>              for (
>                  key,
>                  value,
>              ) in (
>                  cache.items()
>              ):  # key in dict cannot be an array so I use the
sum of the
> array as the key

You can't use a list as a key, but you can use a tuple as a key,
provided that the elements of the tuple are also immutable.

>                  if (
>                      abs(sum_key_arr - key) <= 50
>                  ):  # threshold is great here so that all
values are
> approximated!
>                      # print('approximated')
>                      return cache[key]
>              else:
>                  # print('not approximated')
>                  cache[sum_key_arr] = f(args[0], args[1])
>          return cache[sum_key_arr]
>
>      return g
>
>
> @memoize
> def aggregate(dict_list_arr, operation):
>      if operation == "avg":
>          return sum(list(dict_list_arr)) / len(list(dict_list_arr))
>      if operation == "sum":
>          return sum(list(dict_list_arr))
>      return None
>
>
> t = time.time()
> for i in range(200, 15000):
>      res = aggregate(list(range(i)), "avg")
>
> elapsed = time.time() - t
> print(res)
> print(elapsed)


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



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


Re: Can you help me with this memoization simple example?

2024-03-30 Thread MRAB via Python-list

On 2024-03-31 00:09, marc nicole via Python-list wrote:

I am creating a memoization example with a function that adds up / averages
the elements of an array and compares it with the cached ones to retrieve
them in case they are already stored.

In addition, I want to store only if the result of the function differs
considerably (passes a threshold e.g. 50 below).

I created an example using a decorator to do so, the results using the
decorator is slightly faster than without the memoization which is OK, but
is the logic of the decorator correct ? anybody can tell me ?

My code is attached below:



import time


def memoize(f):
 cache = {}

 def g(*args):
 if args[1] == "avg":
 sum_key_arr = sum(list(args[0])) / len(list(args[0]))


'list' will iterate over args[0] to make a list, and 'sum' will iterate 
over that list.


It would be simpler to just let 'sum' iterate over args[0].


 elif args[1] == "sum":
 sum_key_arr = sum(list(args[0]))
 if sum_key_arr not in cache:
 for (
 key,
 value,
 ) in (
 cache.items()
 ):  # key in dict cannot be an array so I use the sum of the
array as the key


You can't use a list as a key, but you can use a tuple as a key, 
provided that the elements of the tuple are also immutable.



 if (
 abs(sum_key_arr - key) <= 50
 ):  # threshold is great here so that all values are
approximated!
 # print('approximated')
 return cache[key]
 else:
 # print('not approximated')
 cache[sum_key_arr] = f(args[0], args[1])
 return cache[sum_key_arr]

 return g


@memoize
def aggregate(dict_list_arr, operation):
 if operation == "avg":
 return sum(list(dict_list_arr)) / len(list(dict_list_arr))
 if operation == "sum":
 return sum(list(dict_list_arr))
 return None


t = time.time()
for i in range(200, 15000):
 res = aggregate(list(range(i)), "avg")

elapsed = time.time() - t
print(res)
print(elapsed)



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


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

2024-03-30 Thread MRAB via Python-list

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 had a vague recollection of hearing it elsewhere (*Game of Thrones,* on
the armies' battle flags?), but didn't know what it meant. Google tells me:

*an inscribed or painted symbol considered to have magical power.*

So, they're more than just line noise. They confer power on their users...

Perhaps '@' in the context of decorators is the most prominent example in
Python, since decorators technically don't allow the programmer to do
something they couldn't before, but are now are used everywhere, a key
feature of many applications and modules.

Magical-ly, y'rs,


I wouldn't consider '@' to be a sigil any more than I would a unary minus.
In Perl there's the prefixes $ (scalar), @ (array) and % 
(hash/dictionary), but also & (function), although it's rare because 
there's also the () afterwards.


Variables in PHP have the prefix $ and only $.

In old versions of BASIC, string variables had the suffix $, and integer 
variables the suffix %. Some versions also had the suffix # (for double 
precision, I think).

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


Re: the name ``wheel''

2024-03-21 Thread MRAB via Python-list

On 2024-03-21 11:36, Johanne Fairchild via Python-list wrote:

Why is a whl-package called a ``wheel''?  Is it just a pronunciation for
the extension WHL or is it really a name?

Also, it seems that when I install Python on Windows, it doesn't come
with pip ready to run.  I had to say

   python -m ensurepip

and then I saw that a pip on a whl-package was installed.  Why doesn't
the official distribution make pip ready to run by default?  Thank you!


When I install Python on Windows, I always get pip by default, although 
it might not be on the system search path.


As it's recommended to use the Python Launcher py on Windows, I use that 
instead:


py -m pip install something

because it gives better support if you have multiple versions of Python 
installed.

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


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

2024-03-07 Thread MRAB via Python-list

On 2024-03-07 14: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?


If the value is a list, you can do list things to it.

If the value is a number, you can do number things to it.

If the value is a string, you can do string things to it.

And so on.

It's not mentioned in tutorials because it's not special. It just 
behaves how you'd expect it to behave.

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


Re: Can u help me?

2024-03-05 Thread MRAB via Python-list

On 2024-03-06 01: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).


There was an issue 3 years ago about renaming the installer for clarity:

https://github.com/python/cpython/issues/87322

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


Re: Can u help me?

2024-03-05 Thread MRAB via Python-list

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?
--
https://mail.python.org/mailman/listinfo/python-list


Re: Can u help me?

2024-03-05 Thread MRAB via Python-list

On 2024-03-06 00:06, Chano Fucks via Python-list wrote:

[image: image.png]


This list removes all images.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Problem resizing a window and button placement

2024-02-25 Thread MRAB via Python-list

On 2024-02-25 21:19, Steve GS via Python-list wrote:

SOLUTION FOUND!

The fix was to write the code that uses the width value and to place it into 
the function itself.
Kluge? Maybe but it works.

Mischief Managed.


As for the most recent suggestion, it fails for me:

Traceback (most recent call last):
   File "F:/___zInsulin Code A 08-02-23/WinPic/IOWw.pyw", line 14, in 
 print("Ww Outside = <" + str(Ww) > + ">")
TypeError: bad operand type for unary +: 'str'


It fails because there's a mistake. It should be:

print("Ww Outside = <" + str(Ww) + ">")


With the need to close the window, it adds an extra step and intervention to 
the program to use. I am not sure how this help[s.

As a curio, it would be interesting to see how to use the value of a variable, 
created in the function used here, and make it available to the code outside 
the function.


[snip]


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


Re: Problem resizing a window and button placement

2024-02-24 Thread MRAB via Python-list

On 2024-02-25 02:51, Steve GS wrote:

import tkinter as tk

#global Ww  Neither global helps
def on_configure(*args):
# print(args)
  #global Ww  Neither global helps
  Ww = root.winfo_width()
  print("WwInside = <" + str(Ww) + ">")

root = tk.Tk()
root.bind('', on_configure)
print("WwOutside = <" + str(Ww) + ">")
#NameError: name 'Ww' is not defined
root.mainloop()
'Ww' won't exist until 'on_configure' assigns to it, and that won't 
happen until `mainloop` starts.


Also, 'global' works only within a function.

8<

import tkinter as tk

def on_configure(event):
    print(f'{event.width=}, {event.height=}')

root = tk.Tk()
root.bind('',on_configure)
root.mainloop()

8<

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


Re: Problem resizing a window and button placement

2024-02-24 Thread MRAB via Python-list

On 2024-02-25 00:33, Steve GS via Python-list wrote:

"Well, yes, in Python a
variable created inside a
function or method is local to
that function unless you
declare it global."

Yes, I knew that. I tried to
global it both before the
function call and within it.
Same for when I created the
variable. If I try to use it
in the rest of the code, it
keeps coming up as not
declared.  In other functions,
I can 'return' the variable
but that apparently would not
work for this function.

Is this type of function any
different that that which I
have been using?


Please post a short example that shows the problem.

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


Re: Problem resizing a window and button placement

2024-02-23 Thread MRAB via Python-list

On 2024-02-24 01:14, Steve GS via Python-list wrote:

Python, Tkinter: How do I
determine if a window has been
resized? I want to locate
buttons vertically along the
right border and need to know
the new width. The buttons are
to move with the change of
location of the right-side
border.


Bind an event handler for '':

8<

import tkinter as tk

def on_configure(*args):
print(args)

root = tk.Tk()
root.bind('', on_configure)
root.mainloop()

8<

Are you placing the buttons yourself? I always use layouts and they 
handle such things automatically.


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


Re: Using __new__

2024-02-17 Thread MRAB via Python-list

On 2024-02-17 22:35, Jonathan Gossage via Python-list wrote:

I am attempting to use the __new__ method in the following code:
class SingletonExample(object):

 _instance = None

 def __new__(cls, **kwargs):
 if cls._instance is None:
 cls._instance = super().__new__(cls, **kwargs)
 return cls._instance

 def __init__(self, **kwargs) -> None:
 our_attributes = ('h', 'x')
 if kwargs is not None:
 for k, v in kwargs.items():
 if k in our_attributes:
 setattr(self, k, v)

a = SingletonExample(h=1)

and I get the following result:

(PRV) jonathan@jfgdev:/PR$ python -m Library.Testing.test2
Traceback (most recent call last):
   File "", line 198, in _run_module_as_main
   File "", line 88, in _run_code
   File "/mnt/ProgrammingRenaissance/Library/Testing/test2.py", line 16, in

 a = SingletonExample(h=1)
 ^
   File "/mnt/ProgrammingRenaissance/Library/Testing/test2.py", line 6, in
__new__
 cls._instance = super().__new__(cls, **kwargs)
 ^^
TypeError: object.__new__() takes exactly one argument (the type to
instantiate)

I am quite puzzled as it looks as if this code will not work if the
super-class is 'object'. Any suggestions on how to proceed?


Don't pass kwargs to object.__new__ because it doesn't expect it.

Incidentally, kwargs will never be None, and there's no point in giving 
a return type for __init__ because it can only ever return None.

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


Re: A question about import

2024-02-16 Thread MRAB via Python-list

On 2024-02-16 20:07, Gabor Urban via Python-list wrote:

Hi guys,

I need something about modules to be clarified.

Suppose I have written a module eg: ModuleA which imports an other
module, let us say the datetime.

If I import ModuleA in a script, will be datetime imported automatically?


Yes. When a module is imported it can import other modules.
--
https://mail.python.org/mailman/listinfo/python-list


Re: test-ignore

2024-02-15 Thread MRAB via Python-list

On 2024-02-16 00:29, Skip Montanaro via Python-list wrote:


> Test post to see if my Newsgroup post program is working.

Aim your test messages at alt.test, please.



I agree that basic Usenet connectivity messages should go to alt.test. It's
not clear from the original post, but if the poster's aim was to see if
posts to comp.lang.python traverse the gateway and show up on this list,
then alt.test won't help.

True, but did the poster really need to send another one to say "yes, 
that worked"?

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


Re: Error pd.set_option('display.width', 10000)

2024-02-03 Thread MRAB via Python-list

On 2024-02-03 23:02, gelukt gelukt via Python-list wrote:

Dear,

While running a code, I get the error below:
What does this error mean? How can I fix this error?

C:\Users\brech\Desktop\Crypto\venv\Scripts\python.exe 
"C:/Users/brech/Desktop/Crypto/Project/aaa Arbitrage.py"
Traceback (most recent call last):
   File "C:\Users\brech\Desktop\Crypto\Project\aaa Arbitrage.py", line 458, in 

 methode()
   File "C:\Users\brech\Desktop\Crypto\Project\aaa Arbitrage.py", line 49, in 
methode
 wb.sheets[website]['A' + str(1+a)].value = 
inputString[startIndex:startIndex + 3]
 
   File "C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\xlwings\main.py", 
line 2411, in value
 conversion.write(data, self, self._options)
   File 
"C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\xlwings\conversion\__init__.py",
 line 102, in write
 pipeline(ctx)
   File 
"C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\xlwings\conversion\framework.py",
 line 79, in __call__
 stage(*args, **kwargs)
   File 
"C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\xlwings\conversion\standard.py",
 line 75, in __call__
 self._write_value(ctx.range, ctx.value, scalar)
   File 
"C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\xlwings\conversion\standard.py",
 line 63, in _write_value
 rng.raw_value = value
 ^
   File "C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\xlwings\main.py", 
line 1973, in raw_value
 self.impl.raw_value = data
 ^^^
   File 
"C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\xlwings\_xlwindows.py", 
line 1209, in raw_value
 self.xl.Value = data
 ^
   File 
"C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\xlwings\_xlwindows.py", 
line 161, in __setattr__
 return setattr(self._inner, key, value)

   File 
"C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\win32com\client\__init__.py",
 line 597, in __setattr__
 self._oleobj_.Invoke(*(args + (value,) + defArgs))
pywintypes.com_error: (-2147352567, 'Er is een uitzondering opgetreden.', (0, 
None, None, None, 0, -2147024882), None)

Process finished with exit code 1


There's a question on StackOverflow that looks similar:

https://stackoverflow.com/questions/72223654/pywintypes-com-error-2147352567-exception-occured-0-none-none-none-0

Something to do with the cell format.

Check which cell it i, what value it's trying to put there, and whether 
the format of the cell and the value are compatible.

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


Re: How to create a binary tree hierarchy given a list of elements as its leaves

2024-01-28 Thread MRAB via Python-list

On 2024-01-28 18:16, marc nicole via Python-list wrote:

So I am trying to build a binary tree hierarchy given numerical elements
serving for its leaves (last level of the tree to build). From the leaves I
want to randomly create a name for the higher level of the hierarchy and
assign it to the children elements. For example: if the elements inputted
are `0,1,2,3` then I would like to create firstly 4 elements (say by random
giving them a label composed of a letter and a number) then for the second
level (iteration) I assign each of 0,1 to a random name label (e.g. `b1`)
and `2,3` to another label (`b2`) then for the third level I assign a
parent label to each of `b1` and `b2` as `c1`.

An illustation of the example is the following tree:


[image: tree_exp.PNG]

This list strips images, and discussion has mostly moved to 
https://discuss.python.org.


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


Re: Extract lines from file, add to new files

2024-01-11 Thread MRAB via Python-list

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.

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


Re: >>> %matplotlib inline results in SyntaxError: invalid syntax

2023-12-25 Thread MRAB via Python-list

On 2023-12-25 19:53, Alan Gauld via Python-list wrote:

On 25/12/2023 05:34, geetanajali homes via Python-list wrote:

import numpy as np 
import pandas as pd 
import random 
import matplotlib.pyplot as plt 
%matplotlib inline 

I get an error on the last line. I am running this code in Idle Python 
3.4.4 Shell... 


Python names can't start with a % (its the modulo or
string formatting operator).

I know nothing of the innards of matplotlib so I can only
suggest a closer examination of their tutorial information.


I believe it's a feature of Jupyter specifically. It won't work in IDLE.
--
https://mail.python.org/mailman/listinfo/python-list


Re: IDLE editor suggestion.

2023-12-12 Thread MRAB via Python-list

On 2023-12-13 01:28, Steve GS via Python-list wrote:

Does anything from the Visual Studio family of software have a pull down menu 
that lists previous searches so that I don’t have to enter them every time?

SGA

Visual Studio search box has a dropdown list that's shown when you press 
the down arrow key.



-Original Message-
From: Friedrich Romstedt 
Sent: Tuesday, December 12, 2023 12:52 PM
To: Steve GS 
Cc: python-list@python.org
Subject: Re: IDLE editor suggestion.

Hi!

Am Di., 12. Dez. 2023 um 09:28 Uhr schrieb Steve GS via Python-list
:


Maybe this already exists but
I have never seen it in any
editor that I have used.


You might want to choose Microsoft Code from its Visual Studio family of 
software, or, if you're ready for a deep dive, you might try using vim. 
Personally I am using both.

HTH,
Friedrich



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


Re: IDLE editor suggestion.

2023-12-12 Thread MRAB via Python-list

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.
--
https://mail.python.org/mailman/listinfo/python-list


Re: How to enter multiple, similar, dictionaries?

2023-12-11 Thread MRAB via Python-list

On 2023-12-11 15:57, Chris Green via Python-list wrote:

Chris Green  wrote:

Is there a way to abbreviate the following code somehow?

lv = {'dev':'bbb', 'input':'1', 'name':'Leisure volts'}
sv = {'dev':'bbb', 'input':'0', 'name':'Starter volts'}
la = {'dev':'bbb', 'input':'2', 'name':'Leisure Amps'}
sa = {'dev':'bbb', 'input':'3', 'name':'Starter Amps'}
bv = {'dev':'adc2', 'input':0, 'name':'BowProp Volts'}

It's effectively a 'table' with columns named 'dev', 'input' and
'name' and I want to access the values of the table using the variable
name.


Or, more sensibly, make the above into a list (or maybe dictionary)
of dictionaries:-

adccfg = [
 {'abbr':'lv', 'dev':'bbb', 'input':'1', 'name':'Leisure volts'},
 {'abbr':'sv', 'dev':'bbb', 'input':'0', 'name':'Starter volts'},
 {'abbr':'la', 'dev':'bbb', 'input':'2', 'name':'Leisure Amps'},
 {'abbr':'sa', 'dev':'bbb', 'input':'3', 'name':'Starter Amps'},
 {'abbr':'bv', 'dev':'adc2', 'input':0, 'name':'BowProp Volts'}
]

This pickles nicely, I just want an easy way to enter the data!


I could, obviously, store the data in a database (sqlite), I have some
similar data in a database already but the above sort of format in
Python source is more human readable and accessible.  I'm just looking
for a less laborious way of entering it really.


How about:

keys = ['abbr', 'dev', 'input', 'name']
adccfg = [
('lv', 'bbb', '1', 'Leisure volts'),
('sv', 'bbb', '0', 'Starter volts'),
('la', 'bbb', '2', 'Leisure Amps'),
('sa', 'bbb', '3', 'Starter Amps'),
('bv', 'adc2', '0', 'BowProp Volts'),
]
adccfg = [dict(zip(keys, row)) for row in adccfg]

or even:

keys = ['abbr', 'dev', 'input', 'name']
adccfg = '''\
lv,bbb,1,Leisure volts
sv,bbb,0,Starter volts
la,bbb,2,Leisure Amps
sa,bbb,3,Starter Amps
bv,adc2,0,BowProp Volts
'''
adccfg = [dict(zip(keys, line.split(','))) for line in adccfg.splitlines()]

--
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-06 Thread MRAB via Python-list

On 2023-12-06 20:11, dn via Python-list wrote:

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

On 2023-12-06 12:23, Thomas Passin via Python-list wrote:

On 12/6/2023 6:35 AM, Barry Scott via Python-list wrote:



On 6 Dec 2023, at 09:32, Chris Green via Python-list 
 wrote:


My requirement is *slightly* more complex than just key value pairs,
it has one level of hierarchy, e.g.:-

    KEY1:
  a: v1
  c: v3
  d: v4
    KEY2:
  a: v7
  b: v5
  d: v6

Different numbers of value pairs under each KEY.


JSON will allow you to nest dictionaries.

{
 'KEY1': {
 'a': v1
 'c': v3
 'd': v4
 }
 'KEY2': {
  'a': v7
  'b': v5
  'd': v6
 }
}

Personally I would not use .ini style these days as the format does 
not include type of the data.


Neither does JSON.  Besides, JSON is more complicated than necessary
here - in fact, your example isn't even legal JSON since lines are
missing commas.

Fun fact - for at least some, maybe most, JSON files, using eval() on
them is hugely faster than using Python's standard JSON library.  I
learned this when I wanted to ingest a large browser bookmarks JSON
file. It wouldn't matter for a much smaller file, of course.


It would be safer if you used literal_eval.


Ah, memories of Python2...

Does this little hack still work?

What about True/False cf true/false?


Nope, nor None cf null.

If it's numbers, strings, lists and dicts, it works.

--
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-06 Thread MRAB via Python-list

On 2023-12-06 12:23, Thomas Passin via Python-list wrote:

On 12/6/2023 6:35 AM, Barry Scott via Python-list wrote:




On 6 Dec 2023, at 09:32, Chris Green via Python-list  
wrote:

My requirement is *slightly* more complex than just key value pairs,
it has one level of hierarchy, e.g.:-

KEY1:
  a: v1
  c: v3
  d: v4
KEY2:
  a: v7
  b: v5
  d: v6

Different numbers of value pairs under each KEY.


JSON will allow you to nest dictionaries.

{
 'KEY1': {
 'a': v1
 'c': v3
 'd': v4
 }
 'KEY2': {
  'a': v7
  'b': v5
  'd': v6
 }
}

Personally I would not use .ini style these days as the format does not include 
type of the data.


Neither does JSON.  Besides, JSON is more complicated than necessary
here - in fact, your example isn't even legal JSON since lines are
missing commas.

Fun fact - for at least some, maybe most, JSON files, using eval() on
them is hugely faster than using Python's standard JSON library.  I
learned this when I wanted to ingest a large browser bookmarks JSON
file. It wouldn't matter for a much smaller file, of course.


It would be safer if you used literal_eval.
--
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 MRAB via Python-list

On 2023-12-05 14: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?

Some kind of key/value store sounds like the correct solution. I 
wouldn't go as far a database - that's overkill for a few calibration 
values.


I might suggest TOML, except that Python's tomllib (Python 3.11+) is 
read-only!


Personally, I'd go for lines of:

key1: value1
key2: value2

Simple to read, simple to write.

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


Re: Code improvement question

2023-11-17 Thread MRAB via Python-list

On 2023-11-17 09:38, jak via Python-list wrote:

Mike Dewhirst ha scritto:

On 15/11/2023 10:25 am, MRAB via Python-list wrote:

On 2023-11-14 23:14, Mike Dewhirst via Python-list wrote:

I'd like to improve the code below, which works. It feels clunky to me.

I need to clean up user-uploaded files the size of which I don't know in
advance.

After cleaning they might be as big as 1Mb but that would be super rare.
Perhaps only for testing.

I'm extracting CAS numbers and here is the pattern xx-xx-x up to
xxx-xx-x eg., 1012300-77-4

def remove_alpha(txt):

      """  r'[^0-9\- ]':

      [^...]: Match any character that is not in the specified set.

      0-9: Match any digit.

      \: Escape character.

      -: Match a hyphen.

      Space: Match a space.

      """

  cleaned_txt = re.sub(r'[^0-9\- ]', '', txt)

      bits = cleaned_txt.split()

      pieces = []

      for bit in bits:

      # minimum size of a CAS number is 7 so drop smaller clumps 
of digits


      pieces.append(bit if len(bit) > 6 else "")

      return " ".join(pieces)


Many thanks for any hints


Why don't you use re.findall?

re.findall(r'\b[0-9]{2,7}-[0-9]{2}-[0-9]{2}\b', txt)


I think I can see what you did there but it won't make sense to me - or 
whoever looks at the code - in future.


That answers your specific question. However, I am in awe of people who 
can just "do" regular expressions and I thank you very much for what 
would have been a monumental effort had I tried it.


That little re.sub() came from ChatGPT and I can understand it without 
too much effort because it came documented


I suppose ChatGPT is the answer to this thread. Or everything. Or will be.

Thanks

Mike


I respect your opinion but from the point of view of many usenet users
asking a question to chatgpt to solve your problem is truly an overkill.
The computer world overflows with people who know regex. If you had not
already had the answer with the use of 're' I would have sent you my
suggestion that as you can see it is practically identical. I am quite
sure that in this usenet the same solution came to the mind of many
people.

with open(file) as fp:
  try: ret = re.findall(r'\b\d{2,7}\-\d{2}\-\d{1}\b', fp.read())
  except: ret = []

The only difference is '\d' instead of '[0-9]' but they are equivalent.


Bare excepts are a very bad idea.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Code improvement question

2023-11-16 Thread MRAB via Python-list

On 2023-11-17 01:15, Mike Dewhirst via Python-list wrote:

On 15/11/2023 3:08 pm, MRAB via Python-list wrote:

On 2023-11-15 03:41, Mike Dewhirst via Python-list wrote:

On 15/11/2023 10:25 am, MRAB via Python-list wrote:

On 2023-11-14 23:14, Mike Dewhirst via Python-list wrote:
I'd like to improve the code below, which works. It feels clunky to 
me.


I need to clean up user-uploaded files the size of which I don't 
know in

advance.

After cleaning they might be as big as 1Mb but that would be super 
rare.

Perhaps only for testing.

I'm extracting CAS numbers and here is the pattern xx-xx-x up to
xxx-xx-x eg., 1012300-77-4

def remove_alpha(txt):

      """  r'[^0-9\- ]':

      [^...]: Match any character that is not in the specified set.

      0-9: Match any digit.

      \: Escape character.

      -: Match a hyphen.

      Space: Match a space.

      """

  cleaned_txt = re.sub(r'[^0-9\- ]', '', txt)

      bits = cleaned_txt.split()

      pieces = []

      for bit in bits:

      # minimum size of a CAS number is 7 so drop smaller 
clumps of digits


      pieces.append(bit if len(bit) > 6 else "")

      return " ".join(pieces)


Many thanks for any hints


Why don't you use re.findall?

re.findall(r'\b[0-9]{2,7}-[0-9]{2}-[0-9]{2}\b', txt)


I think I can see what you did there but it won't make sense to me - or
whoever looks at the code - in future.

That answers your specific question. However, I am in awe of people who
can just "do" regular expressions and I thank you very much for what
would have been a monumental effort had I tried it.

That little re.sub() came from ChatGPT and I can understand it without
too much effort because it came documented

I suppose ChatGPT is the answer to this thread. Or everything. Or 
will be.



\b  Word boundary
[0-9]{2,7}  2..7 digits
-   "-"
[0-9]{2}    2 digits
-   "-"
[0-9]{2}    2 digits
\b  Word boundary

The "word boundary" thing is to stop it matching where there are 
letters or digits right next to the digits.


For example, if the text contained, say, "123456789-12-1234", you 
wouldn't want it to match because there are more than 7 digits at the 
start and more than 2 digits at the end.



Thanks

I know I should invest some brainspace in re. Many years ago at a Perl
conferenceI did buy a coffee mug completely covered with a regex cheat
sheet. It currently holds pens and pencils on my desk. And spiders now I
look closely!

Then I took up Python and re is different.

Maybe I'll have another look ...

The patterns themselves aren't that different; Perl's just has more 
features than the re module's.

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


Re: Code improvement question

2023-11-14 Thread MRAB via Python-list

On 2023-11-15 03:41, Mike Dewhirst via Python-list wrote:

On 15/11/2023 10:25 am, MRAB via Python-list wrote:

On 2023-11-14 23:14, Mike Dewhirst via Python-list wrote:

I'd like to improve the code below, which works. It feels clunky to me.

I need to clean up user-uploaded files the size of which I don't know in
advance.

After cleaning they might be as big as 1Mb but that would be super rare.
Perhaps only for testing.

I'm extracting CAS numbers and here is the pattern xx-xx-x up to
xxx-xx-x eg., 1012300-77-4

def remove_alpha(txt):

      """  r'[^0-9\- ]':

      [^...]: Match any character that is not in the specified set.

      0-9: Match any digit.

      \: Escape character.

      -: Match a hyphen.

      Space: Match a space.

      """

  cleaned_txt = re.sub(r'[^0-9\- ]', '', txt)

      bits = cleaned_txt.split()

      pieces = []

      for bit in bits:

      # minimum size of a CAS number is 7 so drop smaller clumps 
of digits


      pieces.append(bit if len(bit) > 6 else "")

      return " ".join(pieces)


Many thanks for any hints


Why don't you use re.findall?

re.findall(r'\b[0-9]{2,7}-[0-9]{2}-[0-9]{2}\b', txt)


I think I can see what you did there but it won't make sense to me - or
whoever looks at the code - in future.

That answers your specific question. However, I am in awe of people who
can just "do" regular expressions and I thank you very much for what
would have been a monumental effort had I tried it.

That little re.sub() came from ChatGPT and I can understand it without
too much effort because it came documented

I suppose ChatGPT is the answer to this thread. Or everything. Or will be.


\b  Word boundary
[0-9]{2,7}  2..7 digits
-   "-"
[0-9]{2}2 digits
-   "-"
[0-9]{2}2 digits
\b  Word boundary

The "word boundary" thing is to stop it matching where there are letters 
or digits right next to the digits.


For example, if the text contained, say, "123456789-12-1234", you 
wouldn't want it to match because there are more than 7 digits at the 
start and more than 2 digits at the end.


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


Re: Code improvement question

2023-11-14 Thread MRAB via Python-list

On 2023-11-14 23:14, Mike Dewhirst via Python-list wrote:

I'd like to improve the code below, which works. It feels clunky to me.

I need to clean up user-uploaded files the size of which I don't know in
advance.

After cleaning they might be as big as 1Mb but that would be super rare.
Perhaps only for testing.

I'm extracting CAS numbers and here is the pattern xx-xx-x up to
xxx-xx-x eg., 1012300-77-4

def remove_alpha(txt):

      """  r'[^0-9\- ]':

      [^...]: Match any character that is not in the specified set.

      0-9: Match any digit.

      \: Escape character.

      -: Match a hyphen.

      Space: Match a space.

      """

  cleaned_txt = re.sub(r'[^0-9\- ]', '', txt)

      bits = cleaned_txt.split()

      pieces = []

      for bit in bits:

      # minimum size of a CAS number is 7 so drop smaller clumps of digits

      pieces.append(bit if len(bit) > 6 else "")

      return " ".join(pieces)


Many thanks for any hints


Why don't you use re.findall?

re.findall(r'\b[0-9]{2,7}-[0-9]{2}-[0-9]{2}\b', txt)

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


Re: xor operator

2023-11-13 Thread MRAB via Python-list

On 2023-11-13 21:03, Barry via Python-list wrote:




On 13 Nov 2023, at 17:48, Dom Grigonis  wrote:

Short circuiting happens, when:
xor([True, True, False, False], n=1)
At index 1 it is clear that the answer is false.


Can you share an example with 4 values that is true?
And explain why it is xor.

I think what the OP wants is something that stops after finding n true 
items.


It's a more general form of what 'any' and 'all' do - 'any' stops when 
it finds 1 true item and 'all' stops when it finds 1 false item.


In general, you might want to stop when you find n true items or n false 
items, or whatever.


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


Re: Beep on WIndows 11

2023-11-12 Thread MRAB via Python-list

On 2023-11-12 11:16, Chris Angelico via Python-list wrote:

On Sun, 12 Nov 2023 at 21:27, Y Y via Python-list
 wrote:


I am curious and humble to ask: What is the purpose of a BEEP?



There are several purposes. I can't say which of these are relevant to
the OP, but some or all of them could easily be.

* A very very simple notification that can be triggered by any program
* An audio cue that is not routed to your regular audio system (good
if you use headphones but are AFK)
* An extremely low level signal that requires little-to-no processing power
* An emergency signal that does not even require a CPU (probably not
in this instance though!)
* Imitating a pre-existing audio signal that works by beeping

Depending on what's needed, a more complex system might suffice (for
example, I cover the first two points by having an entire separate
audio subsystem with its own dedicated speakers, which I can invoke
using VLC in a specific configuration); but a basic beep is definitely
of value. I suspect in this situation that the first point is
important here, but it's up to the OP to elaborate.

(Note that the "no CPU emergency sound" option usually requires a
motherboard-mounted speaker or speaker header, which not all have
these days. Sad.)


Recently, I wanted a program to beep.

In the old days, with a BBC micro, that was simple. It had 3 tone 
channels and 1 white noise channel, with control over frequency, 
duration and volume, beeps on different channels could be synchronised 
to start at the same time, there was a sound queue so that the SOUND 
command returned immediately, and there was an ENVELOPE command for 
controlling the attack, decay, sustain and release. All this on an 8-bit 
machine!


My current PC is way more powerful. 64-bit processor, GBs of RAM, etc. 
Python offers winsound.Beep. 1 tone, no volume control, and it blocks 
while beeping.

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


Re: fCONV_AUSRICHTG is not defined - Why?

2023-11-07 Thread MRAB via Python-list

On 2023-11-07 20:56, Thomas Passin via Python-list wrote:

On 11/7/2023 3:29 PM, MRAB via Python-list wrote:

On 2023-11-07 19:20, Jim Schwartz via Python-list wrote:
Where do you define fCONV_AUSRICHTG? It must be initialized or defined 
somewhere. Did you leave out a statement from the python 2 version?



It's given its value here:

     (
     fNAME,
     fLG1,
     fLG2,
     fTYP,
     fCONV_AUSRICHTG,
     fENTRY_AUSRICHTG,
     fTEXT_AUSRICHTUNG,
     fHOLFUNKT,
     fPRUEFFUNKT,
     fPRUEF_ARG,
     ) = list(range(10))



This construction is a sneaky way to assign index numbers to list
entries.  A simplified example:

  >>> S1 = 'string 1'
  >>> S2 = 'string 2'
  >>> (fS1, fS2) = list(range(2))
  >>> fS1
0
  >>>
  >>> fS2
1


You don't need the 'list', though: range(...) will work on its own.

[snip]

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


Re: fCONV_AUSRICHTG is not defined - Why?

2023-11-07 Thread MRAB via Python-list

On 2023-11-07 19:20, Jim Schwartz via Python-list wrote:

Where do you define fCONV_AUSRICHTG? It must be initialized or defined 
somewhere. Did you leave out a statement from the python 2 version?


It's given its value here:

(
fNAME,
fLG1,
fLG2,
fTYP,
fCONV_AUSRICHTG,
fENTRY_AUSRICHTG,
fTEXT_AUSRICHTUNG,
fHOLFUNKT,
fPRUEFFUNKT,
fPRUEF_ARG,
) = list(range(10))




On Nov 7, 2023, at 1:06 PM, Thomas Passin via Python-list 
 wrote:

On 11/7/2023 12:47 PM, Egon Frerich via Python-list wrote:

I've no idea why this happens. In a module there are lists and definitions:
Felder = [
# Name   lg1  lg2 typ   Ausrichtung Holen Prüfen Prüfvorg
["Jahr", 4, 5, "u", "", "right", "center"],
["Monat", 2, 5, "u", "", "right", "center"],
["Tag", 2, 3, "u", "", "right", "center"],
["Belegnr", 5, 7, "s", "", "right", "center"],
["Bank", 2, 4, "u", "", "center", "center"],
["Art", 2, 3, "u", "", "center", "center"],
["Aufg", 2, 4, "u", "", "center", "center"],
["Text", 25, 25, "s", "-", "left", "left"],
["Ergänzung", 12, 12, "s", "-", "left", "left"],
["Betrag", 13, 13, "s", "", "right", "right"],
["W", 1, 2, "s", "", "center", "center"],
["WBetrag", 7, 7, "s", "", "right", "right"],
["Kurs", 6, 6, "s", "", "right", "right"],
]
"Reihenfolge in der Dimension 1"
(
fJAHR,
fMONAT,
fTAG,
fBELEGNR,
fBANK,
fART,
fAUFGABE,
fTEXT,
fTEXTERG,
fBETRAG,
fWAEHRUNG,
fBETRAGinWAEHRUNG,
fUMRECHNUNGSKURS,
) = list(range(13))
"Reihenfolge in der Dimension 2"
(
fNAME,
fLG1,
fLG2,
fTYP,
fCONV_AUSRICHTG,
fENTRY_AUSRICHTG,
fTEXT_AUSRICHTUNG,
fHOLFUNKT,
fPRUEFFUNKT,
fPRUEF_ARG,
) = list(range(10))
Two lines with  test statements follow and the statement which produces an 
error:
print(Felder)
print(fJAHR, fNAME, fTYP, fCONV_AUSRICHTG)
akette = "%" + "%".join(
["%s%s%s " % (i[fCONV_AUSRICHTG], i[fLG2], i[fTYP]) for i in Felder])
The traceback shows:
$ python3 testGeldspurGUI.py
[['Jahr', 4, 5, 'u', '', 'right', 'center'], ['Monat', 2, 5, 'u', '', 'right', 
'center'], ['Tag', 2, 3, 'u', '', 'right', 'center'], ['Belegnr', 5, 7, 's', 
'', 'right', 'center'], ['Bank', 2, 4, 'u', '', 'center', 'center'], ['Art', 2, 
3, 'u', '', 'center', 'center'], ['Aufg', 2, 4, 'u', '', 'center', 'center'], 
['Text', 25, 25, 's', '-', 'left', 'left'], ['Ergänzung', 12, 12, 's', '-', 
'left', 'left'], ['Betrag', 13, 13, 's', '', 'right', 'right'], ['W', 1, 2, 
's', '', 'center', 'center'], ['WBetrag', 7, 7, 's', '', 'right', 'right'], 
['Kurs', 6, 6, 's', '', 'right', 'right']]
0 0 3 4
Traceback (most recent call last):
  File "/home/egon/Entw/Geldspur/geldspur/testGeldspurGUI.py", line 15, in 

from tests.testU2 import testU2
  File "/home/egon/Entw/Geldspur/geldspur/tests/testU2.py", line 9, in 
from gui.GUI_Konfig import GUIcfg
  File "/home/egon/Entw/Geldspur/geldspur/gui/GUI_Konfig.py", line 11, in 

class GUIcfg:
  File "/home/egon/Entw/Geldspur/geldspur/gui/GUI_Konfig.py", line 90, in GUIcfg
["%s%s%s " % (i[fCONV_AUSRICHTG], i[fLG2], i[fTYP]) for i in Felder])
  File "/home/egon/Entw/Geldspur/geldspur/gui/GUI_Konfig.py", line 90, in 

["%s%s%s " % (i[fCONV_AUSRICHTG], i[fLG2], i[fTYP]) for i in Felder])
NameError: name 'fCONV_AUSRICHTG' is not defined
You see "Felder" and with "0 0 3 4" the correct value 4 for fCONV_AUSRICHTG. 
But there is the NameError.
What does  mean? Is there a change from python2 to python3?


You are using a syntax that I don't understand, but "listcomp" means a list 
comprehenson.



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


Re: fCONV_AUSRICHTG is not defined - Why?

2023-11-07 Thread MRAB via Python-list

On 2023-11-07 18:30, dn via Python-list wrote:

On 08/11/2023 06.47, Egon Frerich via Python-list wrote:

I've no idea why this happens. In a module there are lists and definitions:

...


     ["%s%s%s " % (i[fCONV_AUSRICHTG], i[fLG2], i[fTYP]) for i in Felder])
   File "/home/egon/Entw/Geldspur/geldspur/gui/GUI_Konfig.py", line 90, 
in 

     ["%s%s%s " % (i[fCONV_AUSRICHTG], i[fLG2], i[fTYP]) for i in Felder])
NameError: name 'fCONV_AUSRICHTG' is not defined

You see "Felder" and with "0 0 3 4" the correct value 4 for 
fCONV_AUSRICHTG. But there is the NameError.


What does  mean? Is there a change from python2 to python3?


Works for me (Python 3.11 on Fedora-Linux 37)
- both as a script, and simple/single import.

What happens when you extract the second dimension's definitions into a
module of their own, and import that (with/out less-sophisticated join)?


The missing detail is this line from the traceback:

   File "/home/egon/Entw/Geldspur/geldspur/gui/GUI_Konfig.py", line 11,
in 
 class GUIcfg:

Here's a small example that shows the problem:

8<
#!python3.11
# -*- encoding: utf-8 -*-

class Test:
hello = "hello"
print(hello)
print([[zero] for _ in range(4)])
8<

and its traceback:

8<
hello
Traceback (most recent call last):
  File "C:\Projects\regex3\test_clipboard.py", line 4, in 
class Test:
  File "C:\Projects\regex3\test_clipboard.py", line 7, in Test
print([zero for _ in range(4)])
 ^^
  File "C:\Projects\regex3\test_clipboard.py", line 7, in 
print([zero for _ in range(4)])
   
NameError: name 'zero' is not defined
8<

'zero' is visible in:

print(hello)

but not in:

print([zero for _ in range(4)])

Something to do with how scoping is implemented in comprehensions?

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


Re: Writing to clipboard in Python 3.11

2023-11-07 Thread MRAB via Python-list

On 2023-11-06 00:51, Rob Cliffe via Python-list wrote:

Recently I switched from Python 3.8.3 to Python 3.11.4.  A strange
problem appeared which was not there before:
I am using the win32clipboard backage (part of pywin32), and when I use
SetClipboardData() to write text which consists ENTIRELY OF DIGITS to
the clipboard, I either get an error (not always the same error message)
or a program crash.  The problem does not appear if I use
SetClipboardText() instead.
Sample program:

from win32clipboard import *
OpenClipboard()
SetClipboardData(CF_UNICODETEXT, "A")
SetClipboardData(CF_UNICODETEXT, "A0")
SetClipboardData(CF_UNICODETEXT, "0A")
SetClipboardText("0", CF_UNICODETEXT)
print("OK so far")
SetClipboardData(CF_UNICODETEXT, "0")
CloseClipboard()

Sample output:

OK so far
Traceback (most recent call last):
    File "R:\W.PY", line 8, in 
      SetClipboardData(CF_UNICODETEXT, "0")
pywintypes.error: (0, 'SetClipboardData', 'No error message is available')

I can get round the problem by using SetClipboardText().  But can anyone
shed light on this?


It also happens in Python 3.10, but not Python 3.9.

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


Re: Checking if email is valid

2023-11-06 Thread MRAB via Python-list

On 2023-11-06 08:57, Simon Connah via Python-list wrote:



I can see how the truley dim-witted might forget that other countries
have phone numbers with differing lengths and formatting/punctuation,
but there are tons of sites where it takes multiple tries when
entering even a bog-standard USA 10-0digit phone nubmer because they
are completely flummuxed by an area code in parens or hyphens in the
usual places (or lack of hyhpens in the usual places). This stuff
isn't that hard, people...


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? And 
not accepting your mobile number in the landline number field is just when I 
give up. Or having a landline only field that does not accept mobile phones.


I have a landline. It's also how I access the internet.
--
https://mail.python.org/mailman/listinfo/python-list


Re: PyInstaller value error: Invalid Windows resource specifier

2023-10-30 Thread MRAB via Python-list

On 2023-10-30 19:19, McDermott Family via Python-list wrote:

Hello, I am trying to create a one file executable with pyinstaller 6.1.0
and auto-py-to-exe 2.41.0 using Python version 3.10.9 in a virtual
environment.

Some points before the output of pinstaller is shown. My resource .py file
is there where it should be. Also I can fun my program from the command-line


and it does work with the compiled resource file without a problem. Any help
would be greatly appreciated. Thank you.


Running auto-py-to-exe v2.41.0

Building directory: C:\Users\icnte\AppData\Local\Temp\tmpp870eytg

Provided command: pyinstaller --noconfirm --onefile --windowed --icon
"D:/Work/Python/cfepy310/xl/cfegui/Resources/Conform-e_48_1.ico" --name
"Conform-e" --clean --log-level "DEBUG" --debug "all" --version-file
"D:/Work/Python/cfepy310/xl/cfegui/cfe_versionfile.txt" --resource
"D:/Work/Python/cfepy310/xl/cfegui/cfe_Resource_rc.py"
"D:/Work/Python/cfepy310/xl/cfegui/cfe_MainForm.py"

Recursion Limit is set to 5000

Executing: pyinstaller --noconfirm --onefile --windowed --icon
D:/Work/Python/cfepy310/xl/cfegui/Resources/Conform-e_48_1.ico --name
Conform-e --clean --log-level DEBUG --debug all --version-file
D:/Work/Python/cfepy310/xl/cfegui/cfe_versionfile.txt --resource
D:/Work/Python/cfepy310/xl/cfegui/cfe_Resource_rc.py
D:/Work/Python/cfepy310/xl/cfegui/cfe_MainForm.py --distpath
C:\Users\icnte\AppData\Local\Temp\tmpp870eytg\application --workpath
C:\Users\icnte\AppData\Local\Temp\tmpp870eytg\build --specpath
C:\Users\icnte\AppData\Local\Temp\tmpp870eytg


[snip]


ValueError: Invalid Windows resource specifier
'D:WorkPythoncfepy310xlcfeguicfe_Resource_rc.py'!
For arbitrary data file, the format is 'filename,type,name,[language]'!

  


Project output will not be moved to output folder

Complete.


In the docs for "--resource" it says:

"""FILE can be a data file or an exe/dll. For data files, at least TYPE 
and NAME must be specified."""


That might be the problem, but I haven't been able to find out what 
"TYPE" means!


I also wonder whether "--add-data" would work.

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


Re: How to write list of integers to file with struct.pack_into?

2023-10-02 Thread MRAB via Python-list

On 2023-10-01 23:04, Jen Kris via Python-list wrote:
>
> Iwant to write a list of 64-bit integers to a binary file. 
Everyexample I have seen in my research convertsit to .txt, but I want 
it in binary.  I wrote this code,based on some earlier work I have done:

>
> buf= bytes((len(qs_array)) * 8)
>
> foroffset in range(len(qs_array)):
>
> item_to_write= bytes(qs_array[offset])
>
> struct.pack_into(buf,"
> ButI get the error "struct.error: embedded null character."
>
> Maybethere's a better way to do this?
>
You can't pack into a 'bytes' object because it's immutable.

The simplest solution I can think of is:

buf = struct.pack("<%sQ" % len(qs_array), *qs_array)
--
https://mail.python.org/mailman/listinfo/python-list


Re: error of opening Python

2023-09-26 Thread MRAB via Python-list

On 2023-09-27 03:30, Chris Roy-Smith via Python-list wrote:

On 26/9/23 22:27, Abdelkhelk ashref salay eabakh via Python-list wrote:

Dear Python team,

This is my not first time using Python, I tried to launch Python and it showed


I'm no expert but

"Python 3.11.3 (tags/v3.11.3:f3909b8, Apr  4 2023, 23:49:59) [MSC v.1934 64 bit 
(AMD64)] on win

surely running a 64 bit version of python in a 23mbit version of windows
will cause significant problems!


It says "win32" even on 64-bit Windows.

If you try to run 64-bit Python on 32-bit Windows, it won't get as far 
as printing that header!



try the correct python or windows

regards,




Type "help", "copyright", "credits" or "license" for more information." I
don't know what this meant and how to fix this. Could you please help me?
Thank you very much.

Kind regards






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


Re: The GIL and PyEval_RestoreThread

2023-09-26 Thread MRAB via Python-list

On 2023-09-26 14:20, Peter Ebden via Python-list wrote:

Hi all,

I've been working on embedding Python and have an interesting case around
locking with PyEval_RestoreThread which wasn't quite doing what I expect,
hoping someone can explain what I should expect here.

I have a little example (I'm running this in parallel from two different
threads; I have some more C code for that but I don't think it's super
interesting):

void run_python(PyThreadState* thread) {
   LOG("Restoring thread %p...", thread);
   PyEval_RestoreThread(thread);
   LOG("Restored thread %p", thread);
   PyRun_SimpleString("import time; print('sleeping'); time.sleep(3.0)");
   LOG("Saving thread...");
   PyThreadState* saved_thread = PyEval_SaveThread();
   LOG("Saved thread %p", saved_thread);
}

This produces output like
11:46:48.110058893: Restoring thread 0xabc480...
11:46:48.110121656: Restored thread 0xabc480
11:46:48.110166060: Restoring thread 0xabc480...
sleeping
11:46:48.110464194: Restored thread 0xabc480
sleeping
11:46:51.111307541: Saving thread...
11:46:51.111361075: Saved thread 0xabc480
11:46:51.113116633: Saving thread...
11:46:51.113177605: Saved thread 0xabc480

The thing that surprises me is that both threads seem to be able to pass
PyEval_RestoreThread before either reaches the corresponding
PyEval_SaveThread call, which I wasn't expecting to happen; I assumed that
since RestoreThread acquires the GIL, that thread state would remain locked
until it's released.

I understand that the system occasionally switches threads, which I guess
might well happen with that time.sleep() call, but I wasn't expecting the
same thread to become usable somewhere else. Maybe I am just confusing
things by approaching the same Python thread from multiple OS threads
concurrently and should be managing my own locking around that?

Storing the result of PyEval_SaveThread in a local variable looks wrong 
to me.


In the source for the regex module, I release the GIL with 
PyEval_SaveThread and save its result. Then, when I want to claim the 
GIL, I pass that saved value to PyEval_RestoreThread.


You seem to be releasing the GIL and discarding the result, so which 
thread are you resuming when you call PyEval_RestoreThread?


It looks like you're resuming the same thread twice. As it's already 
resumed the second time, no wonder it's not blocking!


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


Re: Tkinter ttk Treeview binding responds to past events!

2023-09-12 Thread MRAB via Python-list

On 2023-09-13 00:40, John O'Hagan via Python-list wrote:

On Tue, 2023-09-12 at 20:51 +0200, Mirko via Python-list wrote:

Am 12.09.23 um 07:43 schrieb John O'Hagan via Python-list:

> My issue is solved, but I'm still curious about what is happening
> here.

MRAB already said it: When you enter the callback function, Tk's 
mainloop waits for it to return. So what's happening is:


1. Tk's mainloop pauses
2. temp_unbind() is called
3. TreeviewSelect is unbound
4. events are queued
5. TreeviewSelect is bound again
6. temp_unbind() returns
7. Tk's mainloop continues with the state:
 - TreeviewSelect is bound
 - events are queued

[. . .]


Thanks (also to others who have explained), now I get it!


FWIW, here's a version without after(), solving this purely on the 
python side, not by temporarily unbinding the event, but by 
selectively doing nothing in the callback function.


from tkinter import *
from tkinter.ttk import *

class Test:
 def __init__(self):
 self.inhibit = False
 root=Tk()
 self.tree = Treeview(root)
 self.tree.pack()
 self.iid = self.tree.insert('', 0, text='test')
 Button(root, command=self.temp_inhibit).pack()
 mainloop()

 def callback(self, *e):
 if not self.inhibit:
 print('called')

 def temp_inhibit(self):
 self.inhibit = True
 self.tree.selection_set(self.iid)
 self.tree.selection_remove(self.iid)
 self.tree.selection_set(self.iid)
 self.inhibit = False
 self.callback()

c=Test()




I like this solution better - it's much more obvious to me what it's
doing.

That code is not binding at all, it's just calling 'temp_inhibit' when 
the button is clicked.


You can remove all uses of self.inhibit and rename 'temp_inhibit' to 
something more meaningful, like 'delete_item'.


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


Re: Tkinter ttk Treeview binding responds to past events!

2023-09-12 Thread MRAB via Python-list

On 2023-09-12 19:51, Mirko via Python-list wrote:

Am 12.09.23 um 07:43 schrieb John O'Hagan via Python-list:


My issue is solved, but I'm still curious about what is happening here.


MRAB already said it: When you enter the callback function, Tk's
mainloop waits for it to return. So what's happening is:

1. Tk's mainloop pauses
2. temp_unbind() is called
3. TreeviewSelect is unbound
4. events are queued
5. TreeviewSelect is bound again
6. temp_unbind() returns
7. Tk's mainloop continues with the state:
- TreeviewSelect is bound
- events are queued

Am 11.09.23 um 23:58 schrieb Rob Cliffe:


Indeed.  And you don't need to specify a delay of 100 milliseconds. 0 will work 
(I'm guessing that's because queued actions are performed in the order that 
they were queued).


Ah, nice, didn't know that!

Well, strictly speaking, it's the order in which they were queued except 
for .after, which will be postponed if you specify a positive delay.


[snip]

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


Re: Tkinter ttk Treeview binding responds to past events!

2023-09-12 Thread MRAB via Python-list

On 2023-09-12 06:43, John O'Hagan via Python-list wrote:

On Mon, 2023-09-11 at 22:25 +0200, Mirko via Python-list wrote:

Am 11.09.23 um 14:30 schrieb John O'Hagan via Python-list:
> I was surprised that the code below prints 'called' three times.
> 
> 
> from tkinter import *

> from tkinter.ttk import *
> 
> root=Tk()
> 
> def callback(*e):

>      print('called')
> 
> tree = Treeview(root)

> tree.pack()
> 
> iid = tree.insert('', 0, text='test')
> 
> tree.selection_set(iid)

> tree.selection_remove(iid)
> tree.selection_set(iid)
> 
> tree.bind('<>', callback)
> 
> mainloop()
> 
> In other words, selection events that occurred _before_ the

> callback
> function was bound to the Treeview selections are triggering the
> function upon binding. AFAIK, no other tk widget/binding
> combination
> behaves this way (although I haven't tried all of them).
> 
> This was a problem because I wanted to reset the contents of the

> Treeview without triggering a relatively expensive bound function,
> but
> found that temporarily unbinding didn't prevent the calls.
> 
> I've worked around this by using a regular button-click binding for

> selection instead, but I'm curious if anyone can cast any light on
> this.
> 
> Cheers
> 
> John



AFAIK (it's been quite some time, since I used Tk/Tkinter):

These selection events are not triggered upon binding, but after the 
mainloop has startet. Tk's eventloop is queue-driven, so the 
tree.selection_{set,remove}() calls just place the events on the 
queue. After that, you setup a callback and when the mainloop 
starts, it processes the events from the queue, executing the 
registered callback.


I seem to remember, that I solved a similar issue by deferring the 
callback installation using root.after().



from tkinter import *
from tkinter.ttk import *

root=Tk()

def callback(*e):
 print('called')

tree = Treeview(root)
tree.pack()

iid = tree.insert('', 0, text='test')

tree.selection_set(iid)
tree.selection_remove(iid)
tree.selection_set(iid)

root.after(100, lambda: tree.bind('<>', callback))

mainloop()



This does not print "called" at all after startup (but still selects 
the entry), because the callback has not been installed when the 
mainloop starts. But any subsequent interaction with the list 
(clicking) will print it (since the callback is then setup).


HTH



Thanks for your reply. However, please see the example below, which is
more like my actual use-case. The selection events take place when a
button is pressed, after the mainloop has started but before the
binding. This also prints 'called' three times.

from tkinter import *
from tkinter.ttk import *

class Test:

def __init__(self):
   root=Tk()
   self.tree = Treeview(root)
   self.tree.pack()
   self.iid = self.tree.insert('', 0, text='test')
   Button(root, command=self.temp_unbind).pack()
   mainloop()

def callback(self, *e):
   print('called')

def temp_unbind(self):

   self.tree.unbind('<>')
   self.tree.selection_set(self.iid)
   self.tree.selection_remove(self.iid)
   self.tree.selection_set(self.iid)
   self.tree.bind('<>', self.callback)
   #self.tree.after(0, lambda: self.tree.bind('<>',
   self.callback))
   
c=Test()


It seems the events are still queued, and then processed by a later
bind?

However, your solution still works, i.e. replacing the bind call with
the commented line. This works even with a delay of 0, as suggested in
Rob Cliffe's reply. Does the call to after clear the event queue
somehow?

My issue is solved, but I'm still curious about what is happening here.


Yes, it's still queuing the events.
When an event occurs, it's queued.

So, you unbound and then re-bound the callback in temp_unbind?

Doesn't matter.

All that matters is that on returning from temp_unbind to the main event 
loop, there are events queued and there's a callback registered, so the 
callback is invoked.


Using the .after trick queues an event that will re-bind the callback 
_after_ the previous events have been handled.

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


Re: Forward References

2023-09-03 Thread MRAB via Python-list

On 2023-09-03 21:43, Jonathan Gossage via Python-list wrote:

I am attempting to use forward references in my program and I am failing.
This also does not work with the older way of putting the name of a class
as a string. Here is some sample code:

from __future__ import annotations

from dataclasses import dataclass
from typing import TypeAlias


ColorDef: TypeAlias = RGB | int | str



@dataclass(frozen=True, slots=True)
class RGB(object):

Can anyone suggest how I should fix this without reversing the statement
order?

 pass

The usual way to deal with forward type references is to use a string 
literal, i.e. 'RGB', but that doesn't work with '|', so use typing.Union 
instead:


from typing import TypeAlias, Union

ColorDef: TypeAlias = Union['RGB', int, str]

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


Re: Passing info to function used in re.sub

2023-09-03 Thread MRAB via Python-list

On 2023-09-03 17:10, Jan Erik Moström via Python-list wrote:

I'm looking for some advice for how to write this in a clean way

I want to replace some text using a regex-pattern, but before creating 
replacement text I need to some file checking/copying etc. My code right now 
look something like this:

def fix_stuff(m):
# Do various things that involves for info
# that what's available in m
replacement_text = m.group(1) + global_var1 + global_var2
return replacement_text

and the call comes here

global_var1 = "bla bla"
global_var2 = "pff"

new_text = re.sub(im_pattern,fix_stuff,md_text)


The "problem" is that I've currently written some code that works but it uses 
global variables ... and I don't like global variables. I assume there is a better way to 
write this, but how?


You could use pass an anonymous function (a lambda) to re.sub:

def fix_stuff(m, var1, var2):
# Do various things that involves for info
# that what's available in m
replacement_text = m.group(1) + var1 + var2
return replacement_text

global_var1 = "bla bla"
global_var2 = "pff"

new_text = re.sub(im_pattern, lambda m, var1=global_var1, 
var2=global_var2: fix_stuff(m, var1, var2), md_text)


Or, if you prefer a named function, define one just before the re.sub:

def fix_stuff(m, var1, var2):
# Do various things that involves for info
# that what's available in m
replacement_text = m.group(1) + var1 + var2
return replacement_text

global_var1 = "bla bla"
global_var2 = "pff"

def fix_it(m, var1=global_var1, var2=global_var2):
return fix_stuff(m, var1, var2)

new_text = re.sub(im_pattern, fix_it, md_text)

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


Re: Setup-tools

2023-07-15 Thread MRAB via Python-list

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.


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


Re: Trouble with defaults and timeout decorator

2023-06-24 Thread MRAB via Python-list

On 2023-06-24 17:18, Jason Friedman via Python-list wrote:

I'm writing a database connectivity module to be used by other modules and
leveraging the jaydebeapi module.
  From what I can tell jaydebeapi contains no built-in timeout capability, so
then I turned to https://pypi.org/project/timeout-decorator/.
My goal is to have a default timeout of, say, 10 seconds, which can be
overridden by the caller.


import jaydebeapi
from timeout_decorator import timeout

class Database:
 database_connection = None
 database_name, user_name, password, host, port = stuff
 timeout = None

 def __init__(self, timeout=10):
 self.timeout = timeout

 @timeout(self.timeout)
 def get_connection(self):
 if not self.database_connection:
 self.database_connection = jaydebeapi.connect(some_args)
 return self.database_connection


The trouble occurs on line 12 with:
NameError: name 'self' is not defined


The decorator is applied when the class is defined, but 'self' exists 
only in 'Database.__init__' and 'Database.get_connection' when they are 
called.


Have you tried applying the decorator "manually" in 'Database.__init__'?

def __init__(self, timeout=10):
self.timeout = timeout
self.get_connection = timeout(self.timeout)(self.get_connection)

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


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

2023-06-07 Thread MRAB via Python-list

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 have also attempted to run the
'get-pip.py' installation script from the command line, but it did not work
either.

I am aware that 'pip' is typically installed automatically with Python, but
I am encountering this persistent difficulty. Therefore, I would like to
request your assistance and expertise in resolving this 'pip' installation
issue. I would like to be able to use 'pip' to manage my Python packages
efficiently.

I am open to any suggestions and steps you can provide to help me resolve
this problem. Please note that I am a user on the Windows operating system.

Thank you sincerely for your attention and support. I eagerly await your
guidance to resolve this situation.


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: Fwd: Problems Installing and getting started.

2023-05-31 Thread MRAB

On 2023-05-31 08:34, Mark Bass wrote:

-- Forwarded message -
From: Mark Bass 
Date: Wed, 31 May 2023 at 08:09
Subject: Problems Installing and getting started.
To: 


Good morning,

I installed python several hours ago (from python.org), I then installed
the IDE PyCharm. I'm using AI to help with a project that requires
statistical analysis.
I cannot open python, when I double clicked a "Modify Setup" window
appeared with the three options Modify, Repair and Uninstall to click. I
assumed this was part of the final installation process and clicked Modify
- it seemed to be successful. I still could not open python. I asked the AI
and it suggested to click Repair, this still made no difference. I finally
Uninstalled it, shut down my laptop, had a coffee then re-installed it but
the same problem occurred.
Can you help ? Any suggestions?
I'm really pleased with the AI so far  and looking forward to using Python
to get my project started.

What do you mean by "open python"? You said that a "Modify Setup" window 
appeared, which sounds like you're clicking on the *installer*.


To make it clear, the file that you download from python.org is the 
installer. It installs Python only. It's not an IDE.


Having said that, the standard distribution from python.org does come 
with IDLE.


You should be running PyCharm that you installed; that's the IDE. You 
just need to ensure that it's using the version of Python that you've 
installed.

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


Re: Module error

2023-05-26 Thread MRAB

On 2023-05-27 01:30, giuseppacef...@gmail.com wrote:

I have reinstalled python which reinstalls pip.  I have added the
path:'C:\sers\Giuseppa\AppData\Local\Packages\PythonSoftwareFoundation.Pytho
n.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\Scripts and still
get the error below. Could you help me with this please?

  


Traceback (most recent call last):

   File "C:\Users\Giuseppa\Documents\DataScience\PYTHON\Subsetting.py", line
11, in 

 import pandas as pd

ModuleNotFoundError: No module named 'pandas'


Have you tried re-installing pandas?
--
https://mail.python.org/mailman/listinfo/python-list


Re: "Invalid literal for int() with base 10": is it really a literal?

2023-05-26 Thread MRAB

On 2023-05-26 09:29, Chris Angelico wrote:

On Fri, 26 May 2023 at 17:56, Roel Schroeven  wrote:


Kevin M. Wilson's post "Invalid literal for int() with base 10?" got me
thinking about the use of the word "literal" in that message. Is it
correct to use "literal" in that context? It's correct in something like
this:

 >>> int('invalid')
Traceback (most recent call last):
   File "", line 1, in 
ValueError: invalid literal for int() with base 10: 'invalid'

But something like this generates the same message:

 >>> int(input())
hello
Traceback (most recent call last):
   File "", line 1, in 
ValueError: invalid literal for int() with base 10: 'hello'

In cases like this there is no literal in sight.

I'm thinking it would be more correct to use the term 'value' here:
ValueError: invalid value for int() with base 10: 'hello'
Does my reasoning make sense?



It's a ValueError, so the problem is with the value. I suppose
"invalid notation" might work, but since the definition of what's
acceptable to the int() constructor is the same as for a Python
literal, it's not wrong to use that word.

However, if you want to change the wording, I'd be more inclined to
synchronize it with float():


float("a")

Traceback (most recent call last):
   File "", line 1, in 
ValueError: could not convert string to float: 'a'


You still need to mention the base because:

>>> int('y', 36)
34

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


Re: Invalid literal for int() with base 10?

2023-05-25 Thread MRAB

On 2023-05-25 22:30, Kevin M. Wilson via Python-list wrote:

Ok, I'm not finding any info. on the int() for converting a str to an int (that specifies 
a base parameter)?! The picture is of the code I've written... And the base 10 paradigm 
involved?? years = int('y') # store for calculationValueError: invalid literal for int() 
with base 10: 'y'What is meant by "invalid literal"? I'm trying to convert srt 
to int, and I didn't know I needed to specify the base. Plus I haven't read anything that 
I need to specify the base for the int().


'12' is a string that contains 2 digits, which together represent the 
number 12. 'y' is a string that contains a letter, which doesn't 
represent a number.


Perhaps what you meant is that y is a variable that contains a string, 
in which case what you want is int(y).



Attached is the code, showing the code and the execution of said code.


There's no code attached; this list automatically strips attachmentments.

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


Re: Does os.path relpath produce an incorrect relative path?

2023-05-25 Thread MRAB

On 2023-05-25 16:53, Eryk Sun wrote:

On 5/25/23, BlindAnagram  wrote:


vcx_path = 'C:\\build.vs22\\lib\\lib.vcxproj'
src_path = 'C:\\lib\\src\\'
rel_path = '..\\..\\..\\lib\\src'

[snip]

The first of these three results produces an incorrect relative path
because relpath does not strip off any non-directory tails before
comparing paths.


The start path is assumed to be a directory, which defaults to the
current working directory, and the input paths are first resolved as
absolute paths. In order to reach src_path from vcx_path, one has to
traverse 3 levels up to the root directory.

https://docs.python.org/3/library/os.path.html#os.path.relpath


Well, it's not necessarily the optimal relative path, because it's not 
always necessary to go all the way up to the root, as in the first example.

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


Re: where is requests

2023-05-23 Thread MRAB

On 2023-05-24 01:14, Rich Osborne wrote:

I have install Python 3.11.3 but my import requests does not work. I found 
documentation that refers to C:\python35 but I am on 3.11.3. Where do I find 
requests?

It's not part of the standard library. You can import it using pip. If 
you're on Windows, the recommended method is o use the Python Launcher 
and the pip module from a Command Prompt window:


py -m pip install requests

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


Re: Learning tkinter

2023-05-18 Thread MRAB

On 2023-05-12 09:55, Rob Cliffe via Python-list wrote:

I am trying to learn tkinter.
Several examples on the internet refer to a messagebox class
(tkinter.messagebox).
But:

Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32
bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
  >>> import tkinter
  >>> tkinter.messagebox
Traceback (most recent call last):
    File "", line 1, in 
AttributeError: module 'tkinter' has no attribute 'messagebox'
  >>>

Why is this?


It's a submodule of tkinter:

>>> import tkinter.messagebox as mb
>>> mb.showinfo


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


Re: Using loguru in a library

2023-05-01 Thread MRAB

On 2023-04-30 16:40, Roy Hann wrote:

Is there anyone using loguru (loguru 0.5.3 in my case) successfully in a
library?


In my __init__.py in mylib I do

   logger.disable('mylib')

which definitely works. I don't get any more logging.

I "pip install ." the library, then in mytest.py I do

   import mylib
   logger.enable('mylib')

expecting that it would report any log messages above level DEBUG, just
as it does when I don't disable logging. Unfortunately it doesn't
have any effect; it doesn't report any logging from mylib.

I have verified that __name__ is visible in the library and is 'mylib'.

I would also have expected that logger.enable(None) would turn all the
logging on everywhere but it seems not.

I have probably misunderstood how logger.enable() is supposed to be
used. Can anyone share a brief example?


According to the docs, the argument is the name of the module.

In your example, the name of the module (i.e. file) is "__init__"; 
"mylib" is the name of the package.

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


Re: How to 'ignore' an error in Python?

2023-04-28 Thread MRAB

On 2023-04-28 16:55, Chris Green wrote:

I'm sure I'm missing something obvious here but I can't see an elegant
way to do this.  I want to create a directory, but if it exists it's
not an error and the code should just continue.

So, I have:-

 for dirname in listofdirs:
 try:
 os.mkdir(dirname)
 except FileExistsError:
 # so what can I do here that says 'carry on regardless'
 except:
 # handle any other error, which is really an error

 # I want code here to execute whether or not dirname exists


Do I really have to use a finally: block?  It feels rather clumsy.

I suppose I could test if the directory exists before the os.mkdir()
but again that feels a bit clumsy somehow.

I suppose also I could use os.mkdirs() with exist_ok=True but again
that feels vaguely wrong somehow.


I'd do this:

from contextlib import suppress

for dirname in listofdirs:
with suppress(FileExistsError):
os.mkdir(dirname)

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


Re: Fwd: pip is not installed

2023-04-16 Thread MRAB

On 2023-04-16 21:54, Khoinguyen Nguyen wrote:

To whom it may concern,
I have tried to reinstall, repair, and run in command prompt, but it seems
as though pip won't install. I am using Windows 10 and Python 3.11.3. Are
there any other suggestions for troubleshooting?
Thank you.


Have you tried using pip via the Python Launcher?

py -m pip

That's installed by default by the installer from python.org.

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


Re: Problem with Matplotlib example

2023-04-13 Thread MRAB

On 2023-04-13 19:41, Martin Schöön wrote:

Anyone had success running this example?
https://tinyurl.com/yhhyc9r

When I try I get this error:
"TypeError: __init__() got an unexpected keyword argument 'transform'"

This is for the line
"m = MarkerStyle(SUCESS_SYMBOLS[mood], transform=t)"

Yes, I know, I could dive into the documentation myself but I hope
some kind soul here will help out.

As far as I know I have an up-to-date matplotlib installed. Pip has
nothing more modern to offer me.


All I can say is that it works for me!

Python 3.10 and 3.11, matplotlib 3.6.1 and then 3.7.1 after updating it.

--
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, avi.e.gr...@gmail.com  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 MRAB

On 2023-04-13 03:12, avi.e.gr...@gmail.com 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: python-list@python.org
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: 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: 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: Windows installer from python source code without access to source code

2023-04-06 Thread MRAB

On 2023-04-06 23:14, Jim Schwartz wrote:

Could someone please help Carlos?  I’m not sure how to answer his
question

Sent from my iPhone

  On Apr 6, 2023, at 3:53 PM, Carlos Fulqueris  wrote:

  
  Hello Jim,
  How can I unsubscribe to this email list?
  I'm waiting for your response.
  Thanks
  Carlos

[snip]
At the bottom of the post is a link to the page that explains how to 
unsubscribe. It's the link:



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


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


Re: Patrick Sheehan: Major Issues with Python

2023-03-26 Thread MRAB

On 2023-03-25 20:03, Patrick Sheehan wrote:

Hello,
I have been working with the attached book (See photo) to try to learn
Python and so far it has been a complete nightmare trying to get python
installed and operating correctly.  I have received a plethora of error
messages and consulted youtube videos and chat groups to try to remedy the
issues.  I am using a computer that is running Windows 10.  I have
installed, and un-installed several versions of Python and was able to
complete the first two lessons in the attached book, but could not complete
lesson 3 (Turtledemo)...Some of the error messages I have received
include:  "This app cannot run on your PC"; "Unable to initialize device
PRN"; “Python is not recognized as an internal or external command”:
"Python was not found: run without arguments to install from Microsoft
Store, or disable this shortcut from settings mange, app execution
aliases:"...I have been at this for 4 days now at least three hours each
day...Any information or help you can provide would be greatly
appreciated.  Additionally, I do have PyCharm installed (As you can tell, I
am a beginner), is PyCharm the same thing as Python?  Thank you in advance!

This list strips attachments such as images, so I don't know which book 
you're referring to.


I'd go for Python 3.11 and the installer "Windows installer (64-bit)" at 
https://www.python.org/downloads/release/python-3112/, i.e. 
"https://www.python.org/ftp/python/3.11.2/python-3.11.2-amd64.exe"; 
(assuming that it's a 64-bit PC).
To run Python, the recommended way is to use the Python Launcher, py.exe 
(so type "py my_program.py" in a Command window), or just double-click 
on it if it's a GUI program.


As for PRN, that's the printer. Does anyone use PRN these days?

And, no, PyCharm is not the same thing as Python. PyCharm is an IDE 
(integrated development environment) for Python, but Python is its own 
thing.

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


Re: Debugging reason for python running unreasonably slow when adding numbers

2023-03-20 Thread MRAB

On 2023-03-20 15:21, Edmondo Giovannozzi wrote:


> def sum1(): 
> s = 0 
> for i in range(100): 
> s += i 
> return s 
> 
> def sum2(): 
> return sum(range(100))
Here you already have the numbers you want to add. 


Actually using numpy you'll be much faster in this case:

§ import numpy as np
§ def sum3():
§return np.arange(1_000_000, dtype=np.int64).sum()

On my computer sum1 takes 44 ms, while the numpy version just 2.6 ms
One problem is that sum2 gives the wrong result. This is why I used np.arange 
with dtype=np.int64.

sum2 evidently doesn't uses the python "big integers" e restrict the result to 
32 bits.


On my computer they all give the same result, as I'd expect.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Fwd: Friday finking: IDE 'macro expansions'

2023-03-17 Thread MRAB

On 2023-03-17 17:55, Thomas Passin wrote:

On 3/17/2023 1:13 PM, Alan Gauld wrote:

Oops! I meant to send this to the group not just Dave.


 Forwarded Message 

On 16/03/2023 22:55, dn via Python-list wrote:


Do you make use of your IDE's expansionist tendencies, and if-so, which
ones?


When I'm writing Java/C++/C# yes, I need all the IDE help I can get.
Netbeans or Eclipse being my tools of choice. And in my Windows days
I used Delphi and Smalltalk/V which both pretty much only exist within
their own IDEs and I used their features extensively.


Back when Delphi first came out, when I first used it, I don't remember
any IDE; one just used a text editor.


I used Turbo Pascal and then Delphi 3 or 4, back when it was still Borland.


When writing Python I use IDLE, or vim for bigger jobs.
IDLE does have some suggestions and auto tricks but I don't
always use them. In vim I use auto-indent and that's about it.



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


Re: How to exit program with custom code and custom message?

2023-03-13 Thread MRAB

On 2023-03-14 03:29, Thomas Passin wrote:

On 3/13/2023 10:34 PM, scruel tao wrote:

Lars:

I totally understand your reasoning here, but in some way it
follows the unix philosophy: Do only one thing, but do that good.



I understand, python is not strongly typed, so `sys.exit` will be
able to accept any types parameters rather than just integer. In
order to handle such “other” types logic, I think this function
already violated the unix philosophy, and there is no way to avoid
it.


Most Python folks will say the Python *is* fairly strongly typed, but
for a different definition of "type". That is, duck typing.

It's strongly typed but not statically typed, unless you count type 
hints, which are optional.

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


Re: =- and -= snag

2023-03-13 Thread MRAB

On 2023-03-14 00:28, Gary Herron wrote:


On 3/13/23 2:26 PM, morp...@gmail.com wrote:

Hi.

I was working in Python today, and sat there scratching my head as the
numbers for calculations didn't add up.  It went into negative numbers,
when that shouldn't have been possible.

Turns out I had a very small typo, I had =- instead of -=.

Isn't it unpythonic to be able to make a mistake like that?

Regards,

Morten



These all mean the same thing, but I don't see a good way to designate
the second or third as an error.


x = -5
x=-5
x =- 5

The third one could be picked up as suspicious by a linter due to its 
unusual spacing.

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


Re: Python installation not full and python not working 3.11.0

2023-03-10 Thread MRAB

On 2023-03-10 23:27, Jan Vasko wrote:

Hello all,


I would like to ask you for help. I have been using Python 3.8 for almost 2 
years and I decided to update to 3.11. Initially everything was correct. But at 
some point Windows shows me that Python is being reinstalled (I don't have a 
message print screen ..), but from that time I cannot run Python at all on my 
PC.

So I tried to reinstall it several times with no success. All the time I receive this 
"The system cannot find the file 
C:\Users...\AppData\Local\Programs\Python\Python311\python.exe."
But files are there:
[cid:image001.png@01D953B0.4E12E170]
Even when I try to run "python.exe" directly I receive this error:
[cid:image002.png@01D953B0.4E12E170]

System Variables are right (added it to both PATH):
1) User Variables:
[cid:image003.png@01D953B0.4E12E170]

2) System Variables
[cid:image004.png@01D953B0.4E12E170]

Strange thing is that after RE-Installing Python the "pip.exe" is missing in subfolder 
"Python/Scripts/" (it is simply empty - not installed but I mark pip to be installed):
[cid:image005.png@01D953B0.4E12E170]

I tried also Repair - no success.

Details:
System: Windows 10 (21H2)
Python: 3.11.0 (full 64bit installer from python.org)

   *   Downloaded from: Python Release Python 3.11.0 | 
Python.org

cmd:
[cid:image006.png@01D953B0.4E12E170]

This is resulting that I cannot use interpreter in VS Code and continue 
development. Any one Any Idea? Thank you

This list is text-only; images are automatically stripped. Please copy 
and paste any relevant text that they might contain.

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


Re: Cutting slices

2023-03-05 Thread MRAB

On 2023-03-06 00:28, dn via Python-list wrote:

On 06/03/2023 11.59, aapost wrote:

On 3/5/23 17:43, Stefan Ram wrote:

   The following behaviour of Python strikes me as being a bit
   "irregular". A user tries to chop of sections from a string,
   but does not use "split" because the separator might become
   more complicated so that a regular expression will be required
   to find it. But for now, let's use a simple "find":
|>>> s = 'alpha.beta.gamma'
|>>> s[ 0: s.find( '.', 0 )]
|'alpha'
|>>> s[ 6: s.find( '.', 6 )]
|'beta'
|>>> s[ 11: s.find( '.', 11 )]
|'gamm'
|>>>

   . The user always inserted the position of the previous find plus
   one to start the next "find", so he uses "0", "6", and "11".
   But the "a" is missing from the final "gamma"!
   And it seems that there is no numerical value at all that
   one can use for "n" in "string[ 0: n ]" to get the whole
   string, isn't it?




I would agree with 1st part of the comment.

Just noting that string[11:], string[11:None], as well as string[11:16] 
work ... as well as string[11:324242]... lol..


To expand on the above, answering the OP's second question: the numeric
value is len( s ).

If the repetitive process is required, try a loop like:

  >>> start_index = 11 #to cure the issue-raised

  >>> try:
... s[ start_index:s.index( '.', start_index ) ]
... except ValueError:
... s[ start_index:len( s ) ]
...
'gamma'


Somewhat off-topic, but...

When there was a discussion about a None-coalescing operator, I thought 
that it would've been nice if .find and .rfind returned None instead of -1.


There have been times when I've wanted to find the next space (or 
whatever) and have it return the length of the string if absent. That 
could've been accomplished with:


s.find(' ', pos) ?? len(s)

Other times I've wanted it to return -1. That could've been accomplished 
with:


s.find(' ', pos) ?? -1

(There's a place in the re module where .rfind returning -1 is just the 
right value.)


In this instance, slicing with None as the end is just what's wanted.

Ah, well...
--
https://mail.python.org/mailman/listinfo/python-list


Re: hi

2023-03-04 Thread MRAB

On 2023-03-04 17:13, Tom wrote:

Bonjour je suis français et je ne comprend pas comment je peux acceder a
python merci de me repondre

CORDIALEMENT Lilian

Go to https://www.python.org/downloads/ and download the installer for 
your operating system (Windows or MacOS). For Windows I'd recommend 
"Windows installer (64-bit)" unless your computer is only 32-bit.


Also, get yourself a decent editor for plain text that supports syntax 
colouring, although you can use IDLE, which comes with Python.

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


Re: How to escape strings for re.finditer?

2023-02-27 Thread MRAB

On 2023-02-27 23:11, Jen Kris via Python-list wrote:

When matching a string against a longer string, where both strings have spaces 
in them, we need to escape the spaces.

This works (no spaces):

import re
example = 'abcdefabcdefabcdefg'
find_string = "abc"
for match in re.finditer(find_string, example):
     print(match.start(), match.end())

That gives me the start and end character positions, which is what I want.

However, this does not work:

import re
example = re.escape('X - cty_degrees + 1 + qq')
find_string = re.escape('cty_degrees + 1')
for match in re.finditer(find_string, example):
     print(match.start(), match.end())

I’ve tried several other attempts based on my reseearch, but still no match.

I don’t have much experience with regex, so I hoped a reg-expert might help.


You need to escape only the pattern, not the string you're searching.
--
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: can only concatenate str (not "int") to str

2023-02-26 Thread MRAB

On 2023-02-26 16:56, Hen Hanna wrote:


On Sunday, February 26, 2023 at 6:41:01 AM UTC-8, Thomas Passin wrote:
On 2/25/2023 8:12 PM, Hen Hanna wrote: 
> 2. the rude guy ('dn') hasn't offered a single word of comment that's directly relevant to it. 
> >  but he did offer related stuff which he   thinks i should be [grateful] for



Please let's stop the ad hominem messages. If someone doesn't like a 
particular person's messages, send them to spam or don't read them. If 
too many people start to get too rude or personal, remind the whole list 
of the guidelines for respectful participation. If you feel that 
someone's contribution was especially helpful in part because it was 
concise and to the point, you could say that.



yes.   let's stop...


If you  (Thomas Passin)   feel that  someone's contribution was especially 
helpful in part because it was
  concise and to the point, you could say that.
 and pls don't hesitate to reproduce such a comment.




i'm sure a few others were also rude, but  it was the rudest of them all ('dn') 
 that   told me to read some [Code of Conduct] document.    Do not EVER 
 do that  again.


Another rude guy who "asked"  me why i write in a Hard-to-read way  Why 
don't you at least   also make a comment that's  On-Topic  besides  the insulting remark ?




so far,  i think  Paul Rubin's post (in another thread) was esp. concise, 
informative, --- but he's also made a comment about   'shunting'  beginners 
 (questions) to a concentration camp, and sounded  a bit  like a 
cold-hearted (or warm-hearted)  Nazi  officer / scientist.


Oh dear. An example of Godwin's Law.
--
https://mail.python.org/mailman/listinfo/python-list


Re: File write, weird behaviour

2023-02-19 Thread MRAB

On 2023-02-19 19:31, Chris Angelico wrote:

On Mon, 20 Feb 2023 at 06:24, Thomas Passin  wrote:


On 2/19/2023 1:53 PM, Chris Angelico wrote:
> On Mon, 20 Feb 2023 at 03:41, Azizbek Khamdamov
>  wrote:
>>
>> Example 1 (works as expected)
>>
>> file = open("D:\Programming\Python\working_with_files\cities.txt",
>> 'r+') ## contains list cities
>
> Side note: You happened to get lucky with P, w, and c, but for the
> future, I recommend using forward slashes for your paths:
>
> open("D:/Programming/Python/working_with_files/cities.txt", "r+")
>
> Otherwise, you may run into annoying and hard-to-solve problems. Or
> alternatively, you'll upgrade to a newer Python and start getting
> warnings, which would at least tell you that there's a problem.

Or use r'...' strings.  If you are copying a path to clipboard from
Windows Explorer - a fairly common operation - it's much easier to
prepend the "r" than to change all the backslashes to forward slashes.



Yep, either way. I personally prefer using forward slashes since
there's no way to end an r-string with a single backslash, which is
often useful when building a path:

# won't work
path = r"c:\path\to\some\"
open(path + "file")

# will work
path = "c:/path/to/some/"
open(path + "file")

When I build a path, I use os.path.join, so it's only a problem if one 
of the strings refers to the root of a drive, e.g. "C:\\".

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


Re: File write, weird behaviour

2023-02-19 Thread MRAB

On 2023-02-19 14:03, Azizbek Khamdamov wrote:

Example 1 (works as expected)

file = open("D:\Programming\Python\working_with_files\cities.txt",
'r+') ## contains list cities
# the following code adds new record to the beginning of the file,
expected behaviour
file.write("new city\n")

file.close()


Example 2 (weird behaviour)

file = open("D:\Programming\Python\working_with_files\cities.txt",
'r+') ## contains list cities
# the following code DOES NOT add new record TO THE BEGINNING of the
file IF FOLLOWED BY readline() and readlines()# Expected behaviour:
new content should be added to the beginning of the file (as in
Example 1)
file.write("new city\n")

file.readlines()
file.close()

I could not find anything in documentation to explain this strange
behaviour. Why is this happening?


It works correctly if you use file.flush() or file.tell() before 
switching from writing to reading.

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


Re: Comparing caching strategies

2023-02-18 Thread MRAB

On 2023-02-18 23:04, avi.e.gr...@gmail.com wrote:
[snip]


Note how this can cause problems with the original idea here of caching strategies. 
Imagine a function that checks the environment as to what encoding or human language and 
so on to produce text in. If you cache it so it produces results that are stored in 
something like a dictionary with a key, and later the user changes the environment as it 
continues running, the cache may now contain invalid results. You might need to keep 
track of the environment and empty the cache if things change, or start a new cache and 
switch to it.  An example would be the way I use Google Translate. I sometimes am 
studying or using a language and want to look up a word or phrase or entire sentence. If 
Google Translate keeps track, it may notice repeated requests like "Valentines 
Day" and cache it for re-use. But I often click to switch languages and see if the 
other one uses a similar or different way to describe what it means or something similar 
but spelled another way. German does the latter as in Valentinstag which is a fairly 
literal translation as does Dutch (Valentijnsdag ) and  Hungarian (Valentin nap) .

But Hebrew calls it the holiday of love, sort of (חג האהבה). Portuguese is 
similar but includes day as well as love (Dia dos Namorados)

Esperanto tosses in more about sainthood (Sankta Valentín) and in a sense 
Spanish does both ways with day and saint (Día de San Valentín).

The Esperanto didn't look right to me; it's "Valentena tago" or 
"Sankt-Valentena tago".


[snip]

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


Re: Comparing caching strategies

2023-02-18 Thread MRAB

On 2023-02-18 19:59, avi.e.gr...@gmail.com wrote:
[snip]

I do not know the internals of any Roaring Bitmap implementation so all I
did gather was that once the problem is broken into accessing individual
things I chose to call zones for want of a more specific name, then each
zone is stored in one of an unknown number of ways depending on some logic.
You say an implementation chose two ways and that is fine. But in theory, it
may make sense to choose other ways as well and the basic outline of the
algorithm remains similar. I can imagine if a region/zone is all the even
numbers, then a function that checks if you are searching for an odd number
may be cheaper. That is an example, not something I expect to see or that is
useful enough. But the concept of storing a function as the determiner for a
region is general enough that it can support many more realistic ideas.

  From what you wrote, the algorithm chosen is fairly simple BUT I have to ask
if these bitmaps are static or can be changed at run time? I mean if you
have a region that is sparse and then you keep adding, does the software
pause and rewrite that region as a bitmap if it is a list of offsets? Or, if
a bitmap loses enough, ...

A region is either "sparse" (<= 4096 entries) or "dense" (> 4096 
entries). It'll be converted to the other type as and when necessary.



On to your other points. Again, understand I am talking way more abstractly
than you and thus it really does not matter what the length of a particular
ID in some country is for the main discussion. The assumption is that if you
are using something with limits, like a Roaring Bitmap, that you do things
within the limits. When I lived in Austria, I did not bother getting an
Austrian Sozialversicherungsnummer so I have no idea it is ten digits long.
In any case, many things grow over time such as the length of telephone
numbers.

The same applies to things like airport codes. They can get longer for many
reasons and may well exceed 4 characters, and certainly UNICODE or other
such representations may exceed four bytes now if you allow non-ASCII
characters that map into multiple bytes. My point was to think about how
useful a Roaring bitmap is if it takes only 32 bit integers and one trivial
mapping was to use any four bytes to represent a unique integer. But clearly
you could map longer strings easily enough if you restrict yourself to 26
upper case letters and perhaps a few other symbols that can be encoded in 5
bits. I am not saying it is worth the effort, but that means 6 characters
can fit in 32 bits.

The Unicode Consortium have said that Unicode will be limited to 
U+..U+10 (21 bits).



I do wonder if the basic idea has to be limited to 32 bits or if it can
expand to say 64 or use additional but fast methods of storing the data
beyond the two mentioned.

There are variants of other ideas I can think of like sparse arrays or
matrices such as you find in the scipy module in Python. If they hold a
Boolean value, they sound like they are a similar idea where you simply keep
track of the ones marked True, or if it makes sense, the ones considered
False.


[snip]

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


Re: Comparing caching strategies

2023-02-16 Thread MRAB

On 2023-02-14 22:20, Rob Cliffe via Python-list wrote:

On 11/02/2023 00:39, Dino wrote:
First off, a big shout out to Peter J. Holzer, who mentioned roaring 
bitmaps a few days ago and led me to quite a discovery.



I was intrigued to hear about roaring bitmaps and discover they really
were a thing (not a typo as I suspected at first).
What next, I wonder?
      argumentative arrays
      chattering classes (on second thoughts, we have those already)
      dancing dictionaries
      garrulous generators
      laughing lists
      piping pipelines
      singing strings
      speaking sets
      stuttering sorts
      talking tuples
      whistling walruses?


babbling bytestrings?


The future awaits [pun not intended] ...


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


Re: bool and int

2023-01-24 Thread MRAB

On 2023-01-24 20:32, Weatherby,Gerard wrote:

https://peps.python.org/pep-0285/

From: Python-list  on behalf of 
rbowman 
Date: Tuesday, January 24, 2023 at 3:01 PM
To: python-list@python.org 
Subject: Re: bool and int


bool is a subtype of integer. I never dug that deep into Python's guts but
I assume it goes back to boolean being an afterthought in C. Some people
fancy it up with #defines but I always use int.  0 is false, anything else
is true.

bool was introduced early in Python 2. Before then 0 and 1 were used for 
false and true, like in C, which also gained 'false' and 'true'.


For backwards compatibility, bool was made a subclass of int.


C# is pickier, which I guess is a good thing.


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


Re: Tkinter GUI freezing, used Thread then encountered RuntimeError: threads can only be started once

2023-01-10 Thread MRAB

On 2023-01-11 00:13, Cameron Simpson wrote:

On 10Jan2023 18:32, MRAB  wrote:
I don't like how you're passing Thread...start as an argument. IMHO, it 
would be better/cleaner to pass a plain function, even if the only 
thing that function does is to start the thread.


Yes, and this is likely the thing causing the cited exception "threads
can only be started once". Your setup of the button with the action
defined as:

  Thread().start

creates a _single_ new Thread _when you define the button_, and makes
hte button callback try to start it. On the second and following
callback, you're trying to start the _same_ single Thread again.


You're right! I missed that detail. :-(


Do as MRAB suggests and have the callback create-and-start a Thread
instead of just starting an _existing_ Thread.

Also, for simple quick things there's no need to use a Thread at all. If
the final version of the programme is going to do something long running
at that point, then sure.

I can't tell what 'change_flag' is doing because of the formatting 
issue. Is it doing GUI stuff? In a thread? If yes, don't do that. The 
GUI doesn't like that. Only the main thread should do GUI stuff.


Aye. This is very important in almost all GUI toolkits.

Bit me very badly with Qt once, badly in that the segfaults (yes!
segfaults! in a Python app!) were erratic and very timing dependent,
making them hard to reproduce and understand. It wasn't until I
_realised_ it was thread/concurrency related that I could fix it.

Note that in Tk you can have a callback do GUI work, just not in a
separate thread.



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


Re: To clarify how Python handles two equal objects

2023-01-10 Thread MRAB

On 2023-01-10 22:21, Jen Kris via Python-list wrote:

There are cases where NumPy would be the best choice, but that wasn’t the case 
here with what the loop was doing.

To sum up what I learned from this post, where one object derives from another object (a = b[0], 
for example), any operation that would alter one will alter the other.  When either is assigned to 
something else, then they no longer point to the same memory location and they’re once again 
independent.   I hope the word "derives" sidesteps the semantic issue of whether they are 
"equal."


[snip]
In C terms (and in CPython), a 'list' is a resizable array of pointers 
to objects, so after "a=b[0]", the name "a" will point to the same 
object that b[0] points to. That object might or might not be mutable.


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


Re: To clarify how Python handles two equal objects

2023-01-10 Thread MRAB

On 2023-01-10 20:41, Jen Kris via Python-list wrote:


Thanks for your comments.  I'd like to make one small point.  You say:

"Assignment in Python is a matter of object references. It's not
"conform them as long as they remain equal". You'll have to think in
terms of object references the entire way."

But where they have been set to the same object, an operation on one will 
affect the other as long as they are equal (in Python).  So I will have to 
conform them in those cases because Python will reflect any math operation in 
both the array and the matrix.

It's not a 2D matrix, it's a 1D list containing references to 1D lists, 
each of which contains references to Python ints.


In CPython, references happen to be pointers, but that's just an 
implementation detail.





Jan 10, 2023, 12:28 by ros...@gmail.com:


On Wed, 11 Jan 2023 at 07:14, Jen Kris via Python-list
 wrote:



I am writing a spot speedup in assembly language for a short but 
computation-intensive Python loop, and I discovered something about Python 
array handling that I would like to clarify.

For a simplified example, I created a matrix mx1 and assigned the array arr1 to 
the third row of the matrix:

mx1 = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
arr1 = mx1[2]

The pointers to these are now the same:

ida = id(mx1[2]) - 140260325306880
idb = id(arr1) - 140260325306880

That’s great because when I encounter this in assembly or C, I can just borrow 
the pointer to row 3 for the array arr1, on the assumption that they will 
continue to point to the same object.  Then when I do any math operations in 
arr1 it will be reflected in both arrays because they are now pointing to the 
same array:



That's not an optimization; what you've done is set arr1 to be a
reference to that object.


But on the next iteration we assign arr1 to something else:

arr1 = [ 10, 11, 12 ]
idc = id(arr1) – 140260325308160
idd = id(mx1[2]) – 140260325306880

Now arr1 is no longer equal to mx1[2], and any subsequent operations in arr1 
will not affect mx1.



Yep, you have just set arr1 to be a completely different object.


So where I’m rewriting some Python code in a low level language, I can’t assume 
that the two objects are equal because that equality will not remain if either 
is reassigned.  So if I do some operation on one array I have to conform the 
two arrays for as long as they remain equal, I can’t just do it in one 
operation because I can’t rely on the objects remaining equal.

Is my understanding of this correct?  Is there anything I’m missing?



Assignment in Python is a matter of object references. It's not
"conform them as long as they remain equal". You'll have to think in
terms of object references the entire way.

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





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


Re: Tkinter GUI freezing, used Thread then encountered RuntimeError: threads can only be started once

2023-01-10 Thread MRAB

On 2023-01-10 14:57, Abhay Singh wrote:

Here is the entire code snippet of the same.

Please help

def change_flag(top_frame, bottom_frame, button1, button2, button3, button4, 
controller): global counter, canvas, my_image, chosen, flag, directory 
canvas.delete('all') button5['state'] = DISABLED counter += 1

chosen, options_text = function_options()
right_answer_flag = get_right_answer_flag(chosen, options_text)
#pdb.set_trace()

try:
 location = directory + chosen + format_image
except:
 controller.show_frame(PlayAgainExit)
 
my_image = PhotoImage(file=location)

canvas.create_image(160, 100, anchor=CENTER, image=my_image)

button1["text"] = options_text[0]
button2["text"] = options_text[1]
button3["text"] = options_text[2]
button4["text"] = options_text[3]

button1['state'] = NORMAL
button2['state'] = NORMAL
button3['state'] = NORMAL
button4['state'] = NORMAL
##

 button5 = Button(
 next_frame,
 width=20,
 text="next",
 fg="black",
 #command=lambda: 
change_flag(top_frame,bottom_frame,button1,button2,button3,button4,controller))
 command=Thread(target=change_flag, args 
=(top_frame,bottom_frame,button1,button2,button3,button4,controller)).start)
 
 button5.pack(side=RIGHT, padx=5, pady=5)



The formatting is messed up, which doesn't help.

Some points:

You have a 'bare' except, i.e. "except:". Don't do that. It swallows 
_all_ exceptions and can hide bugs.


I don't like how you're passing Thread...start as an argument. IMHO, it 
would be better/cleaner to pass a plain function, even if the only thing 
that function does is to start the thread.


I can't tell what 'change_flag' is doing because of the formatting 
issue. Is it doing GUI stuff? In a thread? If yes, don't do that. The 
GUI doesn't like that. Only the main thread should do GUI stuff.

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


  1   2   3   4   5   6   7   8   9   10   >