From pablogsal at gmail.com Wed Jun 1 11:47:11 2022 From: pablogsal at gmail.com (Pablo Galindo Salgado) Date: Wed, 1 Jun 2022 16:47:11 +0100 Subject: [RELEASE] Expedited release of Python3.11.0b3!! Message-ID: Hi everyone, Due to a known incompatibility with pytest and the previous beta release (Python 3.11.0b2) and after some deliberation, me and the rest of the release team have decided to do an expedited release of Python 3.11.0b3 so the community can continue testing their packages with pytest and therefore testing the betas as expected. # Where can I get the new release? https://www.python.org/downloads/release/python-3110b3/ # What happened? Pytest by default rewrites the AST nodes in the testing code to provide better diagnostics when something fails in the test. For doing this, it creates new AST nodes that are then compiled. In Python 3.11, after some changes in the compiler and AST nodes, these new AST nodes that pytest was creating were invalid. This causes CPython to crash in debug mode because we have several assert statements in the compiler, but in release mode this doesn't cause always a crash, but it creates potential corrupted structures in the compiler silently. In 3.11.0b3 we changed the compiler to reject invalid AST nodes, so what was a silent problem and a crash in debug mode turned into an exception being raised. We had a fix to allow the nodes that pytest is creating to work to preserve backwards compatibility but unfortunately, it didn't make it into 3.11.0b2. Is still possible to use pytest with 3.11.0b2 if you add "--assert=plain" to the pytest invocation but given how many users would have to modify their test suite invocation we decided to proceed with a new release that has the fix. # What happens with future beta releases Python 3.11.0b3 should be considered as an extra beta release. Instead of four beta releases, we will have five and the next beta release (3.11.0b4) will happen as scheduled on Thursday, 2022-06-16. # We hope you enjoy the new releases! Thanks to all of the many volunteers who help make Python Development and these releases possible! Please consider supporting our efforts by volunteering yourself or through organization contributions to the Python Software Foundation. https://www.python.org/psf/ If you have any questions, please reach out to me or another member of the release team :) Your friendly release team, Ned Deily @nad https://discuss.python.org/u/nad Steve Dower @steve.dower https://discuss.python.org/u/steve.dower Pablo Galindo Salgado @pablogsal https://discuss.python.org/u/pablogsal From labdmitriy at gmail.com Wed Jun 1 15:59:58 2022 From: labdmitriy at gmail.com (Dmitry Labazkin) Date: Wed, 1 Jun 2022 12:59:58 -0700 (PDT) Subject: dash/underscore on name of package uploaded on pypi In-Reply-To: References: <5c7807b0$0$19262$426a34cc@news.free.fr> Message-ID: <6692ead1-d907-426e-93a3-103625594c7en@googlegroups.com> On Friday, March 1, 2019 at 12:08:00 AM UTC+3, Terry Reedy wrote: > On 2/28/2019 11:09 AM, ast wrote: > > Hello > > > > I just uploaded a package on pypi, whose name is "arith_lib" > > > > The strange thing is that on pypi the package is renamed "arith-lib" > > The underscore is substitued with a dash > > > > If we search for this package: > > > > pip search arith > > > > arith-lib (2.0.0) - A set of functions for miscellaneous arithmetic > > (so a dash) > > > > For installation both: > > > > pip install -U arith_lib > > pip install -U arith-lib > > > > are working well > > > > and in both case I got a directory with an underscore > > > > C:\Program Files\Python36-32\Lib\site-packages > > > > 28/02/2019 16:57 arith_lib > > 28/02/2019 16:57 arith_lib-2.0.0.dist-info > > > > What happens ? > To expand on Paul's answer. > > English uses '-' both as a connector for compound names and as a > subtraction operator. Context usually makes the choice obvious. But > context-free parsers must choose just one, and for computation, > subtraction wins. 'arith-lib' is parsed as (arith) - (lib). Many > algorithm languages use '_' instead of '-' as the compounder for > identifiers (object names). > > In addition, Python uses filenames -(minus) '.py' as identifiers for > imported modules. So if the repository allows '-' in package names, > installers must convert '-' to '_'. But if the repository allows > 'arith_lib' and 'arith-lib' to be distinct names for different packages, > both would be installed with the same file name. So the repository > standardizes on one form, and it went with English instead of Pythonese. > > -- > Terry Jan Reedy Hi, Recently I wrote the article about packages vs distributions and also explored naming and normalization: https://labdmitriy.github.io/blog/distributions-vs-packages/#additional-experiments In the section ?Additional experiments? I got the expected normalization results, but in ?Open questions? I found that for another package URL is not normalized and original URL is used, and name is partially normalized (underscore is replaced by hyphen but dot remains unchanged). Could you please explain this behavior? Thank you. From timbrazil at sbcglobal.net Thu Jun 2 20:44:35 2022 From: timbrazil at sbcglobal.net (Tim Brazil) Date: Thu, 2 Jun 2022 17:44:35 -0700 Subject: Question about building Python-3.9.12 on OpenBSD 7.1 Message-ID: <68e168ec-f2e6-754e-701a-f5b6a60ffb3f@sbcglobal.net> Hello I hope I am not breaking protocol sending this message to the list. This is my first posting to python-list. I am trying to build Python-3.9.12 from the ports distribution on on a new OpenBSD 7.1 installation. It is failing with the following error. Traceback (most recent call last): ? File "/usr/obj/ports/Python-3.9.12/Python-3.9.12/./setup.py", line 2509, in ??? class PyBuildInstallLib(install_lib): ? File "/usr/obj/ports/Python-3.9.12/Python-3.9.12/./setup.py", line 2516, in PyBuildInstallLib ??? shlib_suffix = sysconfig.get_config_var("SHLIB_SUFFIX") ? File "/usr/obj/ports/Python-3.9.12/Python-3.9.12/Lib/sysconfig.py", line 616, in get_config_var ??? return get_config_vars().get(name) ? File "/usr/obj/ports/Python-3.9.12/Python-3.9.12/Lib/sysconfig.py", line 565, in get_config_vars ??? _init_posix(_CONFIG_VARS) ? File "/usr/obj/ports/Python-3.9.12/Python-3.9.12/Lib/sysconfig.py", line 430, in _init_posix ??? _temp = __import__(name, globals(), locals(), ['build_time_vars'], 0) ModuleNotFoundError: No module named '_sysconfigdata__openbsd7_amd64-unknown-openbsd7' *** Error 1 in /usr/obj/ports/Python-3.9.12/Python-3.9.12 (Makefile:649 'sharedmods': @case "`echo X $MAKEFLAGS | sed 's/^X //;s/ -- .*//'`"...) In researching this on the internet I discovered a similar reporting on FreeBSD that seems to relate to regex and MULTIARZCH in the FreeBSD Makefile but it doesn't seem to apply to the port of my Makefile/environment. This is the report I am referring to: ??? https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=259896 My exact problem is... I do not have z _sysconfigdata__openbsd7_amd64-unknown-openbsd7 module but I do have a _sysconfigdata__openbsd7_amd64-unknown-openbsd7.1.py module under: ./build/lib.openbsd-7.1-amd64-3.9/_sysconfigdata__openbsd7_amd64-unknown-openbsd7.1.py I suspect somewhere, it's not picking up the full 7.1 version string. I am having a problem figuring it out. I kindly ask if you have any pointers on fixing it. Should I log a bug or is it a OpenBSD package thing? Thanks in Advance Tim From drsalists at gmail.com Thu Jun 2 23:21:44 2022 From: drsalists at gmail.com (Dan Stromberg) Date: Thu, 2 Jun 2022 20:21:44 -0700 Subject: Question about building Python-3.9.12 on OpenBSD 7.1 In-Reply-To: <68e168ec-f2e6-754e-701a-f5b6a60ffb3f@sbcglobal.net> References: <68e168ec-f2e6-754e-701a-f5b6a60ffb3f@sbcglobal.net> Message-ID: It's been my understanding that there is a fundamental difference between the *BSD's and the Linuxes. The *BSD's have their ports system, that collects deltas against third-party packages to build them on a *BSD. These deltas become part of the ports system. The Linuxes port an application, and contribute the deltas to the package's upstream maintainer. For this reason, I suspect you may do well to contact the person in charge of the port of CPython to OpenBSD. HTH On Thu, Jun 2, 2022 at 5:46 PM Tim Brazil wrote: > Hello > > I hope I am not breaking protocol sending this message to the list. > This is my first posting to python-list. > > I am trying to build Python-3.9.12 from the ports distribution on > on a new OpenBSD 7.1 installation. > It is failing with the following error. > > Traceback (most recent call last): > File "/usr/obj/ports/Python-3.9.12/Python-3.9.12/./setup.py", line > 2509, in > class PyBuildInstallLib(install_lib): > File "/usr/obj/ports/Python-3.9.12/Python-3.9.12/./setup.py", line > 2516, in PyBuildInstallLib > shlib_suffix = sysconfig.get_config_var("SHLIB_SUFFIX") > File "/usr/obj/ports/Python-3.9.12/Python-3.9.12/Lib/sysconfig.py", > line 616, in get_config_var > return get_config_vars().get(name) > File "/usr/obj/ports/Python-3.9.12/Python-3.9.12/Lib/sysconfig.py", > line 565, in get_config_vars > _init_posix(_CONFIG_VARS) > File "/usr/obj/ports/Python-3.9.12/Python-3.9.12/Lib/sysconfig.py", > line 430, in _init_posix > _temp = __import__(name, globals(), locals(), ['build_time_vars'], 0) > ModuleNotFoundError: No module named > '_sysconfigdata__openbsd7_amd64-unknown-openbsd7' > *** Error 1 in /usr/obj/ports/Python-3.9.12/Python-3.9.12 (Makefile:649 > 'sharedmods': @case "`echo X $MAKEFLAGS | sed 's/^X //;s/ -- .*//'`"...) > > In researching this on the internet I discovered a similar reporting on > FreeBSD that seems to relate to regex and MULTIARZCH in the FreeBSD > Makefile but it doesn't seem to apply to the port of my > Makefile/environment. > > This is the report I am referring to: > > https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=259896 > > My exact problem is... > > I do not have z _sysconfigdata__openbsd7_amd64-unknown-openbsd7 module > but I do have a _sysconfigdata__openbsd7_amd64-unknown-openbsd7.1.py > module > under: > > ./build/lib.openbsd-7.1-amd64-3.9/_ > sysconfigdata__openbsd7_amd64-unknown-openbsd7.1.py > > I suspect somewhere, it's not picking up the full 7.1 version string. > I am having a problem figuring it out. I kindly ask if you have any > pointers on fixing > it. Should I log a bug or is it a OpenBSD package thing? > > Thanks in Advance > Tim > -- > https://mail.python.org/mailman/listinfo/python-list > From garabik-news-2005-05 at kassiopeia.juls.savba.sk Fri Jun 3 11:04:50 2022 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Fri, 3 Jun 2022 15:04:50 -0000 (UTC) Subject: [Python-announce] ANN: unicode 2.9 Message-ID: unicode is a simple python command line utility that displays properties for a given unicode character, or searches unicode database for a given name. It was written with Linux in mind, but should work almost everywhere (including MS Windows and MacOSX), UTF-8 console is recommended. ?p??pu??s ?po???u? ??? ?o ?sn p??u??p? pu? s?ld???u???d ??? ?u??????suo??p loo? ??????p??p ?u?ll??x? u? s?? ?I ?s?u??od?po? ?u???????p ?l???ld?o? ?u??sn ?l???? 's?d?l? ?o ?????s ??l?????s ?ll?ns??? o?u?? ?x?? ??? ????uo? o? p??pu??s ?po???u? ??? ?o ???od lln? ??? s???oldx? ???? '????l???n ,?po????d, osl? su????uo? ??????d ??? Changes since previous versions: * better handling of changes in data files URL: http://kassiopeia.juls.savba.sk/~garabik/software/unicode.html License: GPL v3 Installation: pip install unicode -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From timbrazil at sbcglobal.net Fri Jun 3 19:49:56 2022 From: timbrazil at sbcglobal.net (Tim Brazil) Date: Fri, 3 Jun 2022 16:49:56 -0700 Subject: Question about building Python-3.9.12 on OpenBSD 7.1 In-Reply-To: References: <68e168ec-f2e6-754e-701a-f5b6a60ffb3f@sbcglobal.net> Message-ID: <8c35ea70-06ce-3820-1d61-efd241b7ea22@sbcglobal.net> Thanks for the response HTH. Your comment led me to think that perhaps a "ports" dependency failed to be generated correctly. They are patched on the fly. I went back to "scratch" on fresh installation with a clean Python build. This time it worked correctly. Go figure... thx! - Tim Dan Stromberg wrote: > > It's been my understanding that there is a fundamental difference > between the *BSD's and the Linuxes. > > The *BSD's have their ports system, that collects deltas against > third-party packages to build them on a *BSD.? These deltas become > part of the ports system. > > The Linuxes port an application, and contribute the deltas to the > package's upstream maintainer. > > For this reason, I suspect you may do well to contact the person in > charge of the port of CPython to OpenBSD. > > HTH > > > On Thu, Jun 2, 2022 at 5:46 PM Tim Brazil > wrote: > > Hello > > I hope I am not breaking protocol sending this message to the list. > This is my first posting to python-list. > > I am trying to build Python-3.9.12 from the ports distribution on > on a new OpenBSD 7.1 installation. > It is failing with the following error. > > Traceback (most recent call last): > ?? File "/usr/obj/ports/Python-3.9.12/Python-3.9.12/./setup.py", line > 2509, in > ???? class PyBuildInstallLib(install_lib): > ?? File "/usr/obj/ports/Python-3.9.12/Python-3.9.12/./setup.py", line > 2516, in PyBuildInstallLib > ???? shlib_suffix = sysconfig.get_config_var("SHLIB_SUFFIX") > ?? File > "/usr/obj/ports/Python-3.9.12/Python-3.9.12/Lib/sysconfig.py", > line 616, in get_config_var > ???? return get_config_vars().get(name) > ?? File > "/usr/obj/ports/Python-3.9.12/Python-3.9.12/Lib/sysconfig.py", > line 565, in get_config_vars > ???? _init_posix(_CONFIG_VARS) > ?? File > "/usr/obj/ports/Python-3.9.12/Python-3.9.12/Lib/sysconfig.py", > line 430, in _init_posix > ???? _temp = __import__(name, globals(), locals(), > ['build_time_vars'], 0) > ModuleNotFoundError: No module named > '_sysconfigdata__openbsd7_amd64-unknown-openbsd7' > *** Error 1 in /usr/obj/ports/Python-3.9.12/Python-3.9.12 > (Makefile:649 > 'sharedmods': @case "`echo X $MAKEFLAGS | sed 's/^X //;s/ -- > .*//'`"...) > > In researching this on the internet I discovered a similar > reporting on > FreeBSD that seems to relate to regex and MULTIARZCH in the FreeBSD > Makefile but it doesn't seem to apply to the port of my > Makefile/environment. > > This is the report I am referring to: > > https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=259896 > > My exact problem is... > > I do not have z _sysconfigdata__openbsd7_amd64-unknown-openbsd7 module > but I do have a > _sysconfigdata__openbsd7_amd64-unknown-openbsd7.1.py > module > under: > > ./build/lib.openbsd-7.1-amd64-3.9/_sysconfigdata__openbsd7_amd64-unknown-openbsd7.1.py > > > I suspect somewhere, it's not picking up the full 7.1 version string. > I am having a problem figuring it out. I kindly ask if you have any > pointers on fixing > it. Should I log a bug or is it a OpenBSD package thing? > > Thanks in Advance > Tim > -- > https://mail.python.org/mailman/listinfo/python-list > From michael.stemper at gmail.com Sat Jun 4 14:36:26 2022 From: michael.stemper at gmail.com (Michael F. Stemper) Date: Sat, 4 Jun 2022 13:36:26 -0500 Subject: min, max with position Message-ID: Python contains built-in functions that return the minimum or maximum items in a list. >>> l = [1.618033,3.141593,2.718282] >>> min(l) 1.618033 >>> max(l) 3.141593 >>> Are there similar functions that return not only the minimum or maximum value, but also its position? >>> specialmin(l) (0,1.618033) >>> specialmax(l) 3.141593 >>> -- Michael F. Stemper I feel more like I do now than I did when I came in. From wlfraed at ix.netcom.com Sat Jun 4 14:56:24 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sat, 04 Jun 2022 14:56:24 -0400 Subject: min, max with position References: Message-ID: On Sat, 4 Jun 2022 13:36:26 -0500, "Michael F. Stemper" declaimed the following: > >Are there similar functions that return not only the minimum >or maximum value, but also its position? > If it isn't in the library reference manual, NO... But it also isn't that difficult to write... >>> def whatAt(function, data): ... what = function(data) ... at = data.index(what) ... return (at, what) ... >>> l = [ 1.618033, 3.1415923536, 2.718282 ] >>> whatAt(min, l) (0, 1.618033) >>> whatAt(max, l) (1, 3.1415923536) >>> (properly, I should either reverse the order of the return value, or change the name to atWhat() ) -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From michael.stemper at gmail.com Sat Jun 4 15:09:57 2022 From: michael.stemper at gmail.com (Michael F. Stemper) Date: Sat, 4 Jun 2022 14:09:57 -0500 Subject: min, max with position In-Reply-To: References: Message-ID: On 04/06/2022 13.56, Dennis Lee Bieber wrote: > On Sat, 4 Jun 2022 13:36:26 -0500, "Michael F. Stemper" > declaimed the following: > >> >> Are there similar functions that return not only the minimum >> or maximum value, but also its position? >> > If it isn't in the library reference manual, NO... > > But it also isn't that difficult to write... I already wrote it. I was wondering if there was something standard that I should have used instead. I have multiple functions that I wrote, only to later learn that there were standard functions that did the same thing. -- Michael F. Stemper This email is to be read by its intended recipient only. Any other party reading is required by the EULA to send me $500.00. From alan at csail.mit.edu Sat Jun 4 16:16:13 2022 From: alan at csail.mit.edu (Alan Bawden) Date: Sat, 04 Jun 2022 16:16:13 -0400 Subject: min, max with position References: Message-ID: <86tu90tcaa.fsf@williamsburg.bawden.org> "Michael F. Stemper" writes: Are there similar functions that return not only the minimum or maximum value, but also its position? >>> specialmin(l) (0,1.618033) >>> specialmax(l) 3.141593 >>> I believe that what you are looking for is usually called "argmax" and "argmin" (see ). These don't exist in the standard Python library as far as I can tell, but numpy does have "argmax" and "argmin" routines. -- Alan Bawden From mmontgomery at levado.to Sat Jun 4 16:18:36 2022 From: mmontgomery at levado.to (Meredith Montgomery) Date: Sat, 04 Jun 2022 17:18:36 -0300 Subject: on a statement followed by an expression Message-ID: <86mtesb2sj.fsf@levado.to> (*) Question How can I, in a single line, write a statement followed by an expression? For example, if /d/ is a dicionary, how can I write d["key"] = value # and somehow making this line end up with d (*) Where does the question come from? >From the following experiment-exercise. (*) Introduction Here's a gentle way to consome records /rs/, each of which represents a robbery, say, and produce a dictionary containing a count of each zip code. --8<---------------cut here---------------start------------->8--- def zip(r): return r[0] def roberry_per_zip(rs): d = {} for r in rs: d[zip(r)] = dict.get(d, zip(r), 0) + 1 return d --8<---------------cut here---------------end--------------->8--- Now I'd like to compare the code with a version that uses reduce. Let me please write my own reduce function for completeness and clarity --- I suppose. The code is still pretty clear. --8<---------------cut here---------------start------------->8--- def my_reduce(it, f, init): r = init for e in it: r = f(r, e) return r def count_in(d, r): d[zip(r)] = dict.get(d, zip(r), 0) + 1 return d def roberry_via_reduce(rs): return my_reduce(rs, count_in, {}) --8<---------------cut here---------------end--------------->8--- It's not clear, though, how to write such a procedure using a lambda expression in place of count_in. That's because we must return a dicionary and statements are not expressions. How can I execute a statement followed by a value in a single line? def roberry_via_reduce(rs): return my_reduce(rs, lambda d, r: ``increment and return d'', {}) I don't know how to write ``increment and return d'' I'm just curious. Thank you. From alan at csail.mit.edu Sat Jun 4 17:32:48 2022 From: alan at csail.mit.edu (Alan Bawden) Date: Sat, 04 Jun 2022 17:32:48 -0400 Subject: on a statement followed by an expression References: <86mtesb2sj.fsf@levado.to> Message-ID: <86pmjot8qn.fsf@williamsburg.bawden.org> Meredith Montgomery writes: How can I execute a statement followed by a value in a single line? def roberry_via_reduce(rs): return my_reduce(rs, lambda d, r: ``increment and return d'', {}) The grammar or Python is deliberately designed so that the body of a lambda expression cannot contain any statements. So your original code, where you defined a separate `count_in' procedure, is probably what you want. Although using `reduce' is kind of silly in this case because you aren't computing a new dictionary every time, but instead you are mutating the _same_ dictionary every time. Your original code that used a `for' loop is actually much clearer. -- Alan Bawden From rosuav at gmail.com Sat Jun 4 17:50:24 2022 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 5 Jun 2022 07:50:24 +1000 Subject: min, max with position In-Reply-To: References: Message-ID: On Sun, 5 Jun 2022 at 07:46, Michael F. Stemper wrote: > > Python contains built-in functions that return the minimum or > maximum items in a list. > > >>> l = [1.618033,3.141593,2.718282] > >>> min(l) > 1.618033 > >>> max(l) > 3.141593 > >>> > > Are there similar functions that return not only the minimum > or maximum value, but also its position? > > >>> specialmin(l) > (0,1.618033) > >>> specialmax(l) > 3.141593 > >>> > No, but it shouldn't be too hard to make it if you want it. The obvious option of calling max/min on the enumerated list won't work on its own, since the index comes before the value, but with a key function it would work fine: >>> min(enumerate(l), key=lambda x: x[1]) (0, 1.618033) >>> max(enumerate(l), key=lambda x: x[1]) (1, 3.141593) ChrisA From PythonList at DancesWithMice.info Sat Jun 4 17:52:49 2022 From: PythonList at DancesWithMice.info (dn) Date: Sun, 5 Jun 2022 09:52:49 +1200 Subject: min, max with position In-Reply-To: References: Message-ID: On 05/06/2022 06.56, Dennis Lee Bieber wrote: > On Sat, 4 Jun 2022 13:36:26 -0500, "Michael F. Stemper" > declaimed the following: > >> >> Are there similar functions that return not only the minimum >> or maximum value, but also its position? >> > If it isn't in the library reference manual, NO... > > But it also isn't that difficult to write... > >>>> def whatAt(function, data): > ... what = function(data) > ... at = data.index(what) > ... return (at, what) > ... >>>> l = [ 1.618033, 3.1415923536, 2.718282 ] >>>> whatAt(min, l) > (0, 1.618033) >>>> whatAt(max, l) > (1, 3.1415923536) >>>> > > (properly, I should either reverse the order of the return value, or change > the name to atWhat() ) ...and remembering the special case: if the what value appears more than once in the list, the where?at will report the first/'left-most' index only. -- Regards, =dn From rosuav at gmail.com Sat Jun 4 18:02:18 2022 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 5 Jun 2022 08:02:18 +1000 Subject: min, max with position In-Reply-To: References: Message-ID: On Sun, 5 Jun 2022 at 08:00, dn wrote: > > On 05/06/2022 06.56, Dennis Lee Bieber wrote: > > On Sat, 4 Jun 2022 13:36:26 -0500, "Michael F. Stemper" > > declaimed the following: > > > >> > >> Are there similar functions that return not only the minimum > >> or maximum value, but also its position? > >> > > If it isn't in the library reference manual, NO... > > > > But it also isn't that difficult to write... > > > >>>> def whatAt(function, data): > > ... what = function(data) > > ... at = data.index(what) > > ... return (at, what) > > ... > >>>> l = [ 1.618033, 3.1415923536, 2.718282 ] > >>>> whatAt(min, l) > > (0, 1.618033) > >>>> whatAt(max, l) > > (1, 3.1415923536) > >>>> > > > > (properly, I should either reverse the order of the return value, or change > > the name to atWhat() ) > > ...and remembering the special case: > if the what value appears more than once in the list, the where?at will > report the first/'left-most' index only. > Which is consistent with the vanilla min() function. >>> min([1, 1.0]) 1 ChrisA From PythonList at DancesWithMice.info Sat Jun 4 18:07:42 2022 From: PythonList at DancesWithMice.info (dn) Date: Sun, 5 Jun 2022 10:07:42 +1200 Subject: min, max with position In-Reply-To: References: Message-ID: On 05/06/2022 09.50, Chris Angelico wrote: > No, but it shouldn't be too hard to make it if you want it. The > obvious option of calling max/min on the enumerated list won't work on > its own, since the index comes before the value, but with a key > function it would work fine: > >>>> min(enumerate(l), key=lambda x: x[1]) > (0, 1.618033) >>>> max(enumerate(l), key=lambda x: x[1]) > (1, 3.141593) An elegant solution! But, but, but which of the above characters is an 'el' and which a 'one'??? (please have pity on us old f...s and the visually-challenged!) -- Regards, =dn From rosuav at gmail.com Sat Jun 4 18:11:03 2022 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 5 Jun 2022 08:11:03 +1000 Subject: min, max with position In-Reply-To: References: Message-ID: On Sun, 5 Jun 2022 at 08:09, dn wrote: > > On 05/06/2022 09.50, Chris Angelico wrote: > > No, but it shouldn't be too hard to make it if you want it. The > > obvious option of calling max/min on the enumerated list won't work on > > its own, since the index comes before the value, but with a key > > function it would work fine: > > > >>>> min(enumerate(l), key=lambda x: x[1]) > > (0, 1.618033) > >>>> max(enumerate(l), key=lambda x: x[1]) > > (1, 3.141593) > > An elegant solution! > > But, but, but which of the above characters is an 'el' and which a 'one'??? > (please have pity on us old f...s and the visually-challenged!) > Fair point, but I stuck to the OP's example list and kept it called 'l' for list :) ChrisA From greg.ewing at canterbury.ac.nz Sat Jun 4 19:52:45 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Sun, 5 Jun 2022 11:52:45 +1200 Subject: min, max with position In-Reply-To: References: Message-ID: On 5/06/22 10:07 am, dn wrote: > On 05/06/2022 09.50, Chris Angelico wrote: >>>>> min(enumerate(l), key=lambda x: x[1]) >> (0, 1.618033) > > But, but, but which of the above characters is an 'el' and which a 'one'??? > (please have pity on us old f...s and the visually-challenged!) > ell = l one = 1 min(enumerate(ell), key=lambda x: x[one]) Hope that clears it up!!!!!11!one!ell -- Greg From drsalists at gmail.com Sun Jun 5 00:23:34 2022 From: drsalists at gmail.com (Dan Stromberg) Date: Sat, 4 Jun 2022 21:23:34 -0700 Subject: min, max with position In-Reply-To: References: Message-ID: On Sat, Jun 4, 2022 at 9:07 PM Greg Ewing wrote: > On 5/06/22 10:07 am, dn wrote: > > On 05/06/2022 09.50, Chris Angelico wrote: > >>>>> min(enumerate(l), key=lambda x: x[1]) > >> (0, 1.618033) > > > > But, but, but which of the above characters is an 'el' and which a > 'one'??? > > (please have pity on us old f...s and the visually-challenged!) > > > > ell = l > one = 1 > min(enumerate(ell), key=lambda x: x[one]) > > Hope that clears it up!!!!!11!one!ell > I'm kind of partial to: min((value, index) for (index, value) in enumerate(list_)) It'll return a single 2-tuple where the value of interest is at position 0. In the event of a tie, it should give you the first such value encountered. From antoon.pardon at vub.be Sun Jun 5 04:46:40 2022 From: antoon.pardon at vub.be (Antoon Pardon) Date: Sun, 5 Jun 2022 10:46:40 +0200 Subject: min, max with position In-Reply-To: References: Message-ID: <9622cca4-0993-89b6-4f8a-e1307177f38b@vub.be> Op 5/06/2022 om 01:52 schreef Greg Ewing: > On 5/06/22 10:07 am, dn wrote: >> On 05/06/2022 09.50, Chris Angelico wrote: >>>>>> min(enumerate(l), key=lambda x: x[1]) >>> (0, 1.618033) >> >> But, but, but which of the above characters is an 'el' and which a >> 'one'??? >> (please have pity on us old f...s and the visually-challenged!) >> > > ell = l > one = 1 > min(enumerate(ell), key=lambda x: x[one]) I'd like to point to the operator module which allows you to write the above as: min(enumerate(ell), key=operator.itemgetter(one)) -- Antoon Pardon. From michael.stemper at gmail.com Sun Jun 5 11:14:59 2022 From: michael.stemper at gmail.com (Michael F. Stemper) Date: Sun, 5 Jun 2022 10:14:59 -0500 Subject: min, max with position In-Reply-To: References: Message-ID: On 04/06/2022 14.08, Stefan Ram wrote: > "Michael F. Stemper" writes: >> Are there similar functions that return not only the minimum >> or maximum value, but also its position? > > The maximum value does not need to have a unique position. Which is something that I'll just have to live with, whether I use home-brew or something from a standard module. For the particular application, my lists have 24 elements and are converted from data that is received in a %5.2f format, so collisions aren't too likely anyway. > The World-Wide Web holds several suggestions like l.index( > max( l )) or max( enumerate( l ), key=( lambda x: x[ 1 ])). Oh, I like that second one. I tried playing around with a lambda function, but combining with enumerate eluded me. It's much better than my for-loop with extraneous variables. -- Michael F. Stemper Psalm 94:3-6 From dave at looktowindward.com Mon Jun 6 06:37:47 2022 From: dave at looktowindward.com (Dave) Date: Mon, 6 Jun 2022 12:37:47 +0200 Subject: Help with Python/Eyed3 MusicCDIdFrame method Message-ID: <4DF8E610-E149-47C3-9ECD-47456EBD1232@looktowindward.com> Hi, I?m trying to get the ID3 tags of an mp3 file. I trying to use the MusicCDIdFrame method but I can?t seem to get it right. Here is a code snippet: import eyed3 import eyed3.id3 import eyed3.id3.frames import eyed3.id3.apple import eyed3.mp3 myID3 = eyed3.load("/Users/Test/Life in the fast lane.mp3") myTitle = myID3.tag.title myArtist = myID3.tag.artist myAlbum = myID3.tag.album myAlbumArtist = myID3.tag.album_artist myComposer = myID3.tag.composer myPublisher = myID3.tag.publisher myGenre = myID3.tag.genre.name myCDID = myID3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'') When I run this, I get the following error: File "/Documents/Python/Test1/main.py", line 94, in myCDID = myID3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'') AttributeError: 'Mp3AudioFile' object has no attribute 'id3' Any help or suggestion greatly appreciated. All the Best Dave From rshepard at appl-ecosys.com Mon Jun 6 12:10:55 2022 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Mon, 6 Jun 2022 09:10:55 -0700 (PDT) Subject: Tkinter: multicolumn table widget In-Reply-To: References: <6eaa6ad-c333-ec4a-c735-8da9f669f18@appl-ecosys.com> <55a2cf6e-92b7-9953-0314-198860a0a832@mrabarnett.plus.com> Message-ID: <91b92b7d-6e29-cfd1-313e-32ed05abcb2@appl-ecosys.com> On Tue, 31 May 2022, MRAB wrote: > There's an example of how to show a tooltip here: > https://stackoverflow.com/questions/3221956/how-do-i-display-tooltips-in-tkinter MRAB, A tooltip would work. I downloaded the first example and assume that it will display a treeview cell when the cursor hovers over it without needing to be limited to a single column. When I test the module (I'm still writing it) I'll learn what needs fixing. Thanks very much, Rich From philb at philb.ca Mon Jun 6 12:38:46 2022 From: philb at philb.ca (Phil Boutros) Date: Mon, 6 Jun 2022 16:38:46 -0000 (UTC) Subject: Automatic Gain Control in Python? References: <013801d872d9$f8d13700$ea73a500$@SGA.Ninja> <015301d872f1$6bf9afc0$43ed0f40$@SGA.Ninja> <017501d8731a$43882750$ca9875f0$@SGA.Ninja> <010101d87553$6daa6ad0$48ff4070$@SGA.Ninja> Message-ID: Chris Angelico wrote: > > General principle: If you're asking someone else for help, don't tell > them that your way is easier, because the obvious response is "go > ahead then, do it your own way". *Ding Ding Ding*...We have a winner! At least, that's where I dropped off. My experienced advice is all wrong for you? Sorry I couldn't help more. Good luck to you. > You're technically right in a sense: something that you already have > is, indeed, easier than something else. But downloading files is > *easy* in Python, and audio analysis on files is FAR easier than > real-time audio analysis with hysteresis avoidance. Also this. > Unless you have a really good > reason for sticking to the black-box system, I would strongly > recommend going for the much much easier method of simply downloading > the files as they are. As pretty much everyone else has said. Insisting on real-time processing of something that is itself pre-recorded is non-sensical. Phil -- AH#61 Wolf#14 BS#89 bus#1 CCB#1 SENS KOTC#4 philb at philb.ca http://philb.ca From python at mrabarnett.plus.com Mon Jun 6 12:46:09 2022 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 6 Jun 2022 17:46:09 +0100 Subject: Help with Python/Eyed3 MusicCDIdFrame method In-Reply-To: <4DF8E610-E149-47C3-9ECD-47456EBD1232@looktowindward.com> References: <4DF8E610-E149-47C3-9ECD-47456EBD1232@looktowindward.com> Message-ID: On 2022-06-06 11:37, Dave wrote: > Hi, > > I?m trying to get the ID3 tags of an mp3 file. I trying to use the MusicCDIdFrame > method but I can?t seem to get it right. Here is a code snippet: > > > import eyed3 > import eyed3.id3 > import eyed3.id3.frames > import eyed3.id3.apple > import eyed3.mp3 > myID3 = eyed3.load("/Users/Test/Life in the fast lane.mp3") > myTitle = myID3.tag.title > myArtist = myID3.tag.artist > myAlbum = myID3.tag.album > myAlbumArtist = myID3.tag.album_artist > myComposer = myID3.tag.composer > myPublisher = myID3.tag.publisher > myGenre = myID3.tag.genre.name > myCDID = myID3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'') > > When I run this, I get the following error: > > File "/Documents/Python/Test1/main.py", line 94, in > myCDID = myID3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'') > AttributeError: 'Mp3AudioFile' object has no attribute 'id3' > > > Any help or suggestion greatly appreciated. > That line should be: myCDID = eyed3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'') Also remember that some attributes might be None, e.g. 'myID3.tag.genre' might be None. Another point: it's probably not worth importing the submodules of 'eyed3'; you're not gaining anything from it. From grant.b.edwards at gmail.com Mon Jun 6 13:10:37 2022 From: grant.b.edwards at gmail.com (Grant Edwards) Date: Mon, 06 Jun 2022 10:10:37 -0700 (PDT) Subject: Automatic Gain Control in Python? References: <013801d872d9$f8d13700$ea73a500$@SGA.Ninja> <015301d872f1$6bf9afc0$43ed0f40$@SGA.Ninja> <017501d8731a$43882750$ca9875f0$@SGA.Ninja> <010101d87553$6daa6ad0$48ff4070$@SGA.Ninja> Message-ID: <629e350d.1c69fb81.cdc2b.5641@mx.google.com> On 2022-06-06, Phil Boutros wrote: > As pretty much everyone else has said. Insisting on real-time > processing of something that is itself pre-recorded is non-sensical. Downnloading a file, normalizing/compressing the volume, and then streaming the result is three lines in a bash script (assuming you've got wget, sox, and vlc installed). I assume that something similar could be done in PowerShell on Windows. With the right libraries, it's probably about the same in Python. -- Grant From philb at philb.ca Mon Jun 6 12:46:14 2022 From: philb at philb.ca (Phil Boutros) Date: Mon, 6 Jun 2022 16:46:14 -0000 (UTC) Subject: Automatic Gain Control in Python? References: <013801d872d9$f8d13700$ea73a500$@SGA.Ninja> <015301d872f1$6bf9afc0$43ed0f40$@SGA.Ninja> <017501d8731a$43882750$ca9875f0$@SGA.Ninja> <010101d87553$6daa6ad0$48ff4070$@SGA.Ninja> Message-ID: Steve GS wrote: > > Maybe you do not understand smart speakers. That is exactly what they do. > You tell them what podcast/broadcast to play, they get it and play it for > you. It is that simple. > > All I want to do is change the audio levels automatically to make it easier > on the ear. Once again, what you are telling the speaker to play is a pre-recorded file. Grab it. Normalize it however you want (compared to others, compared to set specs, compared to whatever tickles your fancy). Tell the speaker to play *that* file instead. Done. Phil -- AH#61 Wolf#14 BS#89 bus#1 CCB#1 SENS KOTC#4 philb at philb.ca http://philb.ca From pablogsal at gmail.com Mon Jun 6 13:33:56 2022 From: pablogsal at gmail.com (Pablo Galindo Salgado) Date: Mon, 6 Jun 2022 18:33:56 +0100 Subject: [RELEASE] Python 3.10.5 is available Message-ID: The latest bugfix drop for Python 3.10 is here: Python 3.10.5. This release packs more than 230 bugfixes and docs changes, so you surely want to update :) You can get it here: https://www.python.org/downloads/release/python-3105/ ## This is the fourth maintenance release of Python 3.10 Python 3.10.5 is the newest major release of the Python programming language, and it contains many new features and optimizations. # Major new features of the 3.10 series, compared to 3.9 Among the new major new features and changes so far: * [PEP 623](https://www.python.org/dev/peps/pep-0623/) -- Deprecate and prepare for the removal of the wstr member in PyUnicodeObject. * [PEP 604](https://www.python.org/dev/peps/pep-0604/) -- Allow writing union types as X | Y * [PEP 612](https://www.python.org/dev/peps/pep-0612/) -- Parameter Specification Variables * [PEP 626](https://www.python.org/dev/peps/pep-0626/) -- Precise line numbers for debugging and other tools. * [PEP 618 ](https://www.python.org/dev/peps/pep-0618/) -- Add Optional Length-Checking To zip. * [bpo-12782](https://bugs.python.org/issue12782): Parenthesized context managers are now officially allowed. * [PEP 632 ](https://www.python.org/dev/peps/pep-0632/) -- Deprecate distutils module. * [PEP 613 ](https://www.python.org/dev/peps/pep-0613/) -- Explicit Type Aliases * [PEP 634 ](https://www.python.org/dev/peps/pep-0634/) -- Structural Pattern Matching: Specification * [PEP 635 ](https://www.python.org/dev/peps/pep-0635/) -- Structural Pattern Matching: Motivation and Rationale * [PEP 636 ](https://www.python.org/dev/peps/pep-0636/) -- Structural Pattern Matching: Tutorial * [PEP 644 ](https://www.python.org/dev/peps/pep-0644/) -- Require OpenSSL 1.1.1 or newer * [PEP 624 ](https://www.python.org/dev/peps/pep-0624/) -- Remove Py_UNICODE encoder APIs * [PEP 597 ](https://www.python.org/dev/peps/pep-0597/) -- Add optional EncodingWarning [bpo-38605](https://bugs.python.org/issue38605): `from __future__ import annotations` ([PEP 563](https://www.python.org/dev/peps/pep-0563/)) used to be on this list in previous pre-releases but it has been postponed to Python 3.11 due to some compatibility concerns. You can read the Steering Council communication about it [here]( https://mail.python.org/archives/list/python-dev at python.org/thread/CLVXXPQ2T2LQ5MP2Y53VVQFCXYWQJHKZ/) to learn more. # More resources * [Changelog](https://docs.python.org/3.10/whatsnew/changelog.html#changelog ) * [Online Documentation](https://docs.python.org/3.10/) * [PEP 619](https://www.python.org/dev/peps/pep-0619/), 3.10 Release Schedule * Report bugs at [https://bugs.python.org](https://bugs.python.org). * [Help fund Python and its community](/psf/donations/). # And now for something completely different Strange quarks are the third lightest quarks, which are subatomic particles that are so small, they are believed to be the fundamental particles, and not further divisible. Like down quarks, strange quarks have a charge of -1/3. Like all fermions (which are particles that can not exist in the same place at the same time), strange quarks have a spin of 1/2. What makes strange quarks different from down quarks?apart from having 25 times the mass of down quarks?is that they have something that scientists call "strangeness." Strangeness is basically a resistance to decay against strong force and electromagnetism. This means that any particle that contains a strange quark can not decay due to strong force (or electromagnetism), but instead with the much slower weak force. It was believed that this was a 'strange' method of decay, which is why the scientists gave the particles that name. # We hope you enjoy the new releases! Thanks to all of the many volunteers who help make Python Development and these releases possible! Please consider supporting our efforts by volunteering yourself or through organization contributions to the Python Software Foundation. https://www.python.org/psf/ Your friendly release team, Ned Deily @nad https://discuss.python.org/u/nad Steve Dower @steve.dower https://discuss.python.org/u/steve.dower Pablo Galindo Salgado @pablogsal https://discuss.python.org/u/pablogsal From dave at looktowindward.com Mon Jun 6 13:37:20 2022 From: dave at looktowindward.com (Dave) Date: Mon, 6 Jun 2022 19:37:20 +0200 Subject: Help with Python/Eyed3 MusicCDIdFrame method In-Reply-To: References: <4DF8E610-E149-47C3-9ECD-47456EBD1232@looktowindward.com> Message-ID: Thanks! That fixed it! > On 6 Jun 2022, at 18:46, MRAB wrote: > > On 2022-06-06 11:37, Dave wrote: >> Hi, >> I?m trying to get the ID3 tags of an mp3 file. I trying to use the MusicCDIdFrame >> method but I can?t seem to get it right. Here is a code snippet: >> import eyed3 >> import eyed3.id3 >> import eyed3.id3.frames >> import eyed3.id3.apple >> import eyed3.mp3 >> myID3 = eyed3.load("/Users/Test/Life in the fast lane.mp3") >> myTitle = myID3.tag.title >> myArtist = myID3.tag.artist >> myAlbum = myID3.tag.album >> myAlbumArtist = myID3.tag.album_artist >> myComposer = myID3.tag.composer >> myPublisher = myID3.tag.publisher >> myGenre = myID3.tag.genre.name >> myCDID = myID3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'') >> When I run this, I get the following error: >> File "/Documents/Python/Test1/main.py", line 94, in >> myCDID = myID3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'') >> AttributeError: 'Mp3AudioFile' object has no attribute 'id3' >> Any help or suggestion greatly appreciated. > That line should be: > > myCDID = eyed3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'') > > Also remember that some attributes might be None, e.g. 'myID3.tag.genre' might be None. > > Another point: it's probably not worth importing the submodules of 'eyed3'; you're not gaining anything from it. > -- > https://mail.python.org/mailman/listinfo/python-list From Gronicus at SGA.Ninja Mon Jun 6 14:08:41 2022 From: Gronicus at SGA.Ninja (Steve GS) Date: Mon, 6 Jun 2022 14:08:41 -0400 Subject: Automatic Gain Control in Python? In-Reply-To: References: <013801d872d9$f8d13700$ea73a500$@SGA.Ninja> <015301d872f1$6bf9afc0$43ed0f40$@SGA.Ninja> <017501d8731a$43882750$ca9875f0$@SGA.Ninja> <010101d87553$6daa6ad0$48ff4070$@SGA.Ninja> Message-ID: <005001d879d0$74a0bfc0$5de23f40$@SGA.Ninja> Yes, it is real-time play back of a pre-recorded presentation. A juke box does the same thing. It plays records. You didn't put your quarter in to expect the band to play your piece live, did you? Same here, I am pulling in the programs and playing them for an audience. All I want to do is have some semblance of AGC audio since the sources don't seem to be able to do it. " I would strongly > recommend going for the much much easier method of simply downloading > the files as they are." As Bill Gates would say "You have not understood it from the start." No, downloading the files, all 48 of them every week, is not easier if I have to turn around and replay them through the system. What could be easier than to have the smart speaker do all that work and play the podcasts "live". All I want to do is jump in there between the Smart Speaker and the input to the intercom and twerk the audio a bit. Footnote: If you double major in psychology and reverse psychology, to they cancel each other out? -----Original Message----- From: Python-list On Behalf Of Phil Boutros Sent: Monday, June 6, 2022 12:39 PM To: python-list at python.org Subject: Re: Automatic Gain Control in Python? Chris Angelico wrote: > > General principle: If you're asking someone else for help, don't tell > them that your way is easier, because the obvious response is "go > ahead then, do it your own way". *Ding Ding Ding*...We have a winner! At least, that's where I dropped off. My experienced advice is all wrong for you? Sorry I couldn't help more. Good luck to you. > You're technically right in a sense: something that you already have > is, indeed, easier than something else. But downloading files is > *easy* in Python, and audio analysis on files is FAR easier than > real-time audio analysis with hysteresis avoidance. Also this. > Unless you have a really good > reason for sticking to the black-box system, I would strongly > recommend going for the much much easier method of simply downloading > the files as they are. As pretty much everyone else has said. Insisting on real-time processing of something that is itself pre-recorded is non-sensical. Phil -- AH#61 Wolf#14 BS#89 bus#1 CCB#1 SENS KOTC#4 philb at philb.ca http://philb.ca -- https://mail.python.org/mailman/listinfo/python-list From wlfraed at ix.netcom.com Mon Jun 6 13:35:00 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 06 Jun 2022 13:35:00 -0400 Subject: Help with Python/Eyed3 MusicCDIdFrame method References: <4DF8E610-E149-47C3-9ECD-47456EBD1232@looktowindward.com> Message-ID: On Mon, 6 Jun 2022 12:37:47 +0200, Dave declaimed the following: >Hi, > >I?m trying to get the ID3 tags of an mp3 file. I trying to use the MusicCDIdFrame > method but I can?t seem to get it right. Here is a code snippet: > > > import eyed3 >import eyed3.id3 >import eyed3.id3.frames >import eyed3.id3.apple As I understand the documentation, The last is Apple specific/non-standard information... https://eyed3.readthedocs.io/en/latest/eyed3.id3.html """ eyed3.id3.apple module Here lies Apple frames, all of which are non-standard. All of these would have been standard user text frames by anyone not being a bastard, on purpose. """ {I'm not thrilled by the documentation -- it is basically a collection on one-line doc-strings with absolutely no hints as to proper usage} > File "/Documents/Python/Test1/main.py", line 94, in > myCDID = myID3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'') >AttributeError: 'Mp3AudioFile' object has no attribute 'id3' """ eyed3.core.load(path, tag_version=None)[source] Loads the file identified by path and returns a concrete type of eyed3.core.AudioFile. If path is not a file an IOError is raised. None is returned when the file type (i.e. mime-type) is not recognized. The following AudioFile types are supported: eyed3.mp3.Mp3AudioFile - For mp3 audio files. eyed3.id3.TagFile - For raw ID3 data files. """ eyed3.id3.xxxx would appear to be specific to non-MP3 data files. So... I'd try the interactive environment and check each layer... dir(myID3) (based upon the error, there will not be a "id3" key; so try dir(myID3.xxxx) for each key you do find). > > >Any help or suggestion greatly appreciated. > Given this bit of source code from the documentation... def initTag(self, version=id3.ID3_DEFAULT_VERSION): """Add a id3.Tag to the file (removing any existing tag if one exists). """ self.tag = id3.Tag() self.tag.version = version self.tag.file_info = id3.FileInfo(self.path) return self.tag ... you probably need to be looking at myID3.tag.xxxx ... try dir(myID3.tag) and see what all may appear... IOW: the ID3 information has already been parsed into separate "tag" fields. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From philb at philb.ca Mon Jun 6 14:17:17 2022 From: philb at philb.ca (Phil Boutros) Date: Mon, 6 Jun 2022 18:17:17 -0000 (UTC) Subject: Automatic Gain Control in Python? References: <013801d872d9$f8d13700$ea73a500$@SGA.Ninja> <015301d872f1$6bf9afc0$43ed0f40$@SGA.Ninja> <017501d8731a$43882750$ca9875f0$@SGA.Ninja> <010101d87553$6daa6ad0$48ff4070$@SGA.Ninja> <005001d879d0$74a0bfc0$5de23f40$@SGA.Ninja> Message-ID: Steve GS wrote: > Yes, it is real-time play back of a pre-recorded presentation. > A juke box does the same thing. It plays records. > You didn't put your quarter in to expect the band to play your piece live, > did you? > > Same here, I am pulling in the programs and playing them for an audience. > All I want to do is have some semblance of AGC audio since the sources don't > seem to be able to do it. And if your metaphorical jukebox plays digital files, I would expect it to do any modifications to the *file* before playing, not try to modify the output as it analyzed what it was playing via its own output (for some reason), which is vastly more difficult. You're saying it here yourself: "I am pulling in the programs". Good, then modify them *before* playing them? Nope, you insist on getting them playing, then attempting to monitor them and modify them on the fly based on...some parameters that are unclear. But, once again, your way is clearly better, then go ahead and fill your boots on doing it your way. What do we know? Good luck to you. It once again appears that we are at an impasse. Let us know how it works out. Phil -- AH#61 Wolf#14 BS#89 bus#1 CCB#1 SENS KOTC#4 philb at philb.ca http://philb.ca From philb at philb.ca Mon Jun 6 14:19:25 2022 From: philb at philb.ca (Phil Boutros) Date: Mon, 6 Jun 2022 18:19:25 -0000 (UTC) Subject: Automatic Gain Control in Python? References: <013801d872d9$f8d13700$ea73a500$@SGA.Ninja> <015301d872f1$6bf9afc0$43ed0f40$@SGA.Ninja> <017501d8731a$43882750$ca9875f0$@SGA.Ninja> <010101d87553$6daa6ad0$48ff4070$@SGA.Ninja> Message-ID: Stefan Ram wrote: > > When a mike is used anyway: Some mobile devices have a mike > with AGC in the driver, so they usually record with AGC. In the name of all that is Holy, please don't suggest another intermediary step that may actually be taken seriously here! Do you really want a phone listening to this speaker while recording, and then...er...what? Feed that to the speaker again? This is a level of masochism that the Marquis de Sade would blush at. Phil -- AH#61 Wolf#14 BS#89 bus#1 CCB#1 SENS KOTC#4 philb at philb.ca http://philb.ca From Karsten.Hilbert at gmx.net Mon Jun 6 14:57:01 2022 From: Karsten.Hilbert at gmx.net (Karsten Hilbert) Date: Mon, 6 Jun 2022 20:57:01 +0200 Subject: Automatic Gain Control in Python? In-Reply-To: <005001d879d0$74a0bfc0$5de23f40$@SGA.Ninja> References: <017501d8731a$43882750$ca9875f0$@SGA.Ninja> <010101d87553$6daa6ad0$48ff4070$@SGA.Ninja> <005001d879d0$74a0bfc0$5de23f40$@SGA.Ninja> Message-ID: Am Mon, Jun 06, 2022 at 02:08:41PM -0400 schrieb Steve GS: > Yes, it is real-time play back of a pre-recorded presentation. ... What all of us around here don't understand is why you insist on not being able to modify the data to your heart's content inbetween this ... > [...] pulling in the programs ... and that ... > and playing them for an audience. ?? IOW, during the "and" phase. Best, Karsten -- GPG 40BE 5B0E C98E 1713 AFA6 5BC0 3BEA AC80 7D4F C89B From wlfraed at ix.netcom.com Mon Jun 6 15:05:00 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 06 Jun 2022 15:05:00 -0400 Subject: Automatic Gain Control in Python? References: <010101d87553$6daa6ad0$48ff4070$@SGA.Ninja> <629e350d.1c69fb81.cdc2b.5641@mx.google.com> Message-ID: <0fis9h5bpjs34i52rv770ltp7775i8cujm@4ax.com> On Mon, 06 Jun 2022 10:10:37 -0700 (PDT), Grant Edwards declaimed the following: >On 2022-06-06, Phil Boutros wrote: > >> As pretty much everyone else has said. Insisting on real-time >> processing of something that is itself pre-recorded is non-sensical. > >Downnloading a file, normalizing/compressing the volume, and then >streaming the result is three lines in a bash script (assuming you've >got wget, sox, and vlc installed). I assume that something similar >could be done in PowerShell on Windows. > >With the right libraries, it's probably about the same in Python. I would like to point out that "normalization" is not the same as "AGC", which is not the same as "compression"... So what really is desired here? Normalization MUST have the entire file available, as it needs to know the peak signal and adjusts the entire file to maximize the peak. AGC in contrast is a sliding window operation which attempts to level out the overall signal based upon previous "average". It is not "read a chunk, normalize the chunk, repeat". Aggressive AGC will wipe out any dynamics in an audio signal (I once had a cheap RatShack stereo cassette deck which used a fixed AGC on record -- try to imagine the hash it made when taping the 45rpm record of "The Night Chicago Died"... Every time the drum hit in the opening measures the "sirens" were suppressed only to rise in the interval before the next drum hit). Compression operates sample-by-sample, so can be applied live -- but is best used after the entire audio file has been normalized. Compression (at least as used by me in the past -- Vegas 6) /reduces/ the strong parts of the signal (anything above the specified threshold) by some defined ratio -- then adjusts the entire signal back up to maximize the "reduced" portion, thereby raising everything that fell below the threshold value. There may or may not be some hint of AGC in the algorithm used (the Audacity documents show attack/release settings acting as a limited AGC in that it responds when transitions above and below threshold occur). -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From ijbrewster at alaska.edu Mon Jun 6 18:28:41 2022 From: ijbrewster at alaska.edu (Israel Brewster) Date: Mon, 6 Jun 2022 14:28:41 -0800 Subject: Filtering XArray Datasets? Message-ID: <54352CCC-E1A5-4AF7-9E19-6B538A13A459@alaska.edu> I have some large (>100GB) datasets loaded into memory in a two-dimensional (X and Y) NumPy array backed XArray dataset. At one point I want to filter the data using a boolean array created by performing a boolean operation on the dataset that is, I want to filter the dataset for all points with a longitude value greater than, say, 50 and less than 60, just to give an example (hopefully that all makes sense?). Currently I am doing this by creating a boolean array (data[?latitude?]>50, for example), and then applying that boolean array to the dataset using .where(), with drop=True. This appears to work, but has two issues: 1) It?s slow. On my large datasets, applying where can take several minutes (vs. just seconds to use a boolean array to index a similarly sized numpy array) 2) It uses large amounts of memory (which is REALLY a problem when the array is already using 100GB+) What it looks like is that values corresponding to True in the boolean array are copied to a new XArray object, thereby potentially doubling memory usage until it is complete, at which point the original object can be dropped, thereby freeing the memory. Is there any solution for these issues? Some way to do an in-place filtering? --- Israel Brewster Software Engineer Alaska Volcano Observatory Geophysical Institute - UAF 2156 Koyukuk Drive Fairbanks AK 99775-7320 Work: 907-474-5172 cell: 907-328-9145 From wlfraed at ix.netcom.com Mon Jun 6 23:29:02 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 06 Jun 2022 23:29:02 -0400 Subject: Filtering XArray Datasets? References: <54352CCC-E1A5-4AF7-9E19-6B538A13A459@alaska.edu> Message-ID: On Mon, 6 Jun 2022 14:28:41 -0800, Israel Brewster declaimed the following: >I have some large (>100GB) datasets loaded into memory in a two-dimensional (X and Y) NumPy array backed Unless you have some massive number cruncher machine, with TB RAM, you are running with a lot of page swap -- and not just cached pages in unused RAM; actual disk I/O. Pretty much anything that has to scan the data is going to be slow! > >Currently I am doing this by creating a boolean array (data[?latitude?]>50, for example), and then applying that boolean array to the dataset using .where(), with drop=True. This appears to work, but has two issues: > FYI: your first paragraph said "longitude", not "latitude". >1) It?s slow. On my large datasets, applying where can take several minutes (vs. just seconds to use a boolean array to index a similarly sized numpy array) >2) It uses large amounts of memory (which is REALLY a problem when the array is already using 100GB+) > Personally, given the size of the data, and that it is going to involve lots of page swapping... I'd try to convert the datasets into some RDBM -- maybe with indices defined for latitude/longitude columns, allowing queries to scan the index to find matching records, and return those (perhaps for processing one at a time "for rec in cursor:" rather than doing a .fetchall(). Some RDBMs even have extensions for spatial data handling. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From martinp.dipaola at gmail.com Tue Jun 7 09:07:07 2022 From: martinp.dipaola at gmail.com (Martin Di Paola) Date: Tue, 7 Jun 2022 10:07:07 -0300 Subject: Filtering XArray Datasets? In-Reply-To: <54352CCC-E1A5-4AF7-9E19-6B538A13A459@alaska.edu> References: <54352CCC-E1A5-4AF7-9E19-6B538A13A459@alaska.edu> Message-ID: <20220607130707.xlq5monegamlqiyi@gmail.com> Hi, I'm not an expert on this so this is an educated guess: You are calling drop=True and I presume that you want to delete the rows of your dataset that satisfy a condition. That's a problem. If the underlying original data is stored in a dense contiguous array, deleting chunks of it will leave it with "holes". Unless the backend supports sparse implementations, it is likely that it will go for the easiest solution: copy the non-deleted rows in a new array. I don't know the details of you particular problem but most of the time the trick is in not letting the whole data to be loaded. Try to see if instead of loading all the dataset and then performing the filtering/selection, you can do the filtering during the loading. An alternative could use filtering "before" doing the real work. For example, if you have a CSV of >100GB you could write a program X that copies the dataset into a new CSV but doing the filtering. Then, you load the filtered dataset and do the real work in a program Y. I explicitly named X and Y as, in principle, they are 2 different programs using even 2 different technologies. I hope this email can give you hints of how to fix it. In my last project I had a similar problem and I ended up doing the filtering on Python and the "real work" in Julia. Thanks! Martin. On Mon, Jun 06, 2022 at 02:28:41PM -0800, Israel Brewster wrote: >I have some large (>100GB) datasets loaded into memory in a two-dimensional (X and Y) NumPy array backed XArray dataset. At one point I want to filter the data using a boolean array created by performing a boolean operation on the dataset that is, I want to filter the dataset for all points with a longitude value greater than, say, 50 and less than 60, just to give an example (hopefully that all makes sense?). > >Currently I am doing this by creating a boolean array (data[?latitude?]>50, for example), and then applying that boolean array to the dataset using .where(), with drop=True. This appears to work, but has two issues: > >1) It?s slow. On my large datasets, applying where can take several minutes (vs. just seconds to use a boolean array to index a similarly sized numpy array) >2) It uses large amounts of memory (which is REALLY a problem when the array is already using 100GB+) > >What it looks like is that values corresponding to True in the boolean array are copied to a new XArray object, thereby potentially doubling memory usage until it is complete, at which point the original object can be dropped, thereby freeing the memory. > >Is there any solution for these issues? Some way to do an in-place filtering? >--- >Israel Brewster >Software Engineer >Alaska Volcano Observatory >Geophysical Institute - UAF >2156 Koyukuk Drive >Fairbanks AK 99775-7320 >Work: 907-474-5172 >cell: 907-328-9145 > >-- >https://mail.python.org/mailman/listinfo/python-list From __peter__ at web.de Tue Jun 7 09:42:31 2022 From: __peter__ at web.de (Peter Otten) Date: Tue, 7 Jun 2022 15:42:31 +0200 Subject: Filtering XArray Datasets? In-Reply-To: <54352CCC-E1A5-4AF7-9E19-6B538A13A459@alaska.edu> References: <54352CCC-E1A5-4AF7-9E19-6B538A13A459@alaska.edu> Message-ID: On 07/06/2022 00:28, Israel Brewster wrote: > I have some large (>100GB) datasets loaded into memory in a two-dimensional (X and Y) NumPy array backed XArray dataset. At one point I want to filter the data using a boolean array created by performing a boolean operation on the dataset that is, I want to filter the dataset for all points with a longitude value greater than, say, 50 and less than 60, just to give an example (hopefully that all makes sense?). > > Currently I am doing this by creating a boolean array (data[?latitude?]>50, for example), and then applying that boolean array to the dataset using .where(), with drop=True. This appears to work, but has two issues: > > 1) It?s slow. On my large datasets, applying where can take several minutes (vs. just seconds to use a boolean array to index a similarly sized numpy array) > 2) It uses large amounts of memory (which is REALLY a problem when the array is already using 100GB+) > > What it looks like is that values corresponding to True in the boolean array are copied to a new XArray object, thereby potentially doubling memory usage until it is complete, at which point the original object can be dropped, thereby freeing the memory. > > Is there any solution for these issues? Some way to do an in-place filtering? Can XArray-s be sorted, resized in-place? If so, you can sort by longitude <= 50, search the index of the first row with longitude <= 50 and then resize the array. (If the order of rows matters the sort algorithme has to be stable) From dave at looktowindward.com Tue Jun 7 15:35:43 2022 From: dave at looktowindward.com (Dave) Date: Tue, 7 Jun 2022 21:35:43 +0200 Subject: How to test characters of a string Message-ID: Hi, I?m new to Python and have a simple problem that I can?t seem to find the answer. I want to test the first two characters of a string to check if the are numeric (00 to 99) and if so remove the fist three chars from the string. Example: if ?05 Trinket? I want ?Trinket?, but ?Trinket? I still want ?Trinket?. I can?t for the life of work out how to do it in Python? All the Best Dave From PythonList at DancesWithMice.info Tue Jun 7 15:57:22 2022 From: PythonList at DancesWithMice.info (dn) Date: Wed, 8 Jun 2022 07:57:22 +1200 Subject: How to test characters of a string In-Reply-To: References: Message-ID: <65ca189b-0836-d214-e625-cc977ba9a4f5@DancesWithMice.info> On 08/06/2022 07.35, Dave wrote: > Hi, > > I?m new to Python and have a simple problem that I can?t seem to find the answer. > I want to test the first two characters of a string to check if the are numeric (00 to 99) and if so remove the fist three chars from the string. > > Example: if ?05 Trinket? I want ?Trinket?, but ?Trinket? I still want ?Trinket?. I can?t for the life of work out how to do it in Python? This sounds like an assignment or quiz-question. We could provide an/the answer - but then you wouldn't learn how to solve it for yourself... There is a gentle introduction to "slicing" (taking the first two characters) at https://docs.python.org/3/tutorial/introduction.html?highlight=slicing Characters can be turned into int[egers], as discussed at https://docs.python.org/3/library/stdtypes.html#typesnumeric Of course precautions must be taken in case the string is not an integer, eg https://docs.python.org/3/tutorial/errors.html?highlight=except Another approach might be to use isnumeric(), https://docs.python.org/3/library/stdtypes.html?highlight=isnum NB the first URL-pointer is a page in the Python Tutorial. Reading that in its entirety may be a good investment of time! Are you aware of the Python Tutor list? -- Regards, =dn From ongekruisigde at news.eternal-september.org Tue Jun 7 15:58:06 2022 From: ongekruisigde at news.eternal-september.org (De ongekruisigde) Date: Tue, 7 Jun 2022 19:58:06 -0000 (UTC) Subject: How to test characters of a string References: Message-ID: On 2022-06-07, Dave wrote: > Hi, > > I?m new to Python and have a simple problem that I can?t seem to find the answer. > > I want to test the first two characters of a string to check if the are numeric (00 to 99) and if so remove the fist three chars from the string. > > Example: if ?05 Trinket? I want ?Trinket?, but ?Trinket? I still want ?Trinket?. I can?t for the life of work out how to do it in Python? s[3:] if s[0:2].isdigit() else s > All the Best > Dave > -- You're rewriting parts of Quake in *Python*? MUAHAHAHA From dave at looktowindward.com Tue Jun 7 16:23:16 2022 From: dave at looktowindward.com (Dave) Date: Tue, 7 Jun 2022 22:23:16 +0200 Subject: How to test characters of a string In-Reply-To: References: Message-ID: Thanks a lot for this! isDigit was the method I was looking for and couldn?t find. I have another problem related to this, the following code uses the code you just sent. I am getting a files ID3 tags using eyed3, this part seems to work and I get expected values in this case myTitleName (Track name) is set to ?Deadlock Holiday? and myCompareFileName is set to ?01 Deadlock Holiday? (File Name with the Track number prepended). The is digit test works and myCompareFileName is set to ?Deadlock Holiday?, so they should match, right? However the if myCompareFileName != myTitleName always gives a mismatch! What could cause two string that look the fail to not match properly? myCompareFileName = myFile if myCompareFileName[0].isdigit() and myCompareFileName[1].isdigit(): myCompareFileName = myCompareFileName[3:] if myCompareFileName != myTitleName: print('File Name Mismatch - Artist: ',myArtistName,' Album: ',myAlbumName,' Track:',myTitleName,' File: ',myFile) Thanks a lot Dave > On 7 Jun 2022, at 21:58, De ongekruisigde wrote: > > On 2022-06-07, Dave wrote: >> Hi, >> >> I?m new to Python and have a simple problem that I can?t seem to find the answer. >> >> I want to test the first two characters of a string to check if the are numeric (00 to 99) and if so remove the fist three chars from the string. >> >> Example: if ?05 Trinket? I want ?Trinket?, but ?Trinket? I still want ?Trinket?. I can?t for the life of work out how to do it in Python? > > > s[3:] if s[0:2].isdigit() else s > > >> All the Best >> Dave >> > > -- > You're rewriting parts of Quake in *Python*? > MUAHAHAHA > -- > https://mail.python.org/mailman/listinfo/python-list From 2QdxY4RzWzUUiLuE at potatochowder.com Tue Jun 7 16:08:10 2022 From: 2QdxY4RzWzUUiLuE at potatochowder.com (2QdxY4RzWzUUiLuE at potatochowder.com) Date: Tue, 7 Jun 2022 15:08:10 -0500 Subject: How to test characters of a string In-Reply-To: References: Message-ID: On 2022-06-07 at 21:35:43 +0200, Dave wrote: > I?m new to Python and have a simple problem that I can?t seem to find > the answer. > I want to test the first two characters of a string to check if the > are numeric (00 to 99) and if so remove the fist three chars from the > string. > Example: if ?05 Trinket? I want ?Trinket?, but ?Trinket? I still want > ?Trinket?. I can?t for the life of work out how to do it in Python? How would you do it without Python? Given that if the string is called x, then x[y] is the y'th character (where what you would call "the first character," Python calls "the zeroth character"), describe the steps you would take *as a person* (or in some other programming language, if you know one) to carry out this task. Translating that algorithm to Python is the next step. Perhaps https://docs.python.org/3/library/string.html can help. From ongekruisigde at news.eternal-september.org Tue Jun 7 16:15:12 2022 From: ongekruisigde at news.eternal-september.org (De ongekruisigde) Date: Tue, 7 Jun 2022 20:15:12 -0000 (UTC) Subject: How to test characters of a string References: Message-ID: On 2022-06-07, Stefan Ram wrote: > Dave writes: >>Example: if "05 Trinket" I want "Trinket" > > We're not supposed to write complete solutions, Okay, wasn't aware of this group policy; will keep it in mind. -- You're rewriting parts of Quake in *Python*? MUAHAHAHA From ongekruisigde at news.eternal-september.org Tue Jun 7 16:35:22 2022 From: ongekruisigde at news.eternal-september.org (De ongekruisigde) Date: Tue, 7 Jun 2022 20:35:22 -0000 (UTC) Subject: How to test characters of a string References: Message-ID: On 2022-06-07, Dave wrote: > Thanks a lot for this! isDigit was the method I was looking for and couldn?t find. > > I have another problem related to this, the following code uses the code you just sent. I am getting a files ID3 tags using eyed3, this part seems to work and I get expected values in this case myTitleName (Track name) is set to ?Deadlock Holiday? and myCompareFileName is set to ?01 Deadlock Holiday? (File Name with the Track number prepended). The is digit test works and myCompareFileName is set to ?Deadlock Holiday?, so they should match, right? > > However the if myCompareFileName != myTitleName always gives a mismatch! What could cause two string that look the fail to not match properly? Possibly leading or trailing spaces, or upper/lower case differences? > myCompareFileName = myFile > if myCompareFileName[0].isdigit() and myCompareFileName[1].isdigit(): > myCompareFileName = myCompareFileName[3:] > > if myCompareFileName != myTitleName: > print('File Name Mismatch - Artist: ',myArtistName,' Album: ',myAlbumName,' Track:',myTitleName,' File: ',myFile) > Thanks a lot > Dave > >> On 7 Jun 2022, at 21:58, De ongekruisigde wrote: >> >> On 2022-06-07, Dave wrote: >>> Hi, >>> >>> I?m new to Python and have a simple problem that I can?t seem to find the answer. >>> >>> I want to test the first two characters of a string to check if the are numeric (00 to 99) and if so remove the fist three chars from the string. >>> >>> Example: if ?05 Trinket? I want ?Trinket?, but ?Trinket? I still want ?Trinket?. I can?t for the life of work out how to do it in Python? >> >> >> s[3:] if s[0:2].isdigit() else s >> >> >>> All the Best >>> Dave >>> >> >> -- >> You're rewriting parts of Quake in *Python*? >> MUAHAHAHA >> -- >> https://mail.python.org/mailman/listinfo/python-list > -- You're rewriting parts of Quake in *Python*? MUAHAHAHA From dave at looktowindward.com Tue Jun 7 16:56:50 2022 From: dave at looktowindward.com (Dave) Date: Tue, 7 Jun 2022 22:56:50 +0200 Subject: How to test characters of a string In-Reply-To: References: Message-ID: It depends on the language I?m using, in Objective C, I?d use isNumeric, just wanted to know what the equivalent is in Python. If you know the answer why don?t you just tell me and if you don?t, don?t post! > On 7 Jun 2022, at 22:08, 2QdxY4RzWzUUiLuE at potatochowder.com wrote: > > On 2022-06-07 at 21:35:43 +0200, > Dave wrote: > >> I?m new to Python and have a simple problem that I can?t seem to find >> the answer. > >> I want to test the first two characters of a string to check if the >> are numeric (00 to 99) and if so remove the fist three chars from the >> string. > >> Example: if ?05 Trinket? I want ?Trinket?, but ?Trinket? I still want >> ?Trinket?. I can?t for the life of work out how to do it in Python? > > How would you do it without Python? > > Given that if the string is called x, then x[y] is the y'th character > (where what you would call "the first character," Python calls "the > zeroth character"), describe the steps you would take *as a person* (or > in some other programming language, if you know one) to carry out this > task. > > Translating that algorithm to Python is the next step. Perhaps > https://docs.python.org/3/library/string.html can help. > -- > https://mail.python.org/mailman/listinfo/python-list From dave at looktowindward.com Tue Jun 7 17:01:57 2022 From: dave at looktowindward.com (Dave) Date: Tue, 7 Jun 2022 23:01:57 +0200 Subject: How to test characters of a string In-Reply-To: References: Message-ID: <173AD63B-9DDC-4CC9-9C92-2583DCB0364F@looktowindward.com> Hi, No, I?ve checked leading/trailing whitespace, it seems to be related to the variables that are returned from eyed3 in this case, for instance, I added a check for None: myTitleName = myID3.tag.title if myTitleName is None: continue Seems like it can return a null object (or none?). > On 7 Jun 2022, at 22:35, De ongekruisigde wrote: > > On 2022-06-07, Dave > wrote: >> Thanks a lot for this! isDigit was the method I was looking for and couldn?t find. >> >> I have another problem related to this, the following code uses the code you just sent. I am getting a files ID3 tags using eyed3, this part seems to work and I get expected values in this case myTitleName (Track name) is set to ?Deadlock Holiday? and myCompareFileName is set to ?01 Deadlock Holiday? (File Name with the Track number prepended). The is digit test works and myCompareFileName is set to ?Deadlock Holiday?, so they should match, right? >> >> However the if myCompareFileName != myTitleName always gives a mismatch! What could cause two string that look the fail to not match properly? > > Possibly leading or trailing spaces, or upper/lower case differences? > > >> myCompareFileName = myFile >> if myCompareFileName[0].isdigit() and myCompareFileName[1].isdigit(): >> myCompareFileName = myCompareFileName[3:] >> >> if myCompareFileName != myTitleName: >> print('File Name Mismatch - Artist: ',myArtistName,' Album: ',myAlbumName,' Track:',myTitleName,' File: ',myFile) >> Thanks a lot >> Dave >> >>> On 7 Jun 2022, at 21:58, De ongekruisigde wrote: >>> >>> On 2022-06-07, Dave wrote: >>>> Hi, >>>> >>>> I?m new to Python and have a simple problem that I can?t seem to find the answer. >>>> >>>> I want to test the first two characters of a string to check if the are numeric (00 to 99) and if so remove the fist three chars from the string. >>>> >>>> Example: if ?05 Trinket? I want ?Trinket?, but ?Trinket? I still want ?Trinket?. I can?t for the life of work out how to do it in Python? >>> >>> >>> s[3:] if s[0:2].isdigit() else s >>> >>> >>>> All the Best >>>> Dave >>>> >>> >>> -- >>> You're rewriting parts of Quake in *Python*? >>> MUAHAHAHA >>> -- >>> https://mail.python.org/mailman/listinfo/python-list >> > > > -- > You're rewriting parts of Quake in *Python*? > MUAHAHAHA > -- > https://mail.python.org/mailman/listinfo/python-list From dave at looktowindward.com Tue Jun 7 17:10:35 2022 From: dave at looktowindward.com (Dave) Date: Tue, 7 Jun 2022 23:10:35 +0200 Subject: How to test characters of a string In-Reply-To: <173AD63B-9DDC-4CC9-9C92-2583DCB0364F@looktowindward.com> References: <173AD63B-9DDC-4CC9-9C92-2583DCB0364F@looktowindward.com> Message-ID: <4CD6E7CD-B95E-4EF7-9BE3-4EA0D82CB050@looktowindward.com> Hi, Found it! The files name had .mp3 at the end, the problem was being masked by null objects (or whatever) being returned by eyed3. Checked for null objects and then stripped off the .mp3 and its mostly working now. I?ve got a few other eyed3 errors to do with null objects but I can sort those out tomorrow. Thanks for your help - All the Best Dave > On 7 Jun 2022, at 23:01, Dave wrote: > > Hi, > > No, I?ve checked leading/trailing whitespace, it seems to be related to the variables that are returned from eyed3 in this case, for instance, I added a check for None: > myTitleName = myID3.tag.title > if myTitleName is None: > continue > Seems like it can return a null object (or none?). > > >> On 7 Jun 2022, at 22:35, De ongekruisigde > wrote: >> >> On 2022-06-07, Dave >> wrote: >>> Thanks a lot for this! isDigit was the method I was looking for and couldn?t find. >>> >>> I have another problem related to this, the following code uses the code you just sent. I am getting a files ID3 tags using eyed3, this part seems to work and I get expected values in this case myTitleName (Track name) is set to ?Deadlock Holiday? and myCompareFileName is set to ?01 Deadlock Holiday? (File Name with the Track number prepended). The is digit test works and myCompareFileName is set to ?Deadlock Holiday?, so they should match, right? >>> >>> However the if myCompareFileName != myTitleName always gives a mismatch! What could cause two string that look the fail to not match properly? >> >> Possibly leading or trailing spaces, or upper/lower case differences? >> >> >>> myCompareFileName = myFile >>> if myCompareFileName[0].isdigit() and myCompareFileName[1].isdigit(): >>> myCompareFileName = myCompareFileName[3:] >>> >>> if myCompareFileName != myTitleName: >>> print('File Name Mismatch - Artist: ',myArtistName,' Album: ',myAlbumName,' Track:',myTitleName,' File: ',myFile) >>> Thanks a lot >>> Dave >>> >>>> On 7 Jun 2022, at 21:58, De ongekruisigde wrote: >>>> >>>> On 2022-06-07, Dave wrote: >>>>> Hi, >>>>> >>>>> I?m new to Python and have a simple problem that I can?t seem to find the answer. >>>>> >>>>> I want to test the first two characters of a string to check if the are numeric (00 to 99) and if so remove the fist three chars from the string. >>>>> >>>>> Example: if ?05 Trinket? I want ?Trinket?, but ?Trinket? I still want ?Trinket?. I can?t for the life of work out how to do it in Python? >>>> >>>> >>>> s[3:] if s[0:2].isdigit() else s >>>> >>>> >>>>> All the Best >>>>> Dave >>>>> >>>> >>>> -- >>>> You're rewriting parts of Quake in *Python*? >>>> MUAHAHAHA >>>> -- >>>> https://mail.python.org/mailman/listinfo/python-list >>> >> >> >> -- >> You're rewriting parts of Quake in *Python*? >> MUAHAHAHA >> -- >> https://mail.python.org/mailman/listinfo/python-list > > -- > https://mail.python.org/mailman/listinfo/python-list From barry at barrys-emacs.org Tue Jun 7 17:22:50 2022 From: barry at barrys-emacs.org (Barry) Date: Tue, 7 Jun 2022 22:22:50 +0100 Subject: How to test characters of a string In-Reply-To: References: Message-ID: <0266F855-0776-4A75-937B-E4AC79DF8D78@barrys-emacs.org> > On 7 Jun 2022, at 22:04, Dave wrote: > > ?It depends on the language I?m using, in Objective C, I?d use isNumeric, just wanted to know what the equivalent is in Python. > > If you know the answer why don?t you just tell me and if you don?t, don?t post! People ask home work questions here and we try to teach a student with hints not finished answers. Your post was confused with a home work question. Barry > > >> On 7 Jun 2022, at 22:08, 2QdxY4RzWzUUiLuE at potatochowder.com wrote: >> >>> On 2022-06-07 at 21:35:43 +0200, >>> Dave wrote: >>> >>> I?m new to Python and have a simple problem that I can?t seem to find >>> the answer. >> >>> I want to test the first two characters of a string to check if the >>> are numeric (00 to 99) and if so remove the fist three chars from the >>> string. >> >>> Example: if ?05 Trinket? I want ?Trinket?, but ?Trinket? I still want >>> ?Trinket?. I can?t for the life of work out how to do it in Python? >> >> How would you do it without Python? >> >> Given that if the string is called x, then x[y] is the y'th character >> (where what you would call "the first character," Python calls "the >> zeroth character"), describe the steps you would take *as a person* (or >> in some other programming language, if you know one) to carry out this >> task. >> >> Translating that algorithm to Python is the next step. Perhaps >> https://docs.python.org/3/library/string.html can help. >> -- >> https://mail.python.org/mailman/listinfo/python-list > > -- > https://mail.python.org/mailman/listinfo/python-list From rosuav at gmail.com Tue Jun 7 17:29:03 2022 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 8 Jun 2022 07:29:03 +1000 Subject: How to test characters of a string In-Reply-To: <0266F855-0776-4A75-937B-E4AC79DF8D78@barrys-emacs.org> References: <0266F855-0776-4A75-937B-E4AC79DF8D78@barrys-emacs.org> Message-ID: On Wed, 8 Jun 2022 at 07:24, Barry wrote: > > > > > On 7 Jun 2022, at 22:04, Dave wrote: > > > > ?It depends on the language I?m using, in Objective C, I?d use isNumeric, just wanted to know what the equivalent is in Python. > > > > If you know the answer why don?t you just tell me and if you don?t, don?t post! > > People ask home work questions here and we try to teach a student with hints not finished answers. > Your post was confused with a home work question. > In the future, to make it look less like a homework question, show your current code, which would provide context. Last I checked, homework questions don't usually involve ID3 tags in MP3 files :) ChrisA From dave at looktowindward.com Tue Jun 7 17:33:51 2022 From: dave at looktowindward.com (Dave) Date: Tue, 7 Jun 2022 23:33:51 +0200 Subject: How to test characters of a string In-Reply-To: References: <0266F855-0776-4A75-937B-E4AC79DF8D78@barrys-emacs.org> Message-ID: Ahhhh, ok will do, was just trying to be a brief as possible, will post more fully in future. > On 7 Jun 2022, at 23:29, Chris Angelico wrote: > > On Wed, 8 Jun 2022 at 07:24, Barry wrote: >> >> >> >>> On 7 Jun 2022, at 22:04, Dave wrote: >>> >>> ?It depends on the language I?m using, in Objective C, I?d use isNumeric, just wanted to know what the equivalent is in Python. >>> >>> If you know the answer why don?t you just tell me and if you don?t, don?t post! >> >> People ask home work questions here and we try to teach a student with hints not finished answers. >> Your post was confused with a home work question. >> > > In the future, to make it look less like a homework question, show > your current code, which would provide context. Last I checked, > homework questions don't usually involve ID3 tags in MP3 files :) > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list From 2QdxY4RzWzUUiLuE at potatochowder.com Tue Jun 7 17:46:38 2022 From: 2QdxY4RzWzUUiLuE at potatochowder.com (2QdxY4RzWzUUiLuE at potatochowder.com) Date: Tue, 7 Jun 2022 16:46:38 -0500 Subject: How to test characters of a string In-Reply-To: References: <0266F855-0776-4A75-937B-E4AC79DF8D78@barrys-emacs.org> Message-ID: On 2022-06-08 at 07:29:03 +1000, Chris Angelico wrote: > On Wed, 8 Jun 2022 at 07:24, Barry wrote: > > > > > > > > > On 7 Jun 2022, at 22:04, Dave wrote: > > > > > > ?It depends on the language I?m using, in Objective C, I?d use isNumeric, just wanted to know what the equivalent is in Python. > > > > > > If you know the answer why don?t you just tell me and if you don?t, don?t post! > > > > People ask home work questions here and we try to teach a student with hints not finished answers. > > Your post was confused with a home work question. > > > > In the future, to make it look less like a homework question, show > your current code, which would provide context. Last I checked, > homework questions don't usually involve ID3 tags in MP3 files :) The original question in this thread didn't say anything about MP3 files. Jumping to that conclusion from strings like '05 Trinket' was left as an exercise for the interested reader. :-) From python at mrabarnett.plus.com Tue Jun 7 18:07:42 2022 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 7 Jun 2022 23:07:42 +0100 Subject: How to test characters of a string In-Reply-To: References: Message-ID: <05496acc-02ec-a789-8df7-80c69b4390c5@mrabarnett.plus.com> On 2022-06-07 21:23, Dave wrote: > Thanks a lot for this! isDigit was the method I was looking for and couldn?t find. > > I have another problem related to this, the following code uses the code you just sent. I am getting a files ID3 tags using eyed3, this part seems to work and I get expected values in this case myTitleName (Track name) is set to ?Deadlock Holiday? and myCompareFileName is set to ?01 Deadlock Holiday? (File Name with the Track number prepended). The is digit test works and myCompareFileName is set to ?Deadlock Holiday?, so they should match, right? > OT, but are you sure about that name? Isn't it "Dreadlock Holiday" (by 10cc)? [snip] From 2QdxY4RzWzUUiLuE at potatochowder.com Tue Jun 7 18:24:42 2022 From: 2QdxY4RzWzUUiLuE at potatochowder.com (2QdxY4RzWzUUiLuE at potatochowder.com) Date: Tue, 7 Jun 2022 17:24:42 -0500 Subject: How to test characters of a string In-Reply-To: <05496acc-02ec-a789-8df7-80c69b4390c5@mrabarnett.plus.com> References: <05496acc-02ec-a789-8df7-80c69b4390c5@mrabarnett.plus.com> Message-ID: On 2022-06-07 at 23:07:42 +0100, Regarding "Re: How to test characters of a string," MRAB wrote: > On 2022-06-07 21:23, Dave wrote: > > Thanks a lot for this! isDigit was the method I was looking for and couldn?t find. > > > > I have another problem related to this, the following code uses the code you just sent. I am getting a files ID3 tags using eyed3, this part seems to work and I get expected values in this case myTitleName (Track name) is set to ?Deadlock Holiday? and myCompareFileName is set to ?01 Deadlock Holiday? (File Name with the Track number prepended). The is digit test works and myCompareFileName is set to ?Deadlock Holiday?, so they should match, right? > > > OT, but are you sure about that name? Isn't it "Dreadlock Holiday" (by > 10cc)? Edsger Dijkstra originally wrote Deadlock Holiday for his band, The Semaphores. 10cc lost the race condition and had to change the lyrics. Sorry. From dave at looktowindward.com Tue Jun 7 18:24:43 2022 From: dave at looktowindward.com (Dave) Date: Wed, 8 Jun 2022 00:24:43 +0200 Subject: How to test characters of a string In-Reply-To: <05496acc-02ec-a789-8df7-80c69b4390c5@mrabarnett.plus.com> References: <05496acc-02ec-a789-8df7-80c69b4390c5@mrabarnett.plus.com> Message-ID: <00D0FBD1-77E5-4804-8154-F5D31914564F@looktowindward.com> Yes, it was probably just a typeo on my part. I?ve now fixed the majority of cases but still got two strings that look identical but fail to match, this time (again by 10cc), ?I?m Mandy Fly Me?. I?m putting money on it being a utf8 problem but I?m stuck on how to handle it. It?s probably the single quote in I?m, although it has worked with other songs. Any ideas? All the Best Cheers Dave Here is the whole function/method or whatever it?s called in Python: ################################################################################ # # checkMusicFiles # ################################################################################ def checkMusicFiles(theBaseMusicLibraryFolder): myArtistDict = [] # # Loop thru Artists Folder # myArtistsFoldlerList = getFolderList(theBaseMusicLibraryFolder) myArtistCount = 0 for myArtistFolder in myArtistsFoldlerList: print('Artist: ' + myArtistFolder) # # Loop thru Albums Folder # myAlbumList = getFolderList(theBaseMusicLibraryFolder + myArtistFolder) for myAlbum in myAlbumList: print('Album: ' + myAlbum) # # Loop thru Tracks (Files) Folder # myAlbumPath = theBaseMusicLibraryFolder + myArtistFolder + '/' + myAlbum + '/' myFilesList = getFileList(myAlbumPath) for myFile in myFilesList: myFilePath = myAlbumPath + myFile myID3 = eyed3.load(myFilePath) if myID3 is None: continue myArtistName = myID3.tag.artist if myArtistName is None: continue myAlbumName = myID3.tag.album if myAlbumName is None: continue myTitleName = myID3.tag.title if myTitleName is None: continue myCompareFileName = myFile[0:-4] if myCompareFileName[0].isdigit() and myCompareFileName[1].isdigit(): myCompareFileName = myFile[3:-4] if myCompareFileName != myTitleName: myLength1 = len(myCompareFileName) myLength2 = len(myTitleName) print('File Name Mismatch - Artist: [' + myArtistName + '] Album: ['+ myAlbumName + '] Track: [' + myTitleName + '] File: [' + myCompareFileName + ']') if (myLength1 == myLength2): print('lengths match: ',myLength1) else: print('lengths mismatch: ',myLength1,' ',myLength2) print(' ') return myArtistsFoldlerList > On 8 Jun 2022, at 00:07, MRAB wrote: > > On 2022-06-07 21:23, Dave wrote: >> Thanks a lot for this! isDigit was the method I was looking for and couldn?t find. >> I have another problem related to this, the following code uses the code you just sent. I am getting a files ID3 tags using eyed3, this part seems to work and I get expected values in this case myTitleName (Track name) is set to ?Deadlock Holiday? and myCompareFileName is set to ?01 Deadlock Holiday? (File Name with the Track number prepended). The is digit test works and myCompareFileName is set to ?Deadlock Holiday?, so they should match, right? > OT, but are you sure about that name? Isn't it "Dreadlock Holiday" (by 10cc)? > > [snip] > -- > https://mail.python.org/mailman/listinfo/python-list From auriocus at gmx.de Tue Jun 7 18:01:20 2022 From: auriocus at gmx.de (Christian Gollwitzer) Date: Tue, 7 Jun 2022 23:01:20 +0100 Subject: How to test characters of a string In-Reply-To: References: Message-ID: Am 07.06.22 um 21:56 schrieb Dave: > It depends on the language I?m using, in Objective C, I?d use isNumeric, just wanted to know what the equivalent is in Python. > Your problem is also a typical case for regular expressions. You can create an expression for "starts with any number of digits plus optional whitespace" and then replace this with nothing: > chris at linux-tb9f:~> ipython > Python 3.6.15 (default, Sep 23 2021, 15:41:43) [GCC] > Type 'copyright', 'credits' or 'license' for more information > IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help. > > In [1]: import re > > In [2]: s='05 Trinket' > > In [3]: re.sub(r'^\d+\s*', '', s) > Out[3]: 'Trinket' > If it doesn't match, it will do nothing: > In [4]: s='Es geht los' > > In [5]: re.sub(r'^\d+\s*', '', s) > Out[5]: 'Es geht los' Some people on this list don't like regexes but for tasks like this they are made and working well. ^ is "starts with" \d is any digit \s is any space + is at least one * is nothing or one of Christian From auriocus at gmx.de Tue Jun 7 18:04:44 2022 From: auriocus at gmx.de (Christian Gollwitzer) Date: Tue, 7 Jun 2022 23:04:44 +0100 Subject: How to test characters of a string In-Reply-To: References: Message-ID: Am 07.06.22 um 23:01 schrieb Christian Gollwitzer: >> In [3]: re.sub(r'^\d+\s*', '', s) Out[3]: 'Trinket' >> that RE does match what you intended to do, but not exactly what you wrote in the OP. that would be '^\d\d.' start with exactly two digits followed by any character. Christian From ongekruisigde at news.eternal-september.org Tue Jun 7 18:18:17 2022 From: ongekruisigde at news.eternal-september.org (De ongekruisigde) Date: Tue, 7 Jun 2022 22:18:17 -0000 (UTC) Subject: How to test characters of a string References: Message-ID: On 2022-06-08, Christian Gollwitzer wrote: > Am 07.06.22 um 21:56 schrieb Dave: >> It depends on the language I?m using, in Objective C, I?d use isNumeric, just wanted to know what the equivalent is in Python. >> > > Your problem is also a typical case for regular expressions. You can > create an expression for "starts with any number of digits plus optional > whitespace" and then replace this with nothing: Regular expressions are overkill for this and much slower than the simple isdigit based solution. >> chris at linux-tb9f:~> ipython >> Python 3.6.15 (default, Sep 23 2021, 15:41:43) [GCC] >> Type 'copyright', 'credits' or 'license' for more information >> IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help. >> >> In [1]: import re >> >> In [2]: s='05 Trinket' >> >> In [3]: re.sub(r'^\d+\s*', '', s) >> Out[3]: 'Trinket' >> > > If it doesn't match, it will do nothing: > >> In [4]: s='Es geht los' >> >> In [5]: re.sub(r'^\d+\s*', '', s) >> Out[5]: 'Es geht los' > > Some people on this list don't like regexes but for tasks like this they > are made and working well. Regular expressions are indeeed extremely powerful and useful but I tend to avoid them when there's a (faster) normal solution. > ^ is "starts with" > \d is any digit > \s is any space > + is at least one > * is nothing or one of > > Christian -- You're rewriting parts of Quake in *Python*? MUAHAHAHA From PythonList at DancesWithMice.info Tue Jun 7 18:32:38 2022 From: PythonList at DancesWithMice.info (dn) Date: Wed, 8 Jun 2022 10:32:38 +1200 Subject: How to test characters of a string In-Reply-To: References: <0266F855-0776-4A75-937B-E4AC79DF8D78@barrys-emacs.org> Message-ID: <3e2369c4-9862-39c7-fd4f-63095f345466@DancesWithMice.info> >>>> ?It depends on the language I?m using, in Objective C, I?d use isNumeric, just wanted to know what the equivalent is in Python. >>>> >>>> If you know the answer why don?t you just tell me and if you don?t, don?t post! >>> >>> People ask home work questions here and we try to teach a student with hints not finished answers. >>> Your post was confused with a home work question. >> >> In the future, to make it look less like a homework question, show >> your current code, which would provide context. Last I checked, >> homework questions don't usually involve ID3 tags in MP3 files :) Ah, so that's where I've seen it before! (thanks for scratching my head @Chris - but watch-out for splinters!) Yes, the problem has been used as a training exercise, eg same song but in different albums/play-lists, different capitalisation, and such-like; ie 'data cleaning' and harmonisation - good for use at the intersection of Python and SQL (or NoSQL). Knowing the background, and thus the particular need, would have saved a lot of time - giving the answer as code (per one of the contributions) would have taken considerably less effort than looking-up and citing the docs. Perhaps then, the 'learning-opportunity' is that when such questions pop into one's mind, 'the docs' is *the* recommended first-call? > The original question in this thread didn't say anything about MP3 > files. Jumping to that conclusion from strings like '05 Trinket' was > left as an exercise for the interested reader. :-) This reader's interest was to figure-out why "trinket" didn't refer to some small decoration or 'bling', nor to a Python training tool (https://trinket.io/), but to a music group/video series. (even more-surprising: that this grey-beard recognised one of their tracks). On the other side of the relationship, writers are expected to follow the PSF Code of Conduct (https://www.python.org/psf/conduct/), eg respect, acknowledgement, grace... Such also encourages (positive) responses when asking future questions... Now that you (@Dave) have revealed yourself as more than a raw-beginner, and to have skills transferable to the Python world, it'll be great to see you 'here', contributing to others' posts... -- Regards, =dn From dave at looktowindward.com Tue Jun 7 18:38:54 2022 From: dave at looktowindward.com (Dave) Date: Wed, 8 Jun 2022 00:38:54 +0200 Subject: How to test characters of a string In-Reply-To: References: <05496acc-02ec-a789-8df7-80c69b4390c5@mrabarnett.plus.com> Message-ID: rotfl!!!!! Nice one! > On 8 Jun 2022, at 00:24, 2QdxY4RzWzUUiLuE at potatochowder.com wrote: > > On 2022-06-07 at 23:07:42 +0100, > Regarding "Re: How to test characters of a string," > MRAB wrote: > >> On 2022-06-07 21:23, Dave wrote: >>> Thanks a lot for this! isDigit was the method I was looking for and couldn?t find. >>> >>> I have another problem related to this, the following code uses the code you just sent. I am getting a files ID3 tags using eyed3, this part seems to work and I get expected values in this case myTitleName (Track name) is set to ?Deadlock Holiday? and myCompareFileName is set to ?01 Deadlock Holiday? (File Name with the Track number prepended). The is digit test works and myCompareFileName is set to ?Deadlock Holiday?, so they should match, right? >>> >> OT, but are you sure about that name? Isn't it "Dreadlock Holiday" (by >> 10cc)? > > Edsger Dijkstra originally wrote Deadlock Holiday for his band, The > Semaphores. 10cc lost the race condition and had to change the lyrics. > > Sorry. > -- > https://mail.python.org/mailman/listinfo/python-list From PythonList at DancesWithMice.info Tue Jun 7 18:49:59 2022 From: PythonList at DancesWithMice.info (dn) Date: Wed, 8 Jun 2022 10:49:59 +1200 Subject: How to test characters of a string In-Reply-To: References: Message-ID: On 08/06/2022 10.18, De ongekruisigde wrote: > On 2022-06-08, Christian Gollwitzer wrote: >> Am 07.06.22 um 21:56 schrieb Dave: >>> It depends on the language I?m using, in Objective C, I?d use isNumeric, just wanted to know what the equivalent is in Python. >>> >> >> Your problem is also a typical case for regular expressions. You can >> create an expression for "starts with any number of digits plus optional >> whitespace" and then replace this with nothing: > > Regular expressions are overkill for this and much slower than the > simple isdigit based solution. ... > Regular expressions are indeeed extremely powerful and useful but I tend > to avoid them when there's a (faster) normal solution. Yes, simple solutions are (likely) easier to read. RegEx-s are more powerful (and well worth learning for this reason), but are only 'readable' to those who use them frequently. Has either of you performed a timeit comparison? -- Regards, =dn From dave at looktowindward.com Tue Jun 7 18:56:30 2022 From: dave at looktowindward.com (Dave) Date: Wed, 8 Jun 2022 00:56:30 +0200 Subject: How to test characters of a string In-Reply-To: References: Message-ID: <7AC4222A-CEEB-43BB-81B9-AE03F7E22F88@looktowindward.com> I hate regEx and avoid it whenever possible, I?ve never found something that was impossible to do without it. > On 8 Jun 2022, at 00:49, dn wrote: > > On 08/06/2022 10.18, De ongekruisigde wrote: >> On 2022-06-08, Christian Gollwitzer wrote: >>> Am 07.06.22 um 21:56 schrieb Dave: >>>> It depends on the language I?m using, in Objective C, I?d use isNumeric, just wanted to know what the equivalent is in Python. >>>> >>> >>> Your problem is also a typical case for regular expressions. You can >>> create an expression for "starts with any number of digits plus optional >>> whitespace" and then replace this with nothing: >> >> Regular expressions are overkill for this and much slower than the >> simple isdigit based solution. > > ... > >> Regular expressions are indeeed extremely powerful and useful but I tend >> to avoid them when there's a (faster) normal solution. > > Yes, simple solutions are (likely) easier to read. > > RegEx-s are more powerful (and well worth learning for this reason), but > are only 'readable' to those who use them frequently. > > Has either of you performed a timeit comparison? > -- > Regards, > =dn > -- > https://mail.python.org/mailman/listinfo/python-list From python at mrabarnett.plus.com Tue Jun 7 19:15:25 2022 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 8 Jun 2022 00:15:25 +0100 Subject: How to test characters of a string In-Reply-To: <00D0FBD1-77E5-4804-8154-F5D31914564F@looktowindward.com> References: <05496acc-02ec-a789-8df7-80c69b4390c5@mrabarnett.plus.com> <00D0FBD1-77E5-4804-8154-F5D31914564F@looktowindward.com> Message-ID: On 2022-06-07 23:24, Dave wrote: > Yes, it was probably just a typeo on my part. > You've misspelled "typo"! > I?ve now fixed the majority of cases but still got two strings that look identical but fail to match, this time (again by 10cc), ?I?m Mandy Fly Me?. > Try printing the asciified string: >>> print(ascii("I?m Mandy Fly Me")) 'I\u2019m Mandy Fly Me' What you typed above has "smart quotes". Maybe that's also the problem in the program: straight single quote/apodtrophe vs smart single quote. > I?m putting money on it being a utf8 problem but I?m stuck on how to handle it. It?s probably the single quote in I?m, although it has worked with other songs. > > Any ideas? > > All the Best > Cheers > Dave > > Here is the whole function/method or whatever it?s called in Python: > > ################################################################################ > # > # checkMusicFiles > # > ################################################################################ > def checkMusicFiles(theBaseMusicLibraryFolder): > myArtistDict = [] > > # > # Loop thru Artists Folder > # > myArtistsFoldlerList = getFolderList(theBaseMusicLibraryFolder) > myArtistCount = 0 > for myArtistFolder in myArtistsFoldlerList: > print('Artist: ' + myArtistFolder) > # > # Loop thru Albums Folder > # > myAlbumList = getFolderList(theBaseMusicLibraryFolder + myArtistFolder) > for myAlbum in myAlbumList: > print('Album: ' + myAlbum) > > # > # Loop thru Tracks (Files) Folder > # > myAlbumPath = theBaseMusicLibraryFolder + myArtistFolder + '/' + myAlbum + '/' > myFilesList = getFileList(myAlbumPath) > for myFile in myFilesList: > myFilePath = myAlbumPath + myFile > myID3 = eyed3.load(myFilePath) > if myID3 is None: > continue > > myArtistName = myID3.tag.artist > if myArtistName is None: > continue > > myAlbumName = myID3.tag.album > if myAlbumName is None: > continue > > myTitleName = myID3.tag.title > if myTitleName is None: > continue > > myCompareFileName = myFile[0:-4] > if myCompareFileName[0].isdigit() and myCompareFileName[1].isdigit(): > myCompareFileName = myFile[3:-4] > > if myCompareFileName != myTitleName: > myLength1 = len(myCompareFileName) > myLength2 = len(myTitleName) > print('File Name Mismatch - Artist: [' + myArtistName + '] Album: ['+ myAlbumName + '] Track: [' + myTitleName + '] File: [' + myCompareFileName + ']') > if (myLength1 == myLength2): > print('lengths match: ',myLength1) > else: > print('lengths mismatch: ',myLength1,' ',myLength2) > > print(' ') > > > > > return myArtistsFoldlerList > "myArtistsFoldlerList"? And so many variables starting with "my". Not wrong; just ... :-) > > > > > >> On 8 Jun 2022, at 00:07, MRAB wrote: >> >> On 2022-06-07 21:23, Dave wrote: >>> Thanks a lot for this! isDigit was the method I was looking for and couldn?t find. >>> I have another problem related to this, the following code uses the code you just sent. I am getting a files ID3 tags using eyed3, this part seems to work and I get expected values in this case myTitleName (Track name) is set to ?Deadlock Holiday? and myCompareFileName is set to ?01 Deadlock Holiday? (File Name with the Track number prepended). The is digit test works and myCompareFileName is set to ?Deadlock Holiday?, so they should match, right? >> OT, but are you sure about that name? Isn't it "Dreadlock Holiday" (by 10cc)? >> >> [snip] > From avigross at verizon.net Tue Jun 7 21:53:26 2022 From: avigross at verizon.net (Avi Gross) Date: Wed, 8 Jun 2022 01:53:26 +0000 (UTC) Subject: How to test characters of a string In-Reply-To: References: Message-ID: <1900098914.424953.1654653206710@mail.yahoo.com> Amazing how some people bring out the heavy artillery, first!?LOL! If the question was how to remove any?initial?digits and perhaps?whitespace?in a?string, it is fairly easy to do without any functions to test if there are digits before?the title. I mean look at initial characters and move forward if it is between '0' and '9'?or a space.?Duh! Sure, a regular expression that matches anything following a run of digits and?whitespace?and before a ".MPG" or the end of the entry will be easy to extract and compare after removing any?left/right?whitespace?in both things being compared and coercing both to the same case. But the solution may be doomed to failure when it sees things like: "100 Letters"? "1+1"? "10,000 hours" "1 Trillion Dollar$"? "2,000 Light Years From Home" So is it necessary to insist on an exact pattern of two digits followed by a space?? That would fail on?"44 Minutes",?"40 Oz. Dream",?"50 Mission Cap",?"50 Ways to Say Goodbye",?"99 Ways to Die"? It looks to me like you need to compare TWICE just in case. If it matches in?the original (perhaps with some normalization of case and?whitespace, fine. If not?will they match if one or both have something to remove as a prefix such as "02 ".?And if you are comparing items where the same song is in two different numeric sequences?on different disks, ... -----Original Message----- From: Christian Gollwitzer To: python-list at python.org Sent: Tue, Jun 7, 2022 6:01 pm Subject: Re: How to test characters of a string Am 07.06.22 um 21:56 schrieb Dave: > It depends on the language I?m using, in Objective C, I?d use isNumeric, just wanted to know what the equivalent is in Python. > Your problem is also a typical case for regular expressions. You can create an expression for "starts with any number of digits plus optional whitespace" and then replace this with nothing: > chris at linux-tb9f:~> ipython > Python 3.6.15 (default, Sep 23 2021, 15:41:43) [GCC] > Type 'copyright', 'credits' or 'license' for more information > IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help. > > In [1]: import re? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? > > In [2]: s='05 Trinket'? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? > > In [3]: re.sub(r'^\d+\s*', '', s)? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? > Out[3]: 'Trinket' > If it doesn't match, it will do nothing: > In [4]: s='Es geht los'? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? > > In [5]: re.sub(r'^\d+\s*', '', s)? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? > Out[5]: 'Es geht los' Some people on this list don't like regexes but for tasks like this they are made and working well. ^ is "starts with" \d is any digit \s is any space + is at least one * is nothing or one of Christian -- https://mail.python.org/mailman/listinfo/python-list From dave at looktowindward.com Wed Jun 8 04:08:19 2022 From: dave at looktowindward.com (Dave) Date: Wed, 8 Jun 2022 10:08:19 +0200 Subject: How to replace characters in a string? Message-ID: Hi All, I decided to start a new thread as this really is a new subject. I've got two that appear to be identical, but fail to compare. After getting the ascii encoding I see that they are indeed different, my question is how can I replace the \u2019m with a regular single quote mark (or apostrophe)? myCompareFile1 = ascii(myTitleName) myCompareFile2 = ascii(myCompareFileName) myCompareFile1: 'I\u2019m Mandy Fly Me' myCompareFile2: "I'm Mandy Fly Me" I tried the but it doesn?t seem to work? myCompareFile1 = ascii(myTitleName) myCompareFile1.replace("\u2019", "'") myCompareFile2 = ascii(myCompareFileName) myCompareFile2.replace("\u2019", "'") if myCompareFile1 != myCompareFile2: print('myCompareFile1:',myCompareFile1) print('myCompareFile2:',myCompareFile2) myLength1 = len(myCompareFileName) myLength2 = len(myTitleName) print('File Name Mismatch - Artist: [' + myArtistName + '] Album: ['+ myAlbumName + '] Track: [' + myTitleName + '] File: [' + myCompareFileName + ']') if (myLength1 == myLength2): print('lengths match: ',myLength1) else: print('lengths mismatch: ',myLength1,' ',myLength2) print(' ') Console: myCompareFile1: 'I\u2019m Mandy Fly Me' myCompareFile2: "I'm Mandy Fly Me" So it looks like the replace isn?t doing anything? I?m an experienced developer but learning Python. All the Best Dave From rosuav at gmail.com Wed Jun 8 04:14:46 2022 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 8 Jun 2022 18:14:46 +1000 Subject: How to replace characters in a string? In-Reply-To: References: Message-ID: On Wed, 8 Jun 2022 at 18:12, Dave wrote: > I tried the but it doesn?t seem to work? > myCompareFile1 = ascii(myTitleName) > myCompareFile1.replace("\u2019", "'") Strings in Python are immutable. When you call ascii(), you get back a new string, but it's one that has actual backslashes and such in it. (You probably don't need this step, other than for debugging; check the string by printing out the ASCII version of it, but stick to the original for actual processing.) The same is true of the replace() method; it doesn't change the string, it returns a new string. >>> word = "spam" >>> print(word.replace("sp", "h")) ham >>> print(word) spam ChrisA From dave at looktowindward.com Wed Jun 8 04:16:11 2022 From: dave at looktowindward.com (Dave) Date: Wed, 8 Jun 2022 10:16:11 +0200 Subject: How to replace characters in a string? In-Reply-To: References: Message-ID: <620B41C4-5657-494E-9345-2DBDAF53AD46@looktowindward.com> PS I?ve also tried: myCompareFile1 = myTitleName myCompareFile1.replace("\u2019", "'") myCompareFile2 = myCompareFileName myCompareFile2.replace("\u2019", "'") Which also doesn?t work, the replace itself work but it still fails the compare? > On 8 Jun 2022, at 10:08, Dave wrote: > > Hi All, > > I decided to start a new thread as this really is a new subject. > > I've got two that appear to be identical, but fail to compare. After getting the ascii encoding I see that they are indeed different, my question is how can I replace the \u2019m with a regular single quote mark (or apostrophe)? > > myCompareFile1 = ascii(myTitleName) > myCompareFile2 = ascii(myCompareFileName) > myCompareFile1: 'I\u2019m Mandy Fly Me' > myCompareFile2: "I'm Mandy Fly Me" > > I tried the but it doesn?t seem to work? > myCompareFile1 = ascii(myTitleName) > myCompareFile1.replace("\u2019", "'") > myCompareFile2 = ascii(myCompareFileName) > myCompareFile2.replace("\u2019", "'") > if myCompareFile1 != myCompareFile2: > print('myCompareFile1:',myCompareFile1) > print('myCompareFile2:',myCompareFile2) > myLength1 = len(myCompareFileName) > myLength2 = len(myTitleName) > print('File Name Mismatch - Artist: [' + myArtistName + '] Album: ['+ myAlbumName + '] Track: [' + myTitleName + '] File: [' + myCompareFileName + ']') > if (myLength1 == myLength2): > print('lengths match: ',myLength1) > else: > print('lengths mismatch: ',myLength1,' ',myLength2) > print(' ') > Console: > > myCompareFile1: 'I\u2019m Mandy Fly Me' > myCompareFile2: "I'm Mandy Fly Me" > > So it looks like the replace isn?t doing anything? > > I?m an experienced developer but learning Python. > > All the Best > Dave > > > > > > -- > https://mail.python.org/mailman/listinfo/python-list From rosuav at gmail.com Wed Jun 8 04:22:33 2022 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 8 Jun 2022 18:22:33 +1000 Subject: How to replace characters in a string? In-Reply-To: <620B41C4-5657-494E-9345-2DBDAF53AD46@looktowindward.com> References: <620B41C4-5657-494E-9345-2DBDAF53AD46@looktowindward.com> Message-ID: On Wed, 8 Jun 2022 at 18:20, Dave wrote: > > PS > > I?ve also tried: > myCompareFile1 = myTitleName > myCompareFile1.replace("\u2019", "'") > myCompareFile2 = myCompareFileName > myCompareFile2.replace("\u2019", "'") > Which also doesn?t work, the replace itself work but it still fails the compare? > This is a great time to start exploring what actually happens when you do "myCompareFile2 = myCompareFileName". I recommend doing some poking around with strings (which are immutable), lists (which aren't), and tuples (which aren't, but can contain mutable children). ChrisA From dave at looktowindward.com Wed Jun 8 05:09:05 2022 From: dave at looktowindward.com (Dave) Date: Wed, 8 Jun 2022 11:09:05 +0200 Subject: How to replace characters in a string? In-Reply-To: References: Message-ID: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> Hi, Thanks for this! So, is there a copy function/method that returns a MutableString like in objective-C? I?ve solved this problems before in a number of languages like Objective-C and AppleScript. Basically there is a set of common characters that need ?normalizing? and I have a method that replaces them in a string, so: myString = [myString normalizeCharacters]; Would return a new string with all the ?common? replacements applied. Since the following gives an error : myString = 'Hello' myNewstring = myString.replace(myString,'e','a?) TypeError: 'str' object cannot be interpreted as an integer I can?t see of a way to do this in Python? All the Best Dave > On 8 Jun 2022, at 10:14, Chris Angelico wrote: > > On Wed, 8 Jun 2022 at 18:12, Dave wrote: > >> I tried the but it doesn?t seem to work? >> myCompareFile1 = ascii(myTitleName) >> myCompareFile1.replace("\u2019", "'") > > Strings in Python are immutable. When you call ascii(), you get back a > new string, but it's one that has actual backslashes and such in it. > (You probably don't need this step, other than for debugging; check > the string by printing out the ASCII version of it, but stick to the > original for actual processing.) The same is true of the replace() > method; it doesn't change the string, it returns a new string. > >>>> word = "spam" >>>> print(word.replace("sp", "h")) > ham >>>> print(word) > spam > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list From rosuav at gmail.com Wed Jun 8 05:17:28 2022 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 8 Jun 2022 19:17:28 +1000 Subject: How to replace characters in a string? In-Reply-To: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> References: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> Message-ID: On Wed, 8 Jun 2022 at 19:13, Dave wrote: > > Hi, > > Thanks for this! > > So, is there a copy function/method that returns a MutableString like in objective-C? I?ve solved this problems before in a number of languages like Objective-C and AppleScript. > > Basically there is a set of common characters that need ?normalizing? and I have a method that replaces them in a string, so: > > myString = [myString normalizeCharacters]; > > Would return a new string with all the ?common? replacements applied. > > Since the following gives an error : > > myString = 'Hello' > myNewstring = myString.replace(myString,'e','a?) > > TypeError: 'str' object cannot be interpreted as an integer > > I can?t see of a way to do this in Python? > Not sure why you're passing the string as an argument as well as using it as the object you're calling a method on. All you should need to do is: myString.replace('e', 'a') ChrisA From Karsten.Hilbert at gmx.net Wed Jun 8 05:18:08 2022 From: Karsten.Hilbert at gmx.net (Karsten Hilbert) Date: Wed, 8 Jun 2022 11:18:08 +0200 Subject: How to replace characters in a string? In-Reply-To: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> References: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> Message-ID: Am Wed, Jun 08, 2022 at 11:09:05AM +0200 schrieb Dave: > myString = 'Hello' > myNewstring = myString.replace(myString,'e','a?) That won't work (last quote) but apart from that: myNewstring = myString.replace('e', 'a') Karsten -- GPG 40BE 5B0E C98E 1713 AFA6 5BC0 3BEA AC80 7D4F C89B From joel.goldstick at gmail.com Wed Jun 8 05:26:09 2022 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 8 Jun 2022 05:26:09 -0400 Subject: How to replace characters in a string? In-Reply-To: References: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> Message-ID: On Wed, Jun 8, 2022 at 5:22 AM Karsten Hilbert wrote: > > Am Wed, Jun 08, 2022 at 11:09:05AM +0200 schrieb Dave: > > > myString = 'Hello' > > myNewstring = myString.replace(myString,'e','a?) > > That won't work (last quote) but apart from that: > > myNewstring = myString.replace('e', 'a') > > Karsten > -- > GPG 40BE 5B0E C98E 1713 AFA6 5BC0 3BEA AC80 7D4F C89B > -- > https://mail.python.org/mailman/listinfo/python-list Sorry if I'm not reading the nuances correctly, but it looks to me that you failed to realize that string methods return results. They don't change the string in place: Python 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> str1 = "\u2019string with starting smart quote" >>> str1 '?string with starting smart quote' >>> new_str = str1.replace("\u2019","'") >>> str1 '?string with starting smart quote' >>> new_str "'string with starting smart quote" >>> repr(str1) "'?string with starting smart quote'" >>> repr(new_str) '"\'string with starting smart quote"' >>> As you can see, str1 doesn't change, but when you 'replace' on it, the result you want is returned to new_str -- Joel Goldstick From dave at looktowindward.com Wed Jun 8 05:25:38 2022 From: dave at looktowindward.com (Dave) Date: Wed, 8 Jun 2022 11:25:38 +0200 Subject: How to replace characters in a string? In-Reply-To: References: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> Message-ID: <3FB6620E-D54C-40F6-8223-7D3E17DB55ED@looktowindward.com> Hi, I misunderstood how it worked, basically I?ve added this function: def filterCommonCharacters(theString): myNewString = theString.replace("\u2019", "'") return myNewString Which returns a new string replacing the common characters. This can easily be extended to include other characters as and when they come up by adding a line as so: myNewString = theString.replace("\u2014", ?]? #just an example Which is what I was trying to achieve. All the Best Dave > On 8 Jun 2022, at 11:17, Chris Angelico wrote: > > On Wed, 8 Jun 2022 at 19:13, Dave wrote: >> >> Hi, >> >> Thanks for this! >> >> So, is there a copy function/method that returns a MutableString like in objective-C? I?ve solved this problems before in a number of languages like Objective-C and AppleScript. >> >> Basically there is a set of common characters that need ?normalizing? and I have a method that replaces them in a string, so: >> >> myString = [myString normalizeCharacters]; >> >> Would return a new string with all the ?common? replacements applied. >> >> Since the following gives an error : >> >> myString = 'Hello' >> myNewstring = myString.replace(myString,'e','a?) >> >> TypeError: 'str' object cannot be interpreted as an integer >> >> I can?t see of a way to do this in Python? >> > > Not sure why you're passing the string as an argument as well as using > it as the object you're calling a method on. All you should need to do > is: > > myString.replace('e', 'a') > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list From roel at roelschroeven.net Wed Jun 8 07:37:46 2022 From: roel at roelschroeven.net (Roel Schroeven) Date: Wed, 8 Jun 2022 13:37:46 +0200 Subject: How to replace characters in a string? In-Reply-To: <3FB6620E-D54C-40F6-8223-7D3E17DB55ED@looktowindward.com> References: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> <3FB6620E-D54C-40F6-8223-7D3E17DB55ED@looktowindward.com> Message-ID: Op 8/06/2022 om 11:25 schreef Dave: > Hi, > > I misunderstood how it worked, basically I?ve added this function: > > def filterCommonCharacters(theString): > > myNewString = theString.replace("\u2019", "'") > > return myNewString > Which returns a new string replacing the common characters. > > This can easily be extended to include other characters as and when they come up by adding a line as so: > > myNewString = theString.replace("\u2014", ?]? #just an example > > Which is what I was trying to achieve. When you have multiple replacements to do, there's an alternative for multiple replace calls: you can use theString.translate() with a translation map (which you can make yourself or make with str.maketrans()) to do all the replacements at once. Example ??? # Make a map that translates every character from the first string to the ??? # corresponding character in the second string ??? translation_map = str.maketrans("\u2019\u2014", "']") ??? # All the replacements in one go ??? myNewString = theString.translate(translation_map) See: ??? - https://docs.python.org/3.10/library/stdtypes.html#str.maketrans ??? - https://docs.python.org/3.10/library/stdtypes.html#str.translate -- "There is a theory which states that if ever anyone discovers exactly what the Universe is for and why it is here, it will instantly disappear and be replaced by something even more bizarre and inexplicable. There is another theory which states that this has already happened." -- Douglas Adams, The Restaurant at the End of the Universe From drsalists at gmail.com Wed Jun 8 09:45:01 2022 From: drsalists at gmail.com (Dan Stromberg) Date: Wed, 8 Jun 2022 06:45:01 -0700 Subject: How to replace characters in a string? In-Reply-To: References: Message-ID: On Wed, Jun 8, 2022 at 1:11 AM Dave wrote: > I've got two that appear to be identical, but fail to compare. After > getting the ascii encoding I see that they are indeed different, my > question is how can I replace the \u2019m with a regular single quote mark > (or apostrophe)? > Perhaps try https://pypi.org/project/Unidecode/ ? From ongekruisigde at news.eternal-september.org Wed Jun 8 04:07:40 2022 From: ongekruisigde at news.eternal-september.org (De ongekruisigde) Date: Wed, 8 Jun 2022 08:07:40 -0000 (UTC) Subject: How to test characters of a string References: Message-ID: On 2022-06-08, dn wrote: > On 08/06/2022 10.18, De ongekruisigde wrote: >> On 2022-06-08, Christian Gollwitzer wrote: >>> Am 07.06.22 um 21:56 schrieb Dave: >>>> It depends on the language I?m using, in Objective C, I?d use isNumeric, just wanted to know what the equivalent is in Python. >>>> >>> >>> Your problem is also a typical case for regular expressions. You can >>> create an expression for "starts with any number of digits plus optional >>> whitespace" and then replace this with nothing: >> >> Regular expressions are overkill for this and much slower than the >> simple isdigit based solution. > > ... > >> Regular expressions are indeeed extremely powerful and useful but I tend >> to avoid them when there's a (faster) normal solution. > > Yes, simple solutions are (likely) easier to read. Depending on the problem a regular expression may be the much simpler solution. I love them for e.g. text parsing and use them all the time. Unrivaled when e.g. parts of text have to be extracted, e.g. from lines like these: root:x:0:0:System administrator:/root:/run/current-system/sw/bin/bash dhcpcd:x:995:991::/var/empty:/run/current-system/sw/bin/nologin nm-iodine:x:996:57::/var/empty:/run/current-system/sw/bin/nologin avahi:x:997:996:avahi-daemon privilege separation user:/var/empty:/run/current-system/sw/bin/nologin sshd:x:998:993:SSH privilege separation user:/var/empty:/run/current-system/sw/bin/nologin geoclue:x:999:998:Geoinformation service:/var/lib/geoclue:/run/current-system/sw/bin/nologin Compare a regexp solution like this: >>> g = re.search(r'([^:]*):([^:]*):(\d+):(\d+):([^:]*):([^:]*):(.*)$' , s) >>> print(g.groups()) ('geoclue', 'x', '999', '998', 'Geoinformation service', '/var/lib/geoclue', '/run/current-system/sw/bin/nologin') to the code one would require to process it manually, with all the edge cases. The regexp surely reads much simpler (?). > RegEx-s are more powerful (and well worth learning for this reason), but > are only 'readable' to those who use them frequently. > > Has either of you performed a timeit comparison? No need: the isdigit solution doesn't require the overhead of a regex processor. -- You're rewriting parts of Quake in *Python*? MUAHAHAHA From ongekruisigde at news.eternal-september.org Wed Jun 8 04:09:43 2022 From: ongekruisigde at news.eternal-september.org (De ongekruisigde) Date: Wed, 8 Jun 2022 08:09:43 -0000 (UTC) Subject: How to test characters of a string References: <7AC4222A-CEEB-43BB-81B9-AE03F7E22F88@looktowindward.com> Message-ID: On 2022-06-08, Dave wrote: > I hate regEx and avoid it whenever possible, I?ve never found something that was impossible to do without it. I love regular expressions and use them where appropriate. Saves tons of code and is often much more readable than the pages of code required to do the same. -- You're rewriting parts of Quake in *Python*? MUAHAHAHA From ongekruisigde at news.eternal-september.org Wed Jun 8 04:23:58 2022 From: ongekruisigde at news.eternal-september.org (De ongekruisigde) Date: Wed, 8 Jun 2022 08:23:58 -0000 (UTC) Subject: How to replace characters in a string? References: Message-ID: On 2022-06-08, Dave wrote: > Hi All, > > I decided to start a new thread as this really is a new subject. > > I've got two that appear to be identical, but fail to compare. After getting the ascii encoding I see that they are indeed different, my question is how can I replace the \u2019m with a regular single quote mark (or apostrophe)? You're not facing this alone: https://changelog.complete.org/archives/9938-the-python-unicode-mess Perhaps useful insights can be found at: https://realpython.com/python-encodings-guide/ > +++ -- You're rewriting parts of Quake in *Python*? MUAHAHAHA From ongekruisigde at news.eternal-september.org Wed Jun 8 05:06:22 2022 From: ongekruisigde at news.eternal-september.org (De ongekruisigde) Date: Wed, 8 Jun 2022 09:06:22 -0000 (UTC) Subject: How to test characters of a string References: Message-ID: On 2022-06-08, Christian Gollwitzer wrote: > Am 07.06.22 um 23:01 schrieb Christian Gollwitzer: > >>> In [3]: re.sub(r'^\d+\s*', '', s) Out[3]: 'Trinket' >>> > > that RE does match what you intended to do, but not exactly what you > wrote in the OP. that would be '^\d\d.' start with exactly two digits > followed by any character. Indeed but then I'd like '\d{2}' even better. > Christian -- You're rewriting parts of Quake in *Python*? MUAHAHAHA From dave at looktowindward.com Wed Jun 8 05:54:07 2022 From: dave at looktowindward.com (Dave) Date: Wed, 8 Jun 2022 11:54:07 +0200 Subject: How to replace characters in a string? In-Reply-To: <3FB6620E-D54C-40F6-8223-7D3E17DB55ED@looktowindward.com> References: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> <3FB6620E-D54C-40F6-8223-7D3E17DB55ED@looktowindward.com> Message-ID: > On 8 Jun 2022, at 11:25, Dave wrote: > > myNewString = theString.replace("\u2014", ?]? #just an example Opps! Make that myNewString = myNewString.replace("\u2014", ?]? #just an example From jon+usenet at unequivocal.eu Wed Jun 8 06:26:59 2022 From: jon+usenet at unequivocal.eu (Jon Ribbens) Date: Wed, 8 Jun 2022 10:26:59 -0000 (UTC) Subject: How to replace characters in a string? References: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> <3FB6620E-D54C-40F6-8223-7D3E17DB55ED@looktowindward.com> Message-ID: On 2022-06-08, Dave wrote: > I misunderstood how it worked, basically I?ve added this function: > > def filterCommonCharacters(theString): > myNewString = theString.replace("\u2019", "'") > return myNewString > Which returns a new string replacing the common characters. > > This can easily be extended to include other characters as and when > they come up by adding a line as so: > > myNewString = theString.replace("\u2014", ?]? #just an example > > Which is what I was trying to achieve. Here's a head-start on some characters you might want to translate, mostly spaces, hyphens, quotation marks, and ligatures: def unicode_translate(s): return s.translate({ 8192: ' ', 8193: ' ', 8194: ' ', 8195: ' ', 8196: ' ', 8197: ' ', 198: 'AE', 8199: ' ', 8200: ' ', 8201: ' ', 8202: ' ', 8203: '', 64258: 'fl', 8208: '-', 8209: '-', 8210: '-', 8211: '-', 8212: '-', 8722: '-', 8216: "'", 8217: "'", 8220: '"', 8221: '"', 64256: 'ff', 160: ' ', 64260: 'ffl', 8198: ' ', 230: 'ae', 12288: ' ', 173: '', 497: 'DZ', 498: 'Dz', 499: 'dz', 64259: 'ffi', 8230: '...', 64257: 'fi', 64262: 'st'}) If you want to go further then the Unidecode package might be helpful: https://pypi.org/project/Unidecode/ From avigross at verizon.net Wed Jun 8 12:23:16 2022 From: avigross at verizon.net (Avi Gross) Date: Wed, 8 Jun 2022 16:23:16 +0000 (UTC) Subject: How to replace characters in a string? In-Reply-To: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> References: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> Message-ID: <1707808815.586773.1654705396591@mail.yahoo.com> Dave, Your goal is to compare titles and there can be endless replacements needed if you allow?the text to contain anything but ASCII. Have you considered stripping out things instead? I mean remove lots of stuff that is?not ASCII in the first place and perhaps also remove lots of extra punctuation likesingle quotes or question marks or redundant white space and compare the?sort of skeletons of the two?? And even if that fails, could you have a measure of how different they are and tolerate?if they were say off by one letter albeit "My desert" matching "My Dessert" might?not be a valid match with one being a song about an arid environment and the other?about food you don't need! Your seemingly simple need can expand into a fairly complex project. There may be?many ideas on how to deal with it but not anything perfect enough to catch all?cases as even a trained human may have to make decisions at times and?not match what other humans do. We have examples like the TV show "NUMB3RS"?that used a perfectly valid digit 3 to stand for an "E" but yet is often written when I?look it up as NUMBERS. You have obvious cases where titles of songs may contain?composite symbols like "?" which will not compare to one where it is written out as "oe"?so the idea of comparing is quite complex and the best you might do is heuristic. UNICODE has many symbols that are almost the same or even look the same or maybe?in one font versus another. There are libraries of functions that allow some kinds?of comparisons or conversions that you could look into but the gain for you may?not be worth it. Nothing stops a person from naming a song any way they want?and I speak many languages and often see a song re-titled in the local language?and using the local alphabet mixed often with another. Your original question is perhaps now many questions, depending on what you choose.?You started by wanting to know how to compare and it is moving on to how to delete parts?or make substitutions or use regular expressions and it can get worse. You can, for example,?take a string and identify the words within it and create a regular expression that inserts?sequences between the words that match any zero or one or more non-word characters such?as spaces, tabs, punctuation or non-ASCII, so that song titles with the same words in a?sequence match no matter what is between them. The possibilities are endless but?consider some of the techniques that are used by some programs that parse text and suggest?alternate spellings? or even programs like Google Translate that can take a sentence and then?suggest you may mean a slightly altered sentence with one word changed to fit better.? You need to decide what you want to deal with and what will be mis-classified by your?program. Some of us have suggested folding the case of the words but that means asong about a dark skinned person in Poland called "Black Polish" would match a song?about keeping your shoes dark with "black polish" so I keep repeating it is very hard?or frankly impossible, to catch every case I can imagine and the many I can't! But the emphasis here is not your overall problem. It is about whether and how?the computer language called python, and perhaps some add-on modules, can be?used to solve each smaller need such as recognizing a pattern or replacing text. It can?do quite a bit but only when the specification of the problem is exact.? -----Original Message----- From: Dave To: python-list at python.org Sent: Wed, Jun 8, 2022 5:09 am Subject: Re: How to replace characters in a string? Hi, Thanks for this! So, is there a copy function/method that returns a MutableString like in objective-C? I?ve solved this problems before in a number of languages like Objective-C and AppleScript. Basically there is a set of common characters that need ?normalizing? and I have a method that replaces them in a string, so: myString = [myString normalizeCharacters]; Would return a new string with all the ?common? replacements applied. Since the following gives an error : myString = 'Hello' myNewstring = myString.replace(myString,'e','a?) TypeError: 'str' object cannot be interpreted as an integer I can?t see of a way to do this in Python? All the Best Dave > On 8 Jun 2022, at 10:14, Chris Angelico wrote: > > On Wed, 8 Jun 2022 at 18:12, Dave wrote: > >> I tried the but it doesn?t seem to work? >> myCompareFile1 = ascii(myTitleName) >> myCompareFile1.replace("\u2019", "'") > > Strings in Python are immutable. When you call ascii(), you get back a > new string, but it's one that has actual backslashes and such in it. > (You probably don't need this step, other than for debugging; check > the string by printing out the ASCII version of it, but stick to the > original for actual processing.) The same is true of the replace() > method; it doesn't change the string, it returns a new string. > >>>> word = "spam" >>>> print(word.replace("sp", "h")) > ham >>>> print(word) > spam > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list From dave at looktowindward.com Wed Jun 8 13:01:28 2022 From: dave at looktowindward.com (Dave) Date: Wed, 8 Jun 2022 19:01:28 +0200 Subject: How to replace characters in a string? In-Reply-To: <1707808815.586773.1654705396591@mail.yahoo.com> References: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> <1707808815.586773.1654705396591@mail.yahoo.com> Message-ID: <4E7A5722-AB38-49AD-83AE-A838DFD673CA@looktowindward.com> Hi, This is a tool I?m using on my own files to save me time. Basically or most of the tracks were imported with different version iTunes over the years. There are two problems: 1. File System characters are replaced (you can?t have ?/? or ?:? in a file name). 2. Smart Quotes were added at some point, these need to replaced. 3. Other character based of name being of a non-english origin. If find others I?ll add them. I?m using MusicBrainz to do a fuzzy match and get the correct name. it?s not perfect, but works for 99% of files which is good enough for me! Cheers Dave > On 8 Jun 2022, at 18:23, Avi Gross via Python-list wrote: > > Dave, > > Your goal is to compare titles and there can be endless replacements needed if you allow the text to contain anything but ASCII. > > Have you considered stripping out things instead? I mean remove lots of stuff that is not ASCII in the first place and perhaps also remove lots of extra punctuation likesingle quotes or question marks or redundant white space and compare the sort of skeletons of the two? > > And even if that fails, could you have a measure of how different they are and tolerate if they were say off by one letter albeit "My desert" matching "My Dessert" might not be a valid match with one being a song about an arid environment and the other about food you don't need! > > Your seemingly simple need can expand into a fairly complex project. There may be many ideas on how to deal with it but not anything perfect enough to catch all cases as even a trained human may have to make decisions at times and not match what other humans do. We have examples like the TV show "NUMB3RS" that used a perfectly valid digit 3 to stand for an "E" but yet is often written when I look it up as NUMBERS. You have obvious cases where titles of songs may contain composite symbols like "?" which will not compare to one where it is written out as "oe" so the idea of comparing is quite complex and the best you might do is heuristic. > > UNICODE has many symbols that are almost the same or even look the same or maybe in one font versus another. There are libraries of functions that allow some kinds of comparisons or conversions that you could look into but the gain for you may not be worth it. Nothing stops a person from naming a song any way they want and I speak many languages and often see a song re-titled in the local language and using the local alphabet mixed often with another. > > Your original question is perhaps now many questions, depending on what you choose. You started by wanting to know how to compare and it is moving on to how to delete parts or make substitutions or use regular expressions and it can get worse. You can, for example, take a string and identify the words within it and create a regular expression that inserts sequences between the words that match any zero or one or more non-word characters such as spaces, tabs, punctuation or non-ASCII, so that song titles with the same words in a sequence match no matter what is between them. The possibilities are endless but consider some of the techniques that are used by some programs that parse text and suggest alternate spellings or even programs like Google Translate that can take a sentence and then suggest you may mean a slightly altered sentence with one word changed to fit better. > > You need to decide what you want to deal with and what will be mis-classified by your program. Some of us have suggested folding the case of the words but that means asong about a dark skinned person in Poland called "Black Polish" would match a song about keeping your shoes dark with "black polish" so I keep repeating it is very hard or frankly impossible, to catch every case I can imagine and the many I can't! > > But the emphasis here is not your overall problem. It is about whether and how the computer language called python, and perhaps some add-on modules, can be used to solve each smaller need such as recognizing a pattern or replacing text. It can do quite a bit but only when the specification of the problem is exact. > > > > > -----Original Message----- > From: Dave > To: python-list at python.org > Sent: Wed, Jun 8, 2022 5:09 am > Subject: Re: How to replace characters in a string? > > Hi, > > Thanks for this! > > So, is there a copy function/method that returns a MutableString like in objective-C? I?ve solved this problems before in a number of languages like Objective-C and AppleScript. > > Basically there is a set of common characters that need ?normalizing? and I have a method that replaces them in a string, so: > > myString = [myString normalizeCharacters]; > > Would return a new string with all the ?common? replacements applied. > > Since the following gives an error : > > myString = 'Hello' > myNewstring = myString.replace(myString,'e','a?) > > TypeError: 'str' object cannot be interpreted as an integer > > I can?t see of a way to do this in Python? > > All the Best > Dave > > >> On 8 Jun 2022, at 10:14, Chris Angelico wrote: >> >> On Wed, 8 Jun 2022 at 18:12, Dave wrote: >> >>> I tried the but it doesn?t seem to work? >>> myCompareFile1 = ascii(myTitleName) >>> myCompareFile1.replace("\u2019", "'") >> >> Strings in Python are immutable. When you call ascii(), you get back a >> new string, but it's one that has actual backslashes and such in it. >> (You probably don't need this step, other than for debugging; check >> the string by printing out the ASCII version of it, but stick to the >> original for actual processing.) The same is true of the replace() >> method; it doesn't change the string, it returns a new string. >> >>>>> word = "spam" >>>>> print(word.replace("sp", "h")) >> ham >>>>> print(word) >> spam >> >> ChrisA >> -- >> https://mail.python.org/mailman/listinfo/python-list > > -- > https://mail.python.org/mailman/listinfo/python-list > -- > https://mail.python.org/mailman/listinfo/python-list From barry at barrys-emacs.org Wed Jun 8 13:09:25 2022 From: barry at barrys-emacs.org (Barry Scott) Date: Wed, 8 Jun 2022 18:09:25 +0100 Subject: How to test characters of a string In-Reply-To: <00D0FBD1-77E5-4804-8154-F5D31914564F@looktowindward.com> References: <05496acc-02ec-a789-8df7-80c69b4390c5@mrabarnett.plus.com> <00D0FBD1-77E5-4804-8154-F5D31914564F@looktowindward.com> Message-ID: <5C6060DA-40B1-44C7-A345-80CB7E6E4A17@barrys-emacs.org> > On 7 Jun 2022, at 23:24, Dave wrote: > > Yes, it was probably just a typeo on my part. > > I?ve now fixed the majority of cases but still got two strings that look identical but fail to match, this time (again by 10cc), ?I?m Mandy Fly Me?. > > I?m putting money on it being a utf8 problem but I?m stuck on how to handle it. It?s probably the single quote in I?m, although it has worked with other songs. > > Any ideas? You can use difflib to give you a diff of the two strings: :>>> print('\n'.join(difflib.unified_diff('abc', 'adc'))) --- +++ @@ -1,3 +1,3 @@ a -b +d c :>>> The docs talk about lines, but difflib works on sequence. I use it a lot to find differences within lines. Barry > > All the Best > Cheers > Dave > > Here is the whole function/method or whatever it?s called in Python: > > ################################################################################ > # > # checkMusicFiles > # > ################################################################################ > def checkMusicFiles(theBaseMusicLibraryFolder): > myArtistDict = [] > > # > # Loop thru Artists Folder > # > myArtistsFoldlerList = getFolderList(theBaseMusicLibraryFolder) > myArtistCount = 0 > for myArtistFolder in myArtistsFoldlerList: > print('Artist: ' + myArtistFolder) > # > # Loop thru Albums Folder > # > myAlbumList = getFolderList(theBaseMusicLibraryFolder + myArtistFolder) > for myAlbum in myAlbumList: > print('Album: ' + myAlbum) > > # > # Loop thru Tracks (Files) Folder > # > myAlbumPath = theBaseMusicLibraryFolder + myArtistFolder + '/' + myAlbum + '/' > myFilesList = getFileList(myAlbumPath) > for myFile in myFilesList: > myFilePath = myAlbumPath + myFile > myID3 = eyed3.load(myFilePath) > if myID3 is None: > continue > > myArtistName = myID3.tag.artist > if myArtistName is None: > continue > > myAlbumName = myID3.tag.album > if myAlbumName is None: > continue > > myTitleName = myID3.tag.title > if myTitleName is None: > continue > > myCompareFileName = myFile[0:-4] > if myCompareFileName[0].isdigit() and myCompareFileName[1].isdigit(): > myCompareFileName = myFile[3:-4] > > if myCompareFileName != myTitleName: > myLength1 = len(myCompareFileName) > myLength2 = len(myTitleName) > print('File Name Mismatch - Artist: [' + myArtistName + '] Album: ['+ myAlbumName + '] Track: [' + myTitleName + '] File: [' + myCompareFileName + ']') > if (myLength1 == myLength2): > print('lengths match: ',myLength1) > else: > print('lengths mismatch: ',myLength1,' ',myLength2) > > print(' ') > > > > > return myArtistsFoldlerList > > > > > > >> On 8 Jun 2022, at 00:07, MRAB wrote: >> >> On 2022-06-07 21:23, Dave wrote: >>> Thanks a lot for this! isDigit was the method I was looking for and couldn?t find. >>> I have another problem related to this, the following code uses the code you just sent. I am getting a files ID3 tags using eyed3, this part seems to work and I get expected values in this case myTitleName (Track name) is set to ?Deadlock Holiday? and myCompareFileName is set to ?01 Deadlock Holiday? (File Name with the Track number prepended). The is digit test works and myCompareFileName is set to ?Deadlock Holiday?, so they should match, right? >> OT, but are you sure about that name? Isn't it "Dreadlock Holiday" (by 10cc)? >> >> [snip] >> -- >> https://mail.python.org/mailman/listinfo/python-list > > -- > https://mail.python.org/mailman/listinfo/python-list From 2QdxY4RzWzUUiLuE at potatochowder.com Wed Jun 8 13:14:29 2022 From: 2QdxY4RzWzUUiLuE at potatochowder.com (2QdxY4RzWzUUiLuE at potatochowder.com) Date: Wed, 8 Jun 2022 12:14:29 -0500 Subject: How to test characters of a string In-Reply-To: References: Message-ID: On 2022-06-08 at 08:07:40 -0000, De ongekruisigde wrote: > Depending on the problem a regular expression may be the much simpler > solution. I love them for e.g. text parsing and use them all the time. > Unrivaled when e.g. parts of text have to be extracted, e.g. from lines > like these: > > root:x:0:0:System administrator:/root:/run/current-system/sw/bin/bash > dhcpcd:x:995:991::/var/empty:/run/current-system/sw/bin/nologin > nm-iodine:x:996:57::/var/empty:/run/current-system/sw/bin/nologin > avahi:x:997:996:avahi-daemon privilege separation user:/var/empty:/run/current-system/sw/bin/nologin > sshd:x:998:993:SSH privilege separation user:/var/empty:/run/current-system/sw/bin/nologin > geoclue:x:999:998:Geoinformation service:/var/lib/geoclue:/run/current-system/sw/bin/nologin > > Compare a regexp solution like this: > > >>> g = re.search(r'([^:]*):([^:]*):(\d+):(\d+):([^:]*):([^:]*):(.*)$' , s) > >>> print(g.groups()) > ('geoclue', 'x', '999', '998', 'Geoinformation service', '/var/lib/geoclue', '/run/current-system/sw/bin/nologin') > > to the code one would require to process it manually, with all the edge > cases. The regexp surely reads much simpler (?). Uh... >>> import pwd # https://docs.python.org/3/library/pwd.html >>> [x for x in pwd.getpwall() if x[0] == 'geoclue'] [pwd.struct_passwd(pw_name='geoclue', pw_passwd='x', pw_uid=992, pw_gid=992, pw_gecos='Geoinformation service', pw_dir='/var/lib/geoclue', pw_shell='/sbin/nologin')] From rosuav at gmail.com Wed Jun 8 13:18:56 2022 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 9 Jun 2022 03:18:56 +1000 Subject: How to test characters of a string In-Reply-To: References: Message-ID: On Thu, 9 Jun 2022 at 03:15, <2QdxY4RzWzUUiLuE at potatochowder.com> wrote: > > On 2022-06-08 at 08:07:40 -0000, > De ongekruisigde wrote: > > > Depending on the problem a regular expression may be the much simpler > > solution. I love them for e.g. text parsing and use them all the time. > > Unrivaled when e.g. parts of text have to be extracted, e.g. from lines > > like these: > > > > root:x:0:0:System administrator:/root:/run/current-system/sw/bin/bash > > dhcpcd:x:995:991::/var/empty:/run/current-system/sw/bin/nologin > > nm-iodine:x:996:57::/var/empty:/run/current-system/sw/bin/nologin > > avahi:x:997:996:avahi-daemon privilege separation user:/var/empty:/run/current-system/sw/bin/nologin > > sshd:x:998:993:SSH privilege separation user:/var/empty:/run/current-system/sw/bin/nologin > > geoclue:x:999:998:Geoinformation service:/var/lib/geoclue:/run/current-system/sw/bin/nologin > > > > Compare a regexp solution like this: > > > > >>> g = re.search(r'([^:]*):([^:]*):(\d+):(\d+):([^:]*):([^:]*):(.*)$' , s) > > >>> print(g.groups()) > > ('geoclue', 'x', '999', '998', 'Geoinformation service', '/var/lib/geoclue', '/run/current-system/sw/bin/nologin') > > > > to the code one would require to process it manually, with all the edge > > cases. The regexp surely reads much simpler (?). > > Uh... > > >>> import pwd # https://docs.python.org/3/library/pwd.html > >>> [x for x in pwd.getpwall() if x[0] == 'geoclue'] > [pwd.struct_passwd(pw_name='geoclue', pw_passwd='x', pw_uid=992, pw_gid=992, pw_gecos='Geoinformation service', pw_dir='/var/lib/geoclue', pw_shell='/sbin/nologin')] That's great if the lines are specifically coming from your system's own /etc/passwd, but not so much if you're trying to compare passwd files from different systems, where you simply have the files themselves. ChrisA From barry at barrys-emacs.org Wed Jun 8 13:12:41 2022 From: barry at barrys-emacs.org (Barry Scott) Date: Wed, 8 Jun 2022 18:12:41 +0100 Subject: How to replace characters in a string? In-Reply-To: <4E7A5722-AB38-49AD-83AE-A838DFD673CA@looktowindward.com> References: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> <1707808815.586773.1654705396591@mail.yahoo.com> <4E7A5722-AB38-49AD-83AE-A838DFD673CA@looktowindward.com> Message-ID: <33CFD25A-B7DE-4D17-AB2B-BEFE9A1ACF7E@barrys-emacs.org> > On 8 Jun 2022, at 18:01, Dave wrote: > > Hi, > > This is a tool I?m using on my own files to save me time. Basically or most of the tracks were imported with different version iTunes over the years. There are two problems: > > 1. File System characters are replaced (you can?t have ?/? or ?:? in a file name). ok > 2. Smart Quotes were added at some point, these need to replaced. ok > 3. Other character based of name being of a non-english origin. Why is this a problem? Its only if the chars are confusing/will not compare that there is something to fix? All modern OS allow unicode filenames. Barry > > If find others I?ll add them. > > I?m using MusicBrainz to do a fuzzy match and get the correct name. > > it?s not perfect, but works for 99% of files which is good enough for me! > > Cheers > Dave > > >> On 8 Jun 2022, at 18:23, Avi Gross via Python-list wrote: >> >> Dave, >> >> Your goal is to compare titles and there can be endless replacements needed if you allow the text to contain anything but ASCII. >> >> Have you considered stripping out things instead? I mean remove lots of stuff that is not ASCII in the first place and perhaps also remove lots of extra punctuation likesingle quotes or question marks or redundant white space and compare the sort of skeletons of the two? >> >> And even if that fails, could you have a measure of how different they are and tolerate if they were say off by one letter albeit "My desert" matching "My Dessert" might not be a valid match with one being a song about an arid environment and the other about food you don't need! >> >> Your seemingly simple need can expand into a fairly complex project. There may be many ideas on how to deal with it but not anything perfect enough to catch all cases as even a trained human may have to make decisions at times and not match what other humans do. We have examples like the TV show "NUMB3RS" that used a perfectly valid digit 3 to stand for an "E" but yet is often written when I look it up as NUMBERS. You have obvious cases where titles of songs may contain composite symbols like "?" which will not compare to one where it is written out as "oe" so the idea of comparing is quite complex and the best you might do is heuristic. >> >> UNICODE has many symbols that are almost the same or even look the same or maybe in one font versus another. There are libraries of functions that allow some kinds of comparisons or conversions that you could look into but the gain for you may not be worth it. Nothing stops a person from naming a song any way they want and I speak many languages and often see a song re-titled in the local language and using the local alphabet mixed often with another. >> >> Your original question is perhaps now many questions, depending on what you choose. You started by wanting to know how to compare and it is moving on to how to delete parts or make substitutions or use regular expressions and it can get worse. You can, for example, take a string and identify the words within it and create a regular expression that inserts sequences between the words that match any zero or one or more non-word characters such as spaces, tabs, punctuation or non-ASCII, so that song titles with the same words in a sequence match no matter what is between them. The possibilities are endless but consider some of the techniques that are used by some programs that parse text and suggest alternate spellings or even programs like Google Translate that can take a sentence and then suggest you may mean a slightly altered sentence with one word changed to fit better. >> >> You need to decide what you want to deal with and what will be mis-classified by your program. Some of us have suggested folding the case of the words but that means asong about a dark skinned person in Poland called "Black Polish" would match a song about keeping your shoes dark with "black polish" so I keep repeating it is very hard or frankly impossible, to catch every case I can imagine and the many I can't! >> >> But the emphasis here is not your overall problem. It is about whether and how the computer language called python, and perhaps some add-on modules, can be used to solve each smaller need such as recognizing a pattern or replacing text. It can do quite a bit but only when the specification of the problem is exact. >> >> >> >> >> -----Original Message----- >> From: Dave >> To: python-list at python.org >> Sent: Wed, Jun 8, 2022 5:09 am >> Subject: Re: How to replace characters in a string? >> >> Hi, >> >> Thanks for this! >> >> So, is there a copy function/method that returns a MutableString like in objective-C? I?ve solved this problems before in a number of languages like Objective-C and AppleScript. >> >> Basically there is a set of common characters that need ?normalizing? and I have a method that replaces them in a string, so: >> >> myString = [myString normalizeCharacters]; >> >> Would return a new string with all the ?common? replacements applied. >> >> Since the following gives an error : >> >> myString = 'Hello' >> myNewstring = myString.replace(myString,'e','a?) >> >> TypeError: 'str' object cannot be interpreted as an integer >> >> I can?t see of a way to do this in Python? >> >> All the Best >> Dave >> >> >>> On 8 Jun 2022, at 10:14, Chris Angelico wrote: >>> >>> On Wed, 8 Jun 2022 at 18:12, Dave wrote: >>> >>>> I tried the but it doesn?t seem to work? >>>> myCompareFile1 = ascii(myTitleName) >>>> myCompareFile1.replace("\u2019", "'") >>> >>> Strings in Python are immutable. When you call ascii(), you get back a >>> new string, but it's one that has actual backslashes and such in it. >>> (You probably don't need this step, other than for debugging; check >>> the string by printing out the ASCII version of it, but stick to the >>> original for actual processing.) The same is true of the replace() >>> method; it doesn't change the string, it returns a new string. >>> >>>>>> word = "spam" >>>>>> print(word.replace("sp", "h")) >>> ham >>>>>> print(word) >>> spam >>> >>> ChrisA >>> -- >>> https://mail.python.org/mailman/listinfo/python-list >> >> -- >> https://mail.python.org/mailman/listinfo/python-list >> -- >> https://mail.python.org/mailman/listinfo/python-list > > -- > https://mail.python.org/mailman/listinfo/python-list From 2QdxY4RzWzUUiLuE at potatochowder.com Wed Jun 8 14:13:16 2022 From: 2QdxY4RzWzUUiLuE at potatochowder.com (2QdxY4RzWzUUiLuE at potatochowder.com) Date: Wed, 8 Jun 2022 13:13:16 -0500 Subject: How to test characters of a string In-Reply-To: References: Message-ID: On 2022-06-09 at 03:18:56 +1000, Chris Angelico wrote: > On Thu, 9 Jun 2022 at 03:15, <2QdxY4RzWzUUiLuE at potatochowder.com> wrote: > > > > On 2022-06-08 at 08:07:40 -0000, > > De ongekruisigde wrote: > > > > > Depending on the problem a regular expression may be the much simpler > > > solution. I love them for e.g. text parsing and use them all the time. > > > Unrivaled when e.g. parts of text have to be extracted, e.g. from lines > > > like these: > > > > > > root:x:0:0:System administrator:/root:/run/current-system/sw/bin/bash > > > dhcpcd:x:995:991::/var/empty:/run/current-system/sw/bin/nologin > > > nm-iodine:x:996:57::/var/empty:/run/current-system/sw/bin/nologin > > > avahi:x:997:996:avahi-daemon privilege separation user:/var/empty:/run/current-system/sw/bin/nologin > > > sshd:x:998:993:SSH privilege separation user:/var/empty:/run/current-system/sw/bin/nologin > > > geoclue:x:999:998:Geoinformation service:/var/lib/geoclue:/run/current-system/sw/bin/nologin > > > > > > Compare a regexp solution like this: > > > > > > >>> g = re.search(r'([^:]*):([^:]*):(\d+):(\d+):([^:]*):([^:]*):(.*)$' , s) > > > >>> print(g.groups()) > > > ('geoclue', 'x', '999', '998', 'Geoinformation service', '/var/lib/geoclue', '/run/current-system/sw/bin/nologin') > > > > > > to the code one would require to process it manually, with all the edge > > > cases. The regexp surely reads much simpler (?). > > > > Uh... > > > > >>> import pwd # https://docs.python.org/3/library/pwd.html > > >>> [x for x in pwd.getpwall() if x[0] == 'geoclue'] > > [pwd.struct_passwd(pw_name='geoclue', pw_passwd='x', pw_uid=992, pw_gid=992, pw_gecos='Geoinformation service', pw_dir='/var/lib/geoclue', pw_shell='/sbin/nologin')] > > That's great if the lines are specifically coming from your system's > own /etc/passwd, but not so much if you're trying to compare passwd > files from different systems, where you simply have the files > themselves. In addition to pwent to get specific entries from the local password database, POSIX has fpwent to get a specific entry from a stream that looks like /etc/passwd. So even POSIX agrees that if you think you have to process this data manually, you're doing it wrong. Python exposes neither functon directly (at least not in the pwd module or the os module; I didn't dig around or check PyPI). IMO, higher level functions to process such data is way better than a [insert your own adjective/expletive here] regular expression that collects the pieces into numbered groups rather than labeled fields. Readability counts. Yes, absolutely, use a regular expression when all else fails. Don't forget to handle all the edge cases! (I assume that sane OSes preclude colons in paths that are likely to come up in the local password database, but I don't know what happens, e.g., when there's a reason for GECOS to contain a colon.) From rosuav at gmail.com Wed Jun 8 14:15:46 2022 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 9 Jun 2022 04:15:46 +1000 Subject: How to test characters of a string In-Reply-To: References: Message-ID: On Thu, 9 Jun 2022 at 04:14, <2QdxY4RzWzUUiLuE at potatochowder.com> wrote: > > On 2022-06-09 at 03:18:56 +1000, > Chris Angelico wrote: > > > On Thu, 9 Jun 2022 at 03:15, <2QdxY4RzWzUUiLuE at potatochowder.com> wrote: > > > > > > On 2022-06-08 at 08:07:40 -0000, > > > De ongekruisigde wrote: > > > > > > > Depending on the problem a regular expression may be the much simpler > > > > solution. I love them for e.g. text parsing and use them all the time. > > > > Unrivaled when e.g. parts of text have to be extracted, e.g. from lines > > > > like these: > > > > > > > > root:x:0:0:System administrator:/root:/run/current-system/sw/bin/bash > > > > dhcpcd:x:995:991::/var/empty:/run/current-system/sw/bin/nologin > > > > nm-iodine:x:996:57::/var/empty:/run/current-system/sw/bin/nologin > > > > avahi:x:997:996:avahi-daemon privilege separation user:/var/empty:/run/current-system/sw/bin/nologin > > > > sshd:x:998:993:SSH privilege separation user:/var/empty:/run/current-system/sw/bin/nologin > > > > geoclue:x:999:998:Geoinformation service:/var/lib/geoclue:/run/current-system/sw/bin/nologin > > > > > > > > Compare a regexp solution like this: > > > > > > > > >>> g = re.search(r'([^:]*):([^:]*):(\d+):(\d+):([^:]*):([^:]*):(.*)$' , s) > > > > >>> print(g.groups()) > > > > ('geoclue', 'x', '999', '998', 'Geoinformation service', '/var/lib/geoclue', '/run/current-system/sw/bin/nologin') > > > > > > > > to the code one would require to process it manually, with all the edge > > > > cases. The regexp surely reads much simpler (?). > > > > > > Uh... > > > > > > >>> import pwd # https://docs.python.org/3/library/pwd.html > > > >>> [x for x in pwd.getpwall() if x[0] == 'geoclue'] > > > [pwd.struct_passwd(pw_name='geoclue', pw_passwd='x', pw_uid=992, pw_gid=992, pw_gecos='Geoinformation service', pw_dir='/var/lib/geoclue', pw_shell='/sbin/nologin')] > > > > That's great if the lines are specifically coming from your system's > > own /etc/passwd, but not so much if you're trying to compare passwd > > files from different systems, where you simply have the files > > themselves. > > In addition to pwent to get specific entries from the local password > database, POSIX has fpwent to get a specific entry from a stream that > looks like /etc/passwd. So even POSIX agrees that if you think you have > to process this data manually, you're doing it wrong. Python exposes > neither functon directly (at least not in the pwd module or the os > module; I didn't dig around or check PyPI). So...... we can go find some other way of calling fpwent, or we can just parse the file ourselves. It's a very VERY simple format. ChrisA From 2QdxY4RzWzUUiLuE at potatochowder.com Wed Jun 8 14:46:16 2022 From: 2QdxY4RzWzUUiLuE at potatochowder.com (2QdxY4RzWzUUiLuE at potatochowder.com) Date: Wed, 8 Jun 2022 13:46:16 -0500 Subject: How to test characters of a string In-Reply-To: References: Message-ID: On 2022-06-09 at 04:15:46 +1000, Chris Angelico wrote: > On Thu, 9 Jun 2022 at 04:14, <2QdxY4RzWzUUiLuE at potatochowder.com> wrote: > > > > On 2022-06-09 at 03:18:56 +1000, > > Chris Angelico wrote: > > > > > On Thu, 9 Jun 2022 at 03:15, <2QdxY4RzWzUUiLuE at potatochowder.com> wrote: > > > > > > > > On 2022-06-08 at 08:07:40 -0000, > > > > De ongekruisigde wrote: > > > > > > > > > Depending on the problem a regular expression may be the much simpler > > > > > solution. I love them for e.g. text parsing and use them all the time. > > > > > Unrivaled when e.g. parts of text have to be extracted, e.g. from lines > > > > > like these: > > > > > > > > > > root:x:0:0:System administrator:/root:/run/current-system/sw/bin/bash > > > > > dhcpcd:x:995:991::/var/empty:/run/current-system/sw/bin/nologin > > > > > nm-iodine:x:996:57::/var/empty:/run/current-system/sw/bin/nologin > > > > > avahi:x:997:996:avahi-daemon privilege separation user:/var/empty:/run/current-system/sw/bin/nologin > > > > > sshd:x:998:993:SSH privilege separation user:/var/empty:/run/current-system/sw/bin/nologin > > > > > geoclue:x:999:998:Geoinformation service:/var/lib/geoclue:/run/current-system/sw/bin/nologin > > > > > > > > > > Compare a regexp solution like this: > > > > > > > > > > >>> g = re.search(r'([^:]*):([^:]*):(\d+):(\d+):([^:]*):([^:]*):(.*)$' , s) > > > > > >>> print(g.groups()) > > > > > ('geoclue', 'x', '999', '998', 'Geoinformation service', '/var/lib/geoclue', '/run/current-system/sw/bin/nologin') > > > > > > > > > > to the code one would require to process it manually, with all the edge > > > > > cases. The regexp surely reads much simpler (?). > > > > > > > > Uh... > > > > > > > > >>> import pwd # https://docs.python.org/3/library/pwd.html > > > > >>> [x for x in pwd.getpwall() if x[0] == 'geoclue'] > > > > [pwd.struct_passwd(pw_name='geoclue', pw_passwd='x', pw_uid=992, pw_gid=992, pw_gecos='Geoinformation service', pw_dir='/var/lib/geoclue', pw_shell='/sbin/nologin')] > > > > > > That's great if the lines are specifically coming from your system's > > > own /etc/passwd, but not so much if you're trying to compare passwd > > > files from different systems, where you simply have the files > > > themselves. > > > > In addition to pwent to get specific entries from the local password > > database, POSIX has fpwent to get a specific entry from a stream that > > looks like /etc/passwd. So even POSIX agrees that if you think you have > > to process this data manually, you're doing it wrong. Python exposes > > neither functon directly (at least not in the pwd module or the os > > module; I didn't dig around or check PyPI). > > So...... we can go find some other way of calling fpwent, or we can > just parse the file ourselves. It's a very VERY simple format. If you insist: >>> s = 'nm-iodine:x:996:57::/var/empty:/run/current-system/sw/bin/nologin' >>> print(s.split(':')) ['nm-iodine', 'x', '996', '57', '', '/var/empty', '/run/current-system/sw/bin/nologin'] Hesitantly, because this is the Python mailing list, I claim (a) ':' is simpler than r'([^:]*):([^:]*):(\d+):(\d+):([^:]*):([^:]*):(.*)$', and (b) string.split covers pretty much the same edge cases as re.search. From wlfraed at ix.netcom.com Wed Jun 8 13:36:24 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Wed, 08 Jun 2022 13:36:24 -0400 Subject: How to test characters of a string References: <1900098914.424953.1654653206710@mail.yahoo.com> Message-ID: On Wed, 8 Jun 2022 01:53:26 +0000 (UTC), Avi Gross declaimed the following: > >So is it necessary to insist on an exact pattern of two digits followed by a space?? > > >That would fail on?"44 Minutes",?"40 Oz. Dream",?"50 Mission Cap",?"50 Ways to Say Goodbye",?"99 Ways to Die"? > >It looks to me like you need to compare TWICE just in case. If it matches in?the original (perhaps with some normalization of case and?whitespace, fine. If not?will they match if one or both have something to remove as a prefix such as "02 ".?And if you are comparing items where the same song is in two different numeric sequences?on different disks, ... I suspect the OP really needs to extract the /track number/ from the ID3 information, and (converting to a 2digit formatted string) see if the file name begins with that track number... The format of the those filenames appear to be those generated by some software when ripping CDs to MP3s -- for example: -=-=- c:\Music\Roger Miller\All Time Greatest Hits>dir Volume in drive C is OS Volume Serial Number is 4ACC-3CB4 Directory of c:\Music\Roger Miller\All Time Greatest Hits 04/11/2022 05:06 PM . 04/11/2022 05:06 PM .. 07/26/2018 11:20 AM 4,493,279 01 Dang Me.mp3 07/26/2018 11:20 AM 5,072,414 02 Chug-A-Lug.mp3 07/26/2018 11:20 AM 4,275,844 03 Do-Wacka-Do.mp3 07/26/2018 11:20 AM 4,284,208 04 In the Summertime.mp3 07/26/2018 11:20 AM 6,028,730 05 King of the Road.mp3 07/26/2018 11:20 AM 4,662,182 06 You Can't Roller Skate in a Buffalo Herd.mp3 07/26/2018 11:20 AM 5,624,704 07 Engine, Engine #9.mp3 07/26/2018 11:20 AM 5,002,492 08 One Dyin' and a Buryin'.mp3 07/26/2018 11:21 AM 6,799,224 09 Last Word in Lonesome Is Me.mp3 07/26/2018 11:21 AM 5,637,230 10 Kansas City Star.mp3 07/26/2018 11:21 AM 4,656,910 11 England Swings.mp3 07/26/2018 11:21 AM 5,836,638 12 Husbands and Wives.mp3 07/26/2018 11:21 AM 5,470,216 13 I've Been a Long Time Leavin'.mp3 07/26/2018 11:21 AM 6,230,236 14 Walkin' in the Sunshine.mp3 07/26/2018 11:21 AM 6,416,060 15 Little Green Apples.mp3 07/26/2018 11:21 AM 9,794,442 16 Me and Bobby McGee.mp3 07/26/2018 11:22 AM 7,330,642 17 Where Have All the Average People Gone.mp3 07/26/2018 11:22 AM 7,334,752 18 South.mp3 07/26/2018 11:22 AM 6,981,924 19 Tomorrow Night in Baltimore.mp3 07/26/2018 11:22 AM 9,353,872 20 River in the Rain.mp3 20 File(s) 121,285,999 bytes 2 Dir(s) 295,427,198,976 bytes free c:\Music\Roger Miller\All Time Greatest Hits> -=-=- Untested (especially the ID3 "variable" -- substitute variables as needed to match the original code): >>> id3Track = 2 >>> track_number = "%2.2d " % id3Track >>> track_number '02 ' >>> filename = "02 This is the life.mp3" >>> if filename.startswith(track_number): ... nametitle = filename[3:] ... else: ... nametitle = filename ... >>> if nametitle.endswith(".mp3"): ... nametitle = nametitle[:-4] ... >>> nametitle 'This is the life' Handling ASCII ' and " vs Unicode "smart" quotes is a different matter. One may still run the risk of having a filename without a track number BUT having a number that just manages to match the track number. To account for that I'd suggest using the sequence: * Strip extension (if filename.lower().endswith(".mp3"): ...) * Handle any Unicode/ASCII quotes in both filename AND ID3 track title * Compare filename and title. * IF MATCHED -- done * IF NOT MATCHED * Format ID3 track number as shown above * Compare filename to (formatted track number + track title) * IF MATCHED -- done * IF NOT MATCHED * Log full filename and ID3 track title/track number to a log for later examination. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From wlfraed at ix.netcom.com Wed Jun 8 13:55:10 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Wed, 08 Jun 2022 13:55:10 -0400 Subject: How to replace characters in a string? References: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> Message-ID: On Wed, 8 Jun 2022 11:09:05 +0200, Dave declaimed the following: >Hi, > >Thanks for this! > >So, is there a copy function/method that returns a MutableString like in objective-C? I?ve solved this problems before in a number of languages like Objective-C and AppleScript. There are no mutable strings in Python. Any operation manipulating a string RETURNS A MODIFIED NEW STRING. >myString = 'Hello' >myNewstring = myString.replace(myString,'e','a?) > Please study the library reference manual -- it should be clear what the various string methods can perform. Hint: they are "methods", which means whatever is before the . becomes the automatic "self" argument inside the method) https://docs.python.org/3/library/stdtypes.html#string-methods """ str.replace(old, new[, count]) Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. """ myNewstring = myString.replace("e", "a") However... Please study """ static str.maketrans(x[, y[, z]]) This static method returns a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then be converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result. """ """ str.translate(table) Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via __getitem__(), typically a mapping or sequence. When indexed by a Unicode ordinal (an integer), the table object can do any of the following: return a Unicode ordinal or a string, to map the character to one or more other characters; return None, to delete the character from the return string; or raise a LookupError exception, to map the character to itself. You can use str.maketrans() to create a translation map from character-to-character mappings in different formats. See also the codecs module for a more flexible approach to custom character mappings. """ Hmmm, I'm out-of-date... I'm on v3.8 and .removeprefix() and .removesuffix() (from v3.9) simplify my previous post... Instead of if myString.lower().endswith(".mp3"): #lower() is a precaution for case myString = myString[:-4] just use myString = myString.lower().removesuffix(".mp3") {note, you'll have to make the compare using .lower() on the other name since this statement returns a lowercased version} -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From ongekruisigde at news.eternal-september.org Wed Jun 8 14:55:04 2022 From: ongekruisigde at news.eternal-september.org (De ongekruisigde) Date: Wed, 8 Jun 2022 18:55:04 -0000 (UTC) Subject: How to test characters of a string References: Message-ID: On 2022-06-08, 2QdxY4RzWzUUiLuE at potatochowder.com <2QdxY4RzWzUUiLuE at potatochowder.com> wrote: > On 2022-06-08 at 08:07:40 -0000, > De ongekruisigde wrote: > >> Depending on the problem a regular expression may be the much simpler >> solution. I love them for e.g. text parsing and use them all the time. >> Unrivaled when e.g. parts of text have to be extracted, e.g. from lines >> like these: >> >> root:x:0:0:System administrator:/root:/run/current-system/sw/bin/bash >> dhcpcd:x:995:991::/var/empty:/run/current-system/sw/bin/nologin >> nm-iodine:x:996:57::/var/empty:/run/current-system/sw/bin/nologin >> avahi:x:997:996:avahi-daemon privilege separation user:/var/empty:/run/current-system/sw/bin/nologin >> sshd:x:998:993:SSH privilege separation user:/var/empty:/run/current-system/sw/bin/nologin >> geoclue:x:999:998:Geoinformation service:/var/lib/geoclue:/run/current-system/sw/bin/nologin >> >> Compare a regexp solution like this: >> >> >>> g = re.search(r'([^:]*):([^:]*):(\d+):(\d+):([^:]*):([^:]*):(.*)$' , s) >> >>> print(g.groups()) >> ('geoclue', 'x', '999', '998', 'Geoinformation service', '/var/lib/geoclue', '/run/current-system/sw/bin/nologin') >> >> to the code one would require to process it manually, with all the edge >> cases. The regexp surely reads much simpler (?). > > Uh... > > >>> import pwd # https://docs.python.org/3/library/pwd.html > >>> [x for x in pwd.getpwall() if x[0] == 'geoclue'] > [pwd.struct_passwd(pw_name='geoclue', pw_passwd='x', pw_uid=992, pw_gid=992, pw_gecos='Geoinformation service', pw_dir='/var/lib/geoclue', pw_shell='/sbin/nologin')] Yeah... Well, it was just an example and it must be clear by now I'm not a Python programmer. -- You're rewriting parts of Quake in *Python*? MUAHAHAHA From ongekruisigde at news.eternal-september.org Wed Jun 8 14:57:27 2022 From: ongekruisigde at news.eternal-september.org (De ongekruisigde) Date: Wed, 8 Jun 2022 18:57:27 -0000 (UTC) Subject: How to test characters of a string References: Message-ID: On 2022-06-08, 2QdxY4RzWzUUiLuE at potatochowder.com <2QdxY4RzWzUUiLuE at potatochowder.com> wrote: > On 2022-06-09 at 04:15:46 +1000, > Chris Angelico wrote: > >> On Thu, 9 Jun 2022 at 04:14, <2QdxY4RzWzUUiLuE at potatochowder.com> wrote: >> > >> > On 2022-06-09 at 03:18:56 +1000, >> > Chris Angelico wrote: >> > >> > > On Thu, 9 Jun 2022 at 03:15, <2QdxY4RzWzUUiLuE at potatochowder.com> wrote: >> > > > >> > > > On 2022-06-08 at 08:07:40 -0000, >> > > > De ongekruisigde wrote: >> > > > >> > > > > Depending on the problem a regular expression may be the much simpler >> > > > > solution. I love them for e.g. text parsing and use them all the time. >> > > > > Unrivaled when e.g. parts of text have to be extracted, e.g. from lines >> > > > > like these: >> > > > > >> > > > > root:x:0:0:System administrator:/root:/run/current-system/sw/bin/bash >> > > > > dhcpcd:x:995:991::/var/empty:/run/current-system/sw/bin/nologin >> > > > > nm-iodine:x:996:57::/var/empty:/run/current-system/sw/bin/nologin >> > > > > avahi:x:997:996:avahi-daemon privilege separation user:/var/empty:/run/current-system/sw/bin/nologin >> > > > > sshd:x:998:993:SSH privilege separation user:/var/empty:/run/current-system/sw/bin/nologin >> > > > > geoclue:x:999:998:Geoinformation service:/var/lib/geoclue:/run/current-system/sw/bin/nologin >> > > > > >> > > > > Compare a regexp solution like this: >> > > > > >> > > > > >>> g = re.search(r'([^:]*):([^:]*):(\d+):(\d+):([^:]*):([^:]*):(.*)$' , s) >> > > > > >>> print(g.groups()) >> > > > > ('geoclue', 'x', '999', '998', 'Geoinformation service', '/var/lib/geoclue', '/run/current-system/sw/bin/nologin') >> > > > > >> > > > > to the code one would require to process it manually, with all the edge >> > > > > cases. The regexp surely reads much simpler (?). >> > > > >> > > > Uh... >> > > > >> > > > >>> import pwd # https://docs.python.org/3/library/pwd.html >> > > > >>> [x for x in pwd.getpwall() if x[0] == 'geoclue'] >> > > > [pwd.struct_passwd(pw_name='geoclue', pw_passwd='x', pw_uid=992, pw_gid=992, pw_gecos='Geoinformation service', pw_dir='/var/lib/geoclue', pw_shell='/sbin/nologin')] >> > > >> > > That's great if the lines are specifically coming from your system's >> > > own /etc/passwd, but not so much if you're trying to compare passwd >> > > files from different systems, where you simply have the files >> > > themselves. >> > >> > In addition to pwent to get specific entries from the local password >> > database, POSIX has fpwent to get a specific entry from a stream that >> > looks like /etc/passwd. So even POSIX agrees that if you think you have >> > to process this data manually, you're doing it wrong. Python exposes >> > neither functon directly (at least not in the pwd module or the os >> > module; I didn't dig around or check PyPI). >> >> So...... we can go find some other way of calling fpwent, or we can >> just parse the file ourselves. It's a very VERY simple format. > > If you insist: > > >>> s = 'nm-iodine:x:996:57::/var/empty:/run/current-system/sw/bin/nologin' > >>> print(s.split(':')) > ['nm-iodine', 'x', '996', '57', '', '/var/empty', '/run/current-system/sw/bin/nologin'] > > Hesitantly, because this is the Python mailing list, I claim (a) ':' is > simpler than r'([^:]*):([^:]*):(\d+):(\d+):([^:]*):([^:]*):(.*)$', and > (b) string.split covers pretty much the same edge cases as re.search. Ah, but you don't catch the be numeric of fields (0-based) 2 and 3! But agreed, it's not the best of examples. -- You're rewriting parts of Quake in *Python*? MUAHAHAHA From greg.ewing at canterbury.ac.nz Wed Jun 8 17:38:29 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Thu, 9 Jun 2022 09:38:29 +1200 Subject: How to replace characters in a string? In-Reply-To: References: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> <3FB6620E-D54C-40F6-8223-7D3E17DB55ED@looktowindward.com> Message-ID: On 8/06/22 10:26 pm, Jon Ribbens wrote: > Here's a head-start on some characters you might want to translate, Another possibility that might make sense in this case is to simply strip out all punctuation before comparing. That would take care of things being spelled with or without hyphens, commas, etc. -- Greg From pfoosion at gmail.com Wed Jun 8 18:53:43 2022 From: pfoosion at gmail.com (Richard David) Date: Wed, 8 Jun 2022 15:53:43 -0700 (PDT) Subject: PYLAUNCH_DEBUG not printing info Message-ID: <572c1daf-256a-480e-8e4a-40a6b345a423n@googlegroups.com> Why am I not getting debug output on my windows 10 machine: C:\temp>\Windows\py.exe -0 -V:3.11 * Python 3.11 (64-bit) -V:3.10 Python 3.10 (64-bit) C:\temp>set PYLAUNCH_DEBUG=1 C:\temp>\Windows\py.exe Python 3.11.0b3 (main, Jun 1 2022, 13:29:14) [MSC v.1932 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ^Z From greg.ewing at canterbury.ac.nz Wed Jun 8 22:43:40 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Thu, 9 Jun 2022 14:43:40 +1200 Subject: How to replace characters in a string? In-Reply-To: References: <0CBD9609-D7E7-4DF3-82E1-524367FB844C@looktowindward.com> Message-ID: On 9/06/22 5:55 am, Dennis Lee Bieber wrote: > There are no mutable strings in Python. If you really want a mutable sequence of characters, you can use array.array, but you won't be able to use it directly in place of a string in most contexts. -- Greg From dave at looktowindward.com Thu Jun 9 02:50:46 2022 From: dave at looktowindward.com (Dave) Date: Thu, 9 Jun 2022 08:50:46 +0200 Subject: How to test characters of a string In-Reply-To: References: <1900098914.424953.1654653206710@mail.yahoo.com> Message-ID: Hi, I?ve found you also need to take care of multiple disk CD releases. These have a format of ?1-01 Track Name? ?2-02 Trackl Name" Meaning Disk 1 Track1, Disk 2, Track 2. Also A and B Sides (from Vinyl LPs) ?A1-Track Name? ?B2-Track Name? Side A, Track 1, etc. Cheers Dave > On 8 Jun 2022, at 19:36, Dennis Lee Bieber wrote: > > On Wed, 8 Jun 2022 01:53:26 +0000 (UTC), Avi Gross > declaimed the following: > > >> >> So is it necessary to insist on an exact pattern of two digits followed by a space? >> >> >> That would fail on "44 Minutes", "40 Oz. Dream", "50 Mission Cap", "50 Ways to Say Goodbye", "99 Ways to Die" >> >> It looks to me like you need to compare TWICE just in case. If it matches in the original (perhaps with some normalization of case and whitespace, fine. If not will they match if one or both have something to remove as a prefix such as "02 ". And if you are comparing items where the same song is in two different numeric sequences on different disks, ... > > I suspect the OP really needs to extract the /track number/ from the > ID3 information, and (converting to a 2digit formatted string) see if the > file name begins with that track number... The format of the those > filenames appear to be those generated by some software when ripping CDs to > MP3s -- for example: > > -=-=- > c:\Music\Roger Miller\All Time Greatest Hits>dir > Volume in drive C is OS > Volume Serial Number is 4ACC-3CB4 > > Directory of c:\Music\Roger Miller\All Time Greatest Hits > > 04/11/2022 05:06 PM . > 04/11/2022 05:06 PM .. > 07/26/2018 11:20 AM 4,493,279 01 Dang Me.mp3 > 07/26/2018 11:20 AM 5,072,414 02 Chug-A-Lug.mp3 > 07/26/2018 11:20 AM 4,275,844 03 Do-Wacka-Do.mp3 > 07/26/2018 11:20 AM 4,284,208 04 In the Summertime.mp3 > 07/26/2018 11:20 AM 6,028,730 05 King of the Road.mp3 > 07/26/2018 11:20 AM 4,662,182 06 You Can't Roller Skate in a > Buffalo Herd.mp3 > 07/26/2018 11:20 AM 5,624,704 07 Engine, Engine #9.mp3 > 07/26/2018 11:20 AM 5,002,492 08 One Dyin' and a Buryin'.mp3 > 07/26/2018 11:21 AM 6,799,224 09 Last Word in Lonesome Is Me.mp3 > 07/26/2018 11:21 AM 5,637,230 10 Kansas City Star.mp3 > 07/26/2018 11:21 AM 4,656,910 11 England Swings.mp3 > 07/26/2018 11:21 AM 5,836,638 12 Husbands and Wives.mp3 > 07/26/2018 11:21 AM 5,470,216 13 I've Been a Long Time Leavin'.mp3 > 07/26/2018 11:21 AM 6,230,236 14 Walkin' in the Sunshine.mp3 > 07/26/2018 11:21 AM 6,416,060 15 Little Green Apples.mp3 > 07/26/2018 11:21 AM 9,794,442 16 Me and Bobby McGee.mp3 > 07/26/2018 11:22 AM 7,330,642 17 Where Have All the Average People > Gone.mp3 > 07/26/2018 11:22 AM 7,334,752 18 South.mp3 > 07/26/2018 11:22 AM 6,981,924 19 Tomorrow Night in Baltimore.mp3 > 07/26/2018 11:22 AM 9,353,872 20 River in the Rain.mp3 > 20 File(s) 121,285,999 bytes > 2 Dir(s) 295,427,198,976 bytes free > > c:\Music\Roger Miller\All Time Greatest Hits> > -=-=- > > Untested (especially the ID3 "variable" -- substitute variables as > needed to match the original code): > >>>> id3Track = 2 >>>> track_number = "%2.2d " % id3Track >>>> track_number > '02 ' >>>> filename = "02 This is the life.mp3" >>>> if filename.startswith(track_number): > ... nametitle = filename[3:] > ... else: > ... nametitle = filename > ... >>>> if nametitle.endswith(".mp3"): > ... nametitle = nametitle[:-4] > ... >>>> nametitle > 'This is the life' > > Handling ASCII ' and " vs Unicode "smart" quotes is a different matter. > > One may still run the risk of having a filename without a track number > BUT having a number that just manages to match the track number. To account > for that I'd suggest using the sequence: > > * Strip extension (if filename.lower().endswith(".mp3"): ...) > * Handle any Unicode/ASCII quotes in both filename AND ID3 track title > * Compare filename and title. > * IF MATCHED -- done > * IF NOT MATCHED > * Format ID3 track number as shown above > * Compare filename to (formatted track number + track title) > * IF MATCHED -- done > * IF NOT MATCHED > * Log full filename and ID3 track title/track number to a > log for later examination. > > > > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ > -- > https://mail.python.org/mailman/listinfo/python-list From __peter__ at web.de Thu Jun 9 04:40:05 2022 From: __peter__ at web.de (Peter Otten) Date: Thu, 9 Jun 2022 10:40:05 +0200 Subject: PYLAUNCH_DEBUG not printing info In-Reply-To: <572c1daf-256a-480e-8e4a-40a6b345a423n@googlegroups.com> References: <572c1daf-256a-480e-8e4a-40a6b345a423n@googlegroups.com> Message-ID: <65782a50-6d99-f90d-994d-97d70b77efeb@web.de> On 09/06/2022 00:53, Richard David wrote: > Why am I not getting debug output on my windows 10 machine: > > C:\temp>\Windows\py.exe -0 > -V:3.11 * Python 3.11 (64-bit) > -V:3.10 Python 3.10 (64-bit) > > C:\temp>set PYLAUNCH_DEBUG=1 > > C:\temp>\Windows\py.exe > Python 3.11.0b3 (main, Jun 1 2022, 13:29:14) [MSC v.1932 64 bit (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> ^Z > Does getenv() confirm that the variable is set? >>> import os >>> os.getenv("PYLAUNCH_DEBUG") '1' From __peter__ at web.de Thu Jun 9 05:38:10 2022 From: __peter__ at web.de (Peter Otten) Date: Thu, 9 Jun 2022 11:38:10 +0200 Subject: PYLAUNCH_DEBUG not printing info In-Reply-To: <572c1daf-256a-480e-8e4a-40a6b345a423n@googlegroups.com> References: <572c1daf-256a-480e-8e4a-40a6b345a423n@googlegroups.com> Message-ID: <42085f2c-f96f-1c43-484b-62d46b723ddd@web.de> On 09/06/2022 00:53, Richard David wrote: > Why am I not getting debug output on my windows 10 machine: > > C:\temp>\Windows\py.exe -0 > -V:3.11 * Python 3.11 (64-bit) > -V:3.10 Python 3.10 (64-bit) > > C:\temp>set PYLAUNCH_DEBUG=1 > > C:\temp>\Windows\py.exe > Python 3.11.0b3 (main, Jun 1 2022, 13:29:14) [MSC v.1932 64 bit (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> ^Z > Looks like the variable is now called PYLAUNCHER_DEBUG: https://docs.python.org/3.11/using/windows.html#diagnostics From eryksun at gmail.com Thu Jun 9 09:28:32 2022 From: eryksun at gmail.com (Eryk Sun) Date: Thu, 9 Jun 2022 08:28:32 -0500 Subject: PYLAUNCH_DEBUG not printing info In-Reply-To: <42085f2c-f96f-1c43-484b-62d46b723ddd@web.de> References: <572c1daf-256a-480e-8e4a-40a6b345a423n@googlegroups.com> <42085f2c-f96f-1c43-484b-62d46b723ddd@web.de> Message-ID: On 6/9/22, Peter Otten <__peter__ at web.de> wrote: > > Looks like the variable is now called PYLAUNCHER_DEBUG: > > https://docs.python.org/3.11/using/windows.html#diagnostics I wonder why Steve changed the name of the environment variable without supporting the old "PYLAUNCH_DEBUG" name, at least for a couple of releases. Since 3.11 is still in beta, with the first release candidate expected in August, there's still time to restore support for the old name. From avigross at verizon.net Thu Jun 9 13:33:44 2022 From: avigross at verizon.net (Avi Gross) Date: Thu, 9 Jun 2022 17:33:44 +0000 (UTC) Subject: How to test characters of a string In-Reply-To: References: <1900098914.424953.1654653206710@mail.yahoo.com> Message-ID: <1418728975.920840.1654796024274@mail.yahoo.com> Dave, Sometimes a task is done faster by NOT programming anything in any language! Not only have you spent a lot of your own time but many dozens of messages?here have dragged in others, who gain nothing ;-) The domain you are operating in seems to have lots of variants in how the titles?are stored as names and you keep finding new variants. Yes, if your goal is to?use this as a way to learn more in general about Python, clearly it may meet that?goal! Contrary to what I (and some others) said earlier, it may be time to consider?regular expressions and other heavier artillery! LOL! I do not plan on sticking with your twists and turns but will quickly address your variants. Sides that come in two's like records are presumably limited to using A and B?in your example. But multiple disks connected can mean the digit(s) following?can have double digits or even more. Your python code may have to contain?lots of functions you create that match some pattern and return some value and?perhaps other functions that know how to convert from that format to a common?canonical format of your own so they can be compared. Your main code may need to try them in various sequences till it finds a match and?so on. But when you are done, in what format do you save them? The original or your?minimal?? Still confusing to me, as someone who does not give a darn, is the reality that?many songs may have the same name but be different as in a song from?Sinatra when he was young and a later recording? with a different orchestra or by?a Sinatra imitator. They may all be titled something like "New York, New York" or?"NEW YORK -- NEW YORK" which your algorithm folds into the same characters. So I am guessing you also need to access other data about the person who sings?it or what year it was released to make comparisons. At some point you may want?to create or borrow some sort of class/object that encapsulates your data as well?as methods that let you do things like make a canonical version of the Title and then?a way to ask if Object A is reasonably equal to object B might happen if?you define a function/method of __eq__ for that class. It might take you years and need periodic refining as you encounter ever more?varied ways people have chosen to label their music, but so what? LOL! Humor or sarcasm aside, your incremental exploratory method reminds me why it?is a good idea to first scope out the outlines of your problem space and make?some key decisions and write out a fairly detailed set of requirements before?seriously making more than prototypes. You might get very different help from?people if they understood that your first request was far from complete but only?one of many that may better be worked on some other way. And I wonder if you did any search of the internet to see if anyone had done anything?similar in Python (or another language) that may handle parts of what you need before?asking here. I note lots of people who come with what they consider a good?programming background have to adjust to aspects of languages like python as?what they know is in some ways wrong or inadequate in a new environment.? -----Original Message----- From: Dave To: python-list at python.org Sent: Thu, Jun 9, 2022 2:50 am Subject: Re: How to test characters of a string Hi, I?ve found you also need to take care of multiple disk CD releases. These have a format of ?1-01 Track Name? ?2-02? Trackl Name" Meaning Disk 1 Track1, Disk 2, Track 2. Also A and B Sides (from Vinyl LPs) ?A1-Track Name? ?B2-Track Name? Side A, Track 1, etc. Cheers Dave > On 8 Jun 2022, at 19:36, Dennis Lee Bieber wrote: > > On Wed, 8 Jun 2022 01:53:26 +0000 (UTC), Avi Gross > declaimed the following: > > >> >> So is it necessary to insist on an exact pattern of two digits followed by a space? >> >> >> That would fail on "44 Minutes", "40 Oz. Dream", "50 Mission Cap", "50 Ways to Say Goodbye", "99 Ways to Die" >> >> It looks to me like you need to compare TWICE just in case. If it matches in the original (perhaps with some normalization of case and whitespace, fine. If not will they match if one or both have something to remove as a prefix such as "02 ". And if you are comparing items where the same song is in two different numeric sequences on different disks, ... > > ??? I suspect the OP really needs to extract the /track number/ from the > ID3 information, and (converting to a 2digit formatted string) see if the > file name begins with that track number... The format of the those > filenames appear to be those generated by some software when ripping CDs to > MP3s -- for example: > > -=-=- > c:\Music\Roger Miller\All Time Greatest Hits>dir > Volume in drive C is OS > Volume Serial Number is 4ACC-3CB4 > > Directory of c:\Music\Roger Miller\All Time Greatest Hits > > 04/11/2022? 05:06 PM? ? ? ? ? ? ? . > 04/11/2022? 05:06 PM? ? ? ? ? ? ? .. > 07/26/2018? 11:20 AM? ? ? ? 4,493,279 01 Dang Me.mp3 > 07/26/2018? 11:20 AM? ? ? ? 5,072,414 02 Chug-A-Lug.mp3 > 07/26/2018? 11:20 AM? ? ? ? 4,275,844 03 Do-Wacka-Do.mp3 > 07/26/2018? 11:20 AM? ? ? ? 4,284,208 04 In the Summertime.mp3 > 07/26/2018? 11:20 AM? ? ? ? 6,028,730 05 King of the Road.mp3 > 07/26/2018? 11:20 AM? ? ? ? 4,662,182 06 You Can't Roller Skate in a > Buffalo Herd.mp3 > 07/26/2018? 11:20 AM? ? ? ? 5,624,704 07 Engine, Engine #9.mp3 > 07/26/2018? 11:20 AM? ? ? ? 5,002,492 08 One Dyin' and a Buryin'.mp3 > 07/26/2018? 11:21 AM? ? ? ? 6,799,224 09 Last Word in Lonesome Is Me.mp3 > 07/26/2018? 11:21 AM? ? ? ? 5,637,230 10 Kansas City Star.mp3 > 07/26/2018? 11:21 AM? ? ? ? 4,656,910 11 England Swings.mp3 > 07/26/2018? 11:21 AM? ? ? ? 5,836,638 12 Husbands and Wives.mp3 > 07/26/2018? 11:21 AM? ? ? ? 5,470,216 13 I've Been a Long Time Leavin'.mp3 > 07/26/2018? 11:21 AM? ? ? ? 6,230,236 14 Walkin' in the Sunshine.mp3 > 07/26/2018? 11:21 AM? ? ? ? 6,416,060 15 Little Green Apples.mp3 > 07/26/2018? 11:21 AM? ? ? ? 9,794,442 16 Me and Bobby McGee.mp3 > 07/26/2018? 11:22 AM? ? ? ? 7,330,642 17 Where Have All the Average People > Gone.mp3 > 07/26/2018? 11:22 AM? ? ? ? 7,334,752 18 South.mp3 > 07/26/2018? 11:22 AM? ? ? ? 6,981,924 19 Tomorrow Night in Baltimore.mp3 > 07/26/2018? 11:22 AM? ? ? ? 9,353,872 20 River in the Rain.mp3 >? ? ? ? ? ? ? 20 File(s)? ? 121,285,999 bytes >? ? ? ? ? ? ? 2 Dir(s)? 295,427,198,976 bytes free > > c:\Music\Roger Miller\All Time Greatest Hits> > -=-=- > > ??? Untested (especially the ID3 "variable" -- substitute variables as > needed to match the original code): > >>>> id3Track = 2 >>>> track_number = "%2.2d " % id3Track >>>> track_number > '02 ' >>>> filename = "02 This is the life.mp3" >>>> if filename.startswith(track_number): > ... ??? nametitle = filename[3:] > ... else: > ... ??? nametitle = filename > ... ??? >>>> if nametitle.endswith(".mp3"): > ... ??? ??? nametitle = nametitle[:-4] > ... ??? >>>> nametitle > 'This is the life' > > ??? Handling ASCII ' and " vs Unicode "smart" quotes is a different matter. > > ??? One may still run the risk of having a filename without a track number > BUT having a number that just manages to match the track number. To account > for that I'd suggest using the sequence: > > *??? Strip extension (if filename.lower().endswith(".mp3"): ...) > *??? Handle any Unicode/ASCII quotes in both filename AND ID3 track title > *??? Compare filename and title. > *??? ??? IF MATCHED -- done > *??? ??? IF NOT MATCHED > *??? ??? ??? Format ID3 track number as shown above > *??? ??? ??? Compare filename to (formatted track number + track title) > *??? ??? ??? ??? IF MATCHED -- done > *??? ??? ??? ??? IF NOT MATCHED > *??? ??? ??? ??? ??? Log full filename and ID3 track title/track number to a > log for later examination. > > > > -- > ??? Wulfraed? ? ? ? ? ? ? ? Dennis Lee Bieber? ? ? ? AF6VN > ??? wlfraed at ix.netcom.com? ? http://wlfraed.microdiversity.freeddns.org/ > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list From jschwar at sbcglobal.net Thu Jun 9 12:16:50 2022 From: jschwar at sbcglobal.net (jschwar at sbcglobal.net) Date: Thu, 9 Jun 2022 11:16:50 -0500 Subject: cpython and python and visual studio 2019 References: <000e01d87c1c$53e8e4d0$fbbaae70$.ref@sbcglobal.net> Message-ID: <000e01d87c1c$53e8e4d0$fbbaae70$@sbcglobal.net> I contacted Visual Studio 2019 support about this and they referred me to this site, but I'm not sure this is a bug or not (https://github.com/python/cpython/issues/new?assignees= &labels=type-bug&template=bug.md). If I should open a bug request, please let me know and I will. I'm not new to python, but I'm new to cpython and visual studio. I need to install Visual Studio 2019 and get the PCBuild/get_external.bat file up and running. I have python 3.10.4 installed. I tried installing the Community version of Visual Studio 2019 version 16.11, but from what I understand, it's supposed to create a folder in my python directory called PCBuild with that bat file in it and it doesn't. I've searched my C drive for PCBuild and get_external.bat and nothing is found. I've executed this command and from what I can tell, I have installed the correct version of Visual Studio: python -c "import sys; print(sys.version)" 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)] This website says to install version 16.11: https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B I did select the following options when installing Visual Studio 2019: Workloads: Python Development Desktop Development with C++ Under python development I have selected the following: Python native development tools Python web support Live Share Python 3 64-bit (3.9.7) Under Desktop Development with C++ I have selected the following: Included: C++ Core Desktop features Optional: MSVC v142 VS 2019 C++ x64/x86 build Windows 10 SDK (10.0.19041.0) Just-In-Time debugger C++ Profiling tools C++ CMake tools for Windows C++ ATL for latest v142 build tools Test Adapter for Boost.Test Test adapter for Google Test Live Share IntelliCode C++ AddressSanitizer Windows 10 SDK (10.0.18362.0) Can someone please help me on this? Like I said, if I should open a bug report, please let me know and I will. From dave at looktowindward.com Thu Jun 9 06:43:18 2022 From: dave at looktowindward.com (Dave) Date: Thu, 9 Jun 2022 12:43:18 +0200 Subject: Function to Print a nicely formatted Dictionary or List? Message-ID: <6C7CEF1D-A810-44E0-8A23-6B34916C308D@looktowindward.com> Hi, Before I write my own I wondering if anyone knows of a function that will print a nicely formatted dictionary? By nicely formatted I mean not all on one line! Cheers Dave From auriocus at gmx.de Thu Jun 9 08:23:07 2022 From: auriocus at gmx.de (Christian Gollwitzer) Date: Thu, 9 Jun 2022 13:23:07 +0100 Subject: How to test characters of a string In-Reply-To: References: <1900098914.424953.1654653206710@mail.yahoo.com> Message-ID: Am 09.06.22 um 07:50 schrieb Dave: > Hi, > > I?ve found you also need to take care of multiple disk CD releases. These have a format of > > ?1-01 Track Name? > ?2-02 Trackl Name" > > Meaning Disk 1 Track1, Disk 2, Track 2. > > Also A and B Sides (from Vinyl LPs) > > ?A1-Track Name? > ?B2-Track Name? > > Side A, Track 1, etc. > Now you're getting into the complexity that is better handled by REs than by individual character examination. The first of your formats matches the RE \d-\d{2} (one digit, - two digits). Anchor that to check for a match at the beginning. The second one matches (A|B)\d- As long as one digit is enough. What is your goal, to extract these numbers or to strip them? Regexes can do both relatively easily. Christian From auriocus at gmx.de Thu Jun 9 08:29:26 2022 From: auriocus at gmx.de (Christian Gollwitzer) Date: Thu, 9 Jun 2022 13:29:26 +0100 Subject: How to test characters of a string In-Reply-To: References: Message-ID: Am 08.06.22 um 19:57 schrieb De ongekruisigde: > On 2022-06-08, 2QdxY4RzWzUUiLuE at potatochowder.com <2QdxY4RzWzUUiLuE at potatochowder.com> wrote: >> On 2022-06-09 at 04:15:46 +1000, >> Chris Angelico wrote: >> >> If you insist: >> >> >>> s = 'nm-iodine:x:996:57::/var/empty:/run/current-system/sw/bin/nologin' >> >>> print(s.split(':')) >> ['nm-iodine', 'x', '996', '57', '', '/var/empty', '/run/current-system/sw/bin/nologin'] >> >> Hesitantly, because this is the Python mailing list, I claim (a) ':' is >> simpler than r'([^:]*):([^:]*):(\d+):(\d+):([^:]*):([^:]*):(.*)$', and >> (b) string.split covers pretty much the same edge cases as re.search. > > Ah, but you don't catch the be numeric of fields (0-based) 2 and 3! But > agreed, it's not the best of examples. Yes, that is a simplistic example, since the : can't even be quoted to appear in that format (which would require higher-order parsing than a simple split) Fortunately, the OP has just given another requirement to recognise different patterns, and now it went into a direction where it will become quite ugly if you avoid REs or any other pattern matching tools. This is also the main reason I suggested REs initially - often if you see other patterns in the data, you can easily adapt a RE solution, whereas you'll have to write the thing from ground up anew if you do it manually. Christian From pi0003 at uah.edu Thu Jun 9 11:35:59 2022 From: pi0003 at uah.edu (Payton Ireland) Date: Thu, 9 Jun 2022 08:35:59 -0700 (PDT) Subject: Missing global # gdal DRIVER_NAME declaration in gdal_array.py In-Reply-To: References: Message-ID: <902c4f31-2a0b-4d08-81ba-466277d7d742n@googlegroups.com> On Tuesday, March 8, 2022 at 12:52:29 PM UTC-6, Shaozhong SHI wrote: > The following warning kept coming up when running ogr2ogr. > > Warning 1: Missing global # gdal: DRIVER_NAME declaration in > C:\Users\AppData\Local\Programs\Python\Python36\Lib\site-packages\osgeo\gdal_array.py > > What steps to be take to resolve this issue? > > Regards, > > David Hi David, I am having this same issue. Where you ever able to resolve it? Payton From jschwar at sbcglobal.net Thu Jun 9 13:41:43 2022 From: jschwar at sbcglobal.net (jschwar at sbcglobal.net) Date: Thu, 9 Jun 2022 12:41:43 -0500 Subject: cpython and python and visual studio 2019 Message-ID: <000501d87c28$2f028520$8d078f60$@sbcglobal.net> Never mind. I figured it out myself. It's not documented very well. From: jschwar at sbcglobal.net Sent: Thursday, June 9, 2022 11:17 AM To: 'python-list at python.org' Subject: cpython and python and visual studio 2019 I contacted Visual Studio 2019 support about this and they referred me to this site, but I'm not sure this is a bug or not (https://github.com/python/cpython/issues/new?assignees= &labels=type-bug&template=bug.md). If I should open a bug request, please let me know and I will. I'm not new to python, but I'm new to cpython and visual studio. I need to install Visual Studio 2019 and get the PCBuild/get_external.bat file up and running. I have python 3.10.4 installed. I tried installing the Community version of Visual Studio 2019 version 16.11, but from what I understand, it's supposed to create a folder in my python directory called PCBuild with that bat file in it and it doesn't. I've searched my C drive for PCBuild and get_external.bat and nothing is found. I've executed this command and from what I can tell, I have installed the correct version of Visual Studio: python -c "import sys; print(sys.version)" 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)] This website says to install version 16.11: https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B I did select the following options when installing Visual Studio 2019: Workloads: Python Development Desktop Development with C++ Under python development I have selected the following: Python native development tools Python web support Live Share Python 3 64-bit (3.9.7) Under Desktop Development with C++ I have selected the following: Included: C++ Core Desktop features Optional: MSVC v142 VS 2019 C++ x64/x86 build Windows 10 SDK (10.0.19041.0) Just-In-Time debugger C++ Profiling tools C++ CMake tools for Windows C++ ATL for latest v142 build tools Test Adapter for Boost.Test Test adapter for Google Test Live Share IntelliCode C++ AddressSanitizer Windows 10 SDK (10.0.18362.0) Can someone please help me on this? Like I said, if I should open a bug report, please let me know and I will. From larry.martell at gmail.com Thu Jun 9 13:47:42 2022 From: larry.martell at gmail.com (Larry Martell) Date: Thu, 9 Jun 2022 11:47:42 -0600 Subject: Function to Print a nicely formatted Dictionary or List? In-Reply-To: <6C7CEF1D-A810-44E0-8A23-6B34916C308D@looktowindward.com> References: <6C7CEF1D-A810-44E0-8A23-6B34916C308D@looktowindward.com> Message-ID: On Thu, Jun 9, 2022 at 11:44 AM Dave wrote: > > Hi, > > Before I write my own I wondering if anyone knows of a function that will print a nicely formatted dictionary? > > By nicely formatted I mean not all on one line! >>> import json >>> d = {'John': 'Cleese', 'Eric': "Idle", 'Micheal': 'Palin'} >>> print(json.dumps(d, indent=4)) { "John": "Cleese", "Eric": "Idle", "Micheal": "Palin" } From rosuav at gmail.com Thu Jun 9 13:52:02 2022 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 10 Jun 2022 03:52:02 +1000 Subject: Function to Print a nicely formatted Dictionary or List? In-Reply-To: <6C7CEF1D-A810-44E0-8A23-6B34916C308D@looktowindward.com> References: <6C7CEF1D-A810-44E0-8A23-6B34916C308D@looktowindward.com> Message-ID: On Fri, 10 Jun 2022 at 03:44, Dave wrote: > > Hi, > > Before I write my own I wondering if anyone knows of a function that will print a nicely formatted dictionary? > > By nicely formatted I mean not all on one line! > https://docs.python.org/3/library/pprint.html from pprint import pprint pprint(thing) ChrisA From python at mrabarnett.plus.com Thu Jun 9 13:53:24 2022 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 9 Jun 2022 18:53:24 +0100 Subject: Function to Print a nicely formatted Dictionary or List? In-Reply-To: <6C7CEF1D-A810-44E0-8A23-6B34916C308D@looktowindward.com> References: <6C7CEF1D-A810-44E0-8A23-6B34916C308D@looktowindward.com> Message-ID: <31f3fd63-72ed-1dc5-7f13-bacaeaaae384@mrabarnett.plus.com> On 2022-06-09 11:43, Dave wrote: > Hi, > > Before I write my own I wondering if anyone knows of a function that will print a nicely formatted dictionary? > > By nicely formatted I mean not all on one line! > It's called "pretty-printing". Have a look at the 'pprint' module. From avigross at verizon.net Thu Jun 9 14:06:05 2022 From: avigross at verizon.net (Avi Gross) Date: Thu, 9 Jun 2022 18:06:05 +0000 (UTC) Subject: Function to Print a nicely formatted Dictionary or List? In-Reply-To: <6C7CEF1D-A810-44E0-8A23-6B34916C308D@looktowindward.com> References: <6C7CEF1D-A810-44E0-8A23-6B34916C308D@looktowindward.com> Message-ID: <1736232332.928565.1654797965859@mail.yahoo.com> Dave, Despite your other programming knowledge, I suspect you think this is the forum where?people come to be tutored. Try here: https://mail.python.org/mailman/listinfo/tutor Yes, there are plenty of pretty printers available and you can build your own function fairly easily.?A module like pprint may have what you want in pprint.pprint()? but you can write a function for?yourself that takes a??dictionary and loops through items and prints them one per line and, if you feel like it,?also prints how many items there are and your own custom touches such as doing them alphabetically. Consider using a search engine before posting. Throw in a few words like?"python pretty print dictionary function" and refine that if it does not get you?immediate results. It is free and easy and does not waste time for so many others?who already know or don't care. And consider reading a few books perhaps designed to teach python to people with some?programming experience or taking a course on something like COURSERA as a part?of your learning process and not depending on volunteers so much. Much of what you are?asking is covered in fairly beginner and intermediate such books/courses. I think I am now going to ignore messages from you for a while. Signal to noise ratio ... -----Original Message----- From: Dave To: python-list at python.org Sent: Thu, Jun 9, 2022 6:43 am Subject: Function to Print a nicely formatted Dictionary or List? Hi, Before I write my own I wondering if anyone knows of a function that will print a nicely formatted dictionary? By nicely formatted I mean not all on one line! Cheers Dave -- https://mail.python.org/mailman/listinfo/python-list From mats at wichmann.us Thu Jun 9 15:01:16 2022 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 9 Jun 2022 13:01:16 -0600 Subject: Function to Print a nicely formatted Dictionary or List? In-Reply-To: References: <6C7CEF1D-A810-44E0-8A23-6B34916C308D@looktowindward.com> Message-ID: On 6/9/22 11:52, Chris Angelico wrote: > On Fri, 10 Jun 2022 at 03:44, Dave wrote: >> >> Hi, >> >> Before I write my own I wondering if anyone knows of a function that will print a nicely formatted dictionary? >> >> By nicely formatted I mean not all on one line! >> > > https://docs.python.org/3/library/pprint.html > > from pprint import pprint > pprint(thing) > > ChrisA I might add the note that there was a recent thread on the Discuss board about options for styling the pprint output (okay, it was me that started that one...) - you can choose indent and compact (compact is the not-all-on-one-line flag) but there might be some other choices missing. haven't gotten around to following up on that... https://discuss.python.org/t/pprint-styling-options/15947 From dave at looktowindward.com Thu Jun 9 15:35:24 2022 From: dave at looktowindward.com (Dave) Date: Thu, 9 Jun 2022 21:35:24 +0200 Subject: Function to Print a nicely formatted Dictionary or List? In-Reply-To: References: <6C7CEF1D-A810-44E0-8A23-6B34916C308D@looktowindward.com> Message-ID: Hi, I quite like the format that JSON gives - thanks a lot! Cheers Dave > On 9 Jun 2022, at 20:02, Stefan Ram wrote: > > Since nicety is in the eyes of the beholder, I would not > hesitate to write a custom function in this case. Python > has the standard modules "pprint" and "json". > > main.py > > import json > d ={ 1:2, 'alpha': 'beta' } > print( json.dumps( d, indent=4 )) > > output > > { > "1": 2, > "alpha": "beta" > } > From anthra.norell at bluewin.ch Thu Jun 9 16:13:08 2022 From: anthra.norell at bluewin.ch (Friedrich Rentsch) Date: Thu, 9 Jun 2022 22:13:08 +0200 Subject: Function to Print a nicely formatted Dictionary or List? In-Reply-To: <6C7CEF1D-A810-44E0-8A23-6B34916C308D@looktowindward.com> References: <6C7CEF1D-A810-44E0-8A23-6B34916C308D@looktowindward.com> Message-ID: If you want tables layed out in a framing grid, you might want to take a look at this: https://bitbucket.org/astanin/python-tabulate/pull-requests/31/allow-specifying-float-formats-per-column/diff Frederic On 6/9/22 12:43, Dave wrote: > Hi, > > Before I write my own I wondering if anyone knows of a function that will print a nicely formatted dictionary? > > By nicely formatted I mean not all on one line! > > Cheers > Dave > From michael.stemper at gmail.com Thu Jun 9 15:49:36 2022 From: michael.stemper at gmail.com (Michael F. Stemper) Date: Thu, 9 Jun 2022 14:49:36 -0500 Subject: Function to Print a nicely formatted Dictionary or List? In-Reply-To: References: <6C7CEF1D-A810-44E0-8A23-6B34916C308D@looktowindward.com> Message-ID: On 09/06/2022 12.52, Chris Angelico wrote: > On Fri, 10 Jun 2022 at 03:44, Dave wrote: >> Before I write my own I wondering if anyone knows of a function that will print a nicely formatted dictionary? >> >> By nicely formatted I mean not all on one line! >> > > https://docs.python.org/3/library/pprint.html > > from pprint import pprint > pprint(thing) >>> from pprint import pprint >>> d = {'two':2, 'three':5} >>> pprint(d) {'three': 5, 'two': 2} >>> This is all on one line. That might be acceptable to the OP, but it doesn't actually match what he said. -- Michael F. Stemper Outside of a dog, a book is man's best friend. Inside of a dog, it's too dark to read. From cs at cskk.id.au Thu Jun 9 19:12:39 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Fri, 10 Jun 2022 09:12:39 +1000 Subject: Function to Print a nicely formatted Dictionary or List? In-Reply-To: References: Message-ID: On 09Jun2022 21:35, Dave wrote: >I quite like the format that JSON gives - thanks a lot! Note that JSON output is JavaScript notation, not Python. The `pprint` module (which has `pprint` and `pformat` functions) outputs Python notation. If you're just writing for human eyes, JSON is fine, though you will want to keep in mind that JSON spells `None` as `null`. Cheers, Cameron Simpson From grant.b.edwards at gmail.com Thu Jun 9 20:51:59 2022 From: grant.b.edwards at gmail.com (Grant Edwards) Date: Thu, 09 Jun 2022 17:51:59 -0700 (PDT) Subject: Function to Print a nicely formatted Dictionary or List? References: <6C7CEF1D-A810-44E0-8A23-6B34916C308D@looktowindward.com> <1736232332.928565.1654797965859@mail.yahoo.com> <9ol4aht8fmqu0l1umncobn7dgcphadgaie@4ax.com> Message-ID: <62a295af.1c69fb81.d52c6.9c90@mx.google.com> On 2022-06-09, Dennis Lee Bieber wrote: > However, the Gmane list<>NNTP gateway server DOES make the tutor > list available to news readers (unfortunately, the comp.lang.python > <> list <> Gmane has been read-only since last fall (unless things > have changed recently) so I'm stuck with the spammy general > comp.lang.python news group. Here's how I fixed that problem: https://github.com/GrantEdwards/hybrid-inews I read this "group" using slrn pointed at gmane.comp.python.general, on the NNTP server news.gmain.io. When I post to this group from slrn, it gets e-mailed to the regular mailing list address. Other gmane "groups" get posts sent via NNTP. slrn is configured to post all articles via /usr/local/bin/inews (which is the python "inews" work-alike program above) when connected to news.gmane.io. How/why people follow mailing lists via actual e-mail is beyond my ken... -- Grant From drsalists at gmail.com Thu Jun 9 20:59:02 2022 From: drsalists at gmail.com (Dan Stromberg) Date: Thu, 9 Jun 2022 17:59:02 -0700 Subject: Function to Print a nicely formatted Dictionary or List? In-Reply-To: References: <6C7CEF1D-A810-44E0-8A23-6B34916C308D@looktowindward.com> Message-ID: On Thu, Jun 9, 2022 at 1:52 PM Michael F. Stemper wrote: > On 09/06/2022 12.52, Chris Angelico wrote: > > On Fri, 10 Jun 2022 at 03:44, Dave wrote: > > >> Before I write my own I wondering if anyone knows of a function that > will print a nicely formatted dictionary? > >> > >> By nicely formatted I mean not all on one line! > >> > > > > https://docs.python.org/3/library/pprint.html > > > > from pprint import pprint > > pprint(thing) > > >>> from pprint import pprint > >>> d = {'two':2, 'three':5} > >>> pprint(d) > {'three': 5, 'two': 2} > >>> > > This is all on one line. That might be acceptable to the OP, but it > doesn't actually match what he said. > For small outputs, pprint uses a single line. For larger outputs, it inserts newlines. It's intended to be human-readable more than machine-readable. From zdmrysf1 at gmail.com Fri Jun 10 04:51:46 2022 From: zdmrysf1 at gmail.com (=?utf-8?Q?Yusuf_=C3=96zdemir?=) Date: Fri, 10 Jun 2022 11:51:46 +0300 Subject: installing Message-ID: <2495EEA5-4F0A-4EE4-A09E-BCCB6D20F7C5@hxcore.ol> ? ? From grant.b.edwards at gmail.com Fri Jun 10 15:29:48 2022 From: grant.b.edwards at gmail.com (Grant Edwards) Date: Fri, 10 Jun 2022 12:29:48 -0700 (PDT) Subject: installing References: <2495EEA5-4F0A-4EE4-A09E-BCCB6D20F7C5@hxcore.ol> Message-ID: <62a39bac.1c69fb81.65a16.8312@mx.google.com> On 2022-06-10, Yusuf ?zdemir wrote: > ? Your question is a bit vague. -- Grant From mg.yuotube at gmail.com Sat Jun 11 04:41:22 2022 From: mg.yuotube at gmail.com (=?UTF-8?B?16HXkNeh15kg16HXkNeh?=) Date: Sat, 11 Jun 2022 11:41:22 +0300 Subject: Fwd: my vs code isnt working In-Reply-To: References: Message-ID: ---------- Forwarded message --------- ???: ???? ??? ?Date: ???, 11 ????? 2022 ?-11:36? Subject: my vs code isnt working To: what shoud i do to make that work i tried reinstalling and it still didnt work [image: image.png] From freethinker at mymail.com Sat Jun 11 06:37:37 2022 From: freethinker at mymail.com (Freethinker) Date: Sat, 11 Jun 2022 12:37:37 +0200 Subject: installing References: <2495EEA5-4F0A-4EE4-A09E-BCCB6D20F7C5@hxcore.ol> <62a39bac.1c69fb81.65a16.8312@mx.google.com> Message-ID: On 10.06.22 21:29, Grant Edwards wrote: > On 2022-06-10, Yusuf ?zdemir wrote: > >> ? > > Your question is a bit vague. > > -- > Grant > > > Hahahahaha, to say the least! From ayeshatassaduq422 at gmail.com Sat Jun 11 10:51:57 2022 From: ayeshatassaduq422 at gmail.com (Ayesha Tassaduq) Date: Sat, 11 Jun 2022 07:51:57 -0700 (PDT) Subject: Need help in blockchain coding. Message-ID: I am a beginner in python I want to transfer generated hash to a local database. I try it with socket programming but I fail. can anyone please help me ow I can do this? class Block: def __init__( self, previous_block_hash, transaction_list ): self.previous_block_hash = previous_block_hash self.transaction_list = transaction_list self.block_data = f"{' - '.join(transaction_list)} - {previous_block_hash}" self.block_hash = hashlib.sha256(self.block_data.encode()).hexdigest() class Blockchain: def __init__( self ): self.chain = [ ] self.generate_genesis_block() def generate_genesis_block( self ): self.chain.append(Block("0", [ 'Genesis Block' ])) def create_block_from_transaction( self, transaction_list ): previous_block_hash = self.last_block.block_hash self.chain.append(Block(previous_block_hash, transaction_list)) def display_chain( self ): for i in range(len(self.chain)): print(f"Hash {i + 1}: {self.chain [ i ].block_hash}\n") @property def last_block( self ): return self.chain [ -1 ] **t1 = Time_sensitive_df t2 = "abcdefghijklmnopqrstuvwxyz" t3 = normal_df myblockchain = Blockchain() myblockchain.create_block_from_transaction(t1) myblockchain.create_block_from_transaction(t2) myblockchain.create_block_from_transaction(t3) myblockchain.display_chain()** From ikorot01 at gmail.com Sat Jun 11 11:46:43 2022 From: ikorot01 at gmail.com (Igor Korot) Date: Sat, 11 Jun 2022 10:46:43 -0500 Subject: my vs code isnt working In-Reply-To: References: Message-ID: Hi, ?On Sat, Jun 11, 2022 at 10:05 AM ????? ????? wrote:? > > ---------- Forwarded message --------- > ???: ???? ??? > ?Date: ???, 11 ????? 2022 ?-11:36? > Subject: my vs code isnt working > To: > > > what shoud i do to make that work i tried reinstalling and it still > didnt work This list DOES NOT accept attachment. You will have to copy and paste the error you receive. Thank you. > > > > > [image: image.png] > -- > https://mail.python.org/mailman/listinfo/python-list From barry at barrys-emacs.org Sat Jun 11 13:45:48 2022 From: barry at barrys-emacs.org (Barry) Date: Sat, 11 Jun 2022 18:45:48 +0100 Subject: installing In-Reply-To: <2495EEA5-4F0A-4EE4-A09E-BCCB6D20F7C5@hxcore.ol> References: <2495EEA5-4F0A-4EE4-A09E-BCCB6D20F7C5@hxcore.ol> Message-ID: <7B03C326-DE35-4F81-9C54-16AAF6FEDC42@barrys-emacs.org> > On 10 Jun 2022, at 17:32, Yusuf ?zdemir wrote: > > ? ? My guess you attached an image, but this list does not allows attachements. Please copy and paste the text of the error for us to read. However you may find that this helps: https://docs.python.org/3/using/windows.html Barry > > > -- > https://mail.python.org/mailman/listinfo/python-list From nospam at please.ty Sat Jun 11 12:55:12 2022 From: nospam at please.ty (jak) Date: Sat, 11 Jun 2022 18:55:12 +0200 Subject: installing References: <2495EEA5-4F0A-4EE4-A09E-BCCB6D20F7C5@hxcore.ol> Message-ID: Il 10/06/2022 10:51, Yusuf ?zdemir ha scritto: > ? > > 0000000 ? 3f 63 077 0000001 From PythonList at DancesWithMice.info Sat Jun 11 17:29:02 2022 From: PythonList at DancesWithMice.info (dn) Date: Sun, 12 Jun 2022 09:29:02 +1200 Subject: Need help in blockchain coding. In-Reply-To: References: Message-ID: On 12/06/2022 02.51, Ayesha Tassaduq wrote: > I am a beginner in python I want to transfer generated hash to a local database. I try it with socket programming but I fail. can anyone please help me ow I can do this? Where is the database? Where is the socket? What are the (full) error messages? > class Block: > def __init__( self, previous_block_hash, transaction_list ): > self.previous_block_hash = previous_block_hash > self.transaction_list = transaction_list > > self.block_data = f"{' - '.join(transaction_list)} - {previous_block_hash}" > self.block_hash = hashlib.sha256(self.block_data.encode()).hexdigest() > > > class Blockchain: > def __init__( self ): > self.chain = [ ] > self.generate_genesis_block() > > def generate_genesis_block( self ): > self.chain.append(Block("0", [ 'Genesis Block' ])) > > def create_block_from_transaction( self, transaction_list ): > previous_block_hash = self.last_block.block_hash > self.chain.append(Block(previous_block_hash, transaction_list)) > > def display_chain( self ): > for i in range(len(self.chain)): > print(f"Hash {i + 1}: {self.chain [ i ].block_hash}\n") > > @property > def last_block( self ): > return self.chain [ -1 ] > > > **t1 = Time_sensitive_df > t2 = "abcdefghijklmnopqrstuvwxyz" > t3 = normal_df > myblockchain = Blockchain() > myblockchain.create_block_from_transaction(t1) > myblockchain.create_block_from_transaction(t2) > myblockchain.create_block_from_transaction(t3) > myblockchain.display_chain()** -- Regards, =dn From mats at wichmann.us Sat Jun 11 18:23:26 2022 From: mats at wichmann.us (Mats Wichmann) Date: Sat, 11 Jun 2022 16:23:26 -0600 Subject: Need help in blockchain coding. In-Reply-To: References: Message-ID: On 6/11/22 15:29, dn wrote: > On 12/06/2022 02.51, Ayesha Tassaduq wrote: >> I am a beginner in python I want to transfer generated hash to a local database. I try it with socket programming but I fail. can anyone please help me ow I can do this? > > Where is the database? > Where is the socket? > What are the (full) error messages? Indeed... what you've posted, with the exception that we don't see what these two _df values are: t1 = Time_sensitive_df ... t3 = normal_df looks basically workable for what it is. Guessing at your intent here - presumably you want your chain to be persistent and not be created from scratch each time you go to access it. You *could* use a database for this, and there are lots of Python technologies for talking to databases, but there's none of that in your code so we can't comment on it. For early experiments you could just use a text file. Then you need to code a way to load the existing chain from the file into your working copy, if the file exists, rather than instantiating a copy of Blockchain, which will always start over: def __init__( self ): self.chain = [ ] self.generate_genesis_block() since the chain itself is a list, perhaps you could dump that list to a json file, and reload it into self.chain if the json file is found to exist, instead of doing the initial-setup? Apologies if I have completely misunderstood what you are seeking... From drsalists at gmail.com Sat Jun 11 18:45:51 2022 From: drsalists at gmail.com (Dan Stromberg) Date: Sat, 11 Jun 2022 15:45:51 -0700 Subject: python.org wiki, not allowing me to log in? Message-ID: Hi folks. I have a little elbow grease available, so I thought I'd edit https://wiki.python.org/moin/BeginnersGuide/Download ...a little. However, signing in with my google creds by clicking the little Google button, gives me: OpenID discovery failure, not a valid OpenID. Does this mean I'm unauthorized to edit the page, or does it mean there's some sort of OpenID problem? Thanks. From mats at wichmann.us Sat Jun 11 19:03:52 2022 From: mats at wichmann.us (Mats Wichmann) Date: Sat, 11 Jun 2022 17:03:52 -0600 Subject: python.org wiki, not allowing me to log in? In-Reply-To: References: Message-ID: <8b28fe08-a973-dcd8-f3a0-ea12956a4a8f@wichmann.us> On 6/11/22 16:45, Dan Stromberg wrote: > Hi folks. > > I have a little elbow grease available, so I thought I'd edit > https://wiki.python.org/moin/BeginnersGuide/Download > > ...a little. > > However, signing in with my google creds by clicking the little Google > button, gives me: > OpenID discovery failure, not a valid OpenID. > > > Does this mean I'm unauthorized to edit the page, or does it mean there's > some sort of OpenID problem? "Yes" I don't know what the current state of the openid logins there is, for a while there were known problems. In any case, in order to edit you have to be added to the editors' list (it's a minimal anti-spam protection, you just tell the team you'd like to edit something particular and they add you). I admit I don't know how to do that with a login that isn't a wiki login. In any case, you want to write to pydotorg-www at python.org if you want to edit the wiki. From ayeshatassaduq422 at gmail.com Sun Jun 12 08:40:17 2022 From: ayeshatassaduq422 at gmail.com (Ayesha Tassaduq) Date: Sun, 12 Jun 2022 05:40:17 -0700 (PDT) Subject: python Store text file in mangodb Message-ID: Hi i am trying to store a text file into MongoDB but i got the error . "failing because no such method exists." % self.__name.split(".")[-1] TypeError: 'Collection' object is not callable. If you meant to call the 'insert' method on a 'Collection' object it is failing because no such method exists. Can anyone please tell what is wrong here i also tried to do it with insert_one and insert_many but when i try to do it with insert_many it shows error raise TypeError("documents must be a non-empty list") TypeError: documents must be a non-empty list from pymongo import MongoClient client = MongoClient() db = client.test_database # use a database called "test_database" collection = db.files # and inside that DB, a collection called "files" f = open('hashes.txt') # open a file # build a document to be inserted text_file_doc = {"file_name": "hashes.txt"} # insert the contents into the "file" collection collection.insert(text_file_doc) File names Hshes.txt has follown=ing data Hash 1: 39331a6a2ea1cf31a5014b2a7c9e8dfad82df0b0666e81ce04cf8173cc5aed Hash 2: 0e0ff63b7e5e872b9ea2f0d604b5d5afd6ba05665e52246fa321ead5b79c00ad Hash 3: 89241ce841704508be1d0b76c478c9575ec8a7ec8be46742fd5acb0dc72787f3 Hash 4: 80283cb08f91b415aae04bcada0da1ca3e37bbe971ae821116b4d29008970bdb From __peter__ at web.de Mon Jun 13 04:26:15 2022 From: __peter__ at web.de (Peter Otten) Date: Mon, 13 Jun 2022 10:26:15 +0200 Subject: python Store text file in mangodb In-Reply-To: References: Message-ID: <0e1facd9-fe70-c74b-08b7-0a46d5f415a9@web.de> On 12/06/2022 14:40, Ayesha Tassaduq wrote: > Hi i am trying to store a text file into MongoDB but i got the error . > "failing because no such method exists." % self.__name.split(".")[-1] > TypeError: 'Collection' object is not callable. If you meant to call the 'insert' method on a 'Collection' object it is failing because no such method exists. > > Can anyone please tell what is wrong here > i also tried to do it with insert_one and insert_many > but when i try to do it with insert_many it shows error > raise TypeError("documents must be a non-empty list") > TypeError: documents must be a non-empty list Read the error messages carefully: (1) "...If you meant to call the 'insert' method on a 'Collection' object it is failing because no such method exists." It may be a bit unfortunate that attributes spring into existence when you try to access them, but you want an "insert" method, and the error message warns you that no such method exists. You can run your script in idle and then type >>> collections.insert to see what it actually is. (2) "...documents must be a non-empty list" The insert_many() method expects a non-empty list of documents Example: collection.insert_many([text_file_doc]) You don't provide an error message for insert_one(), and indeed it should work where you tried insert(): collection.insert(text_file_doc) > from pymongo import MongoClient > client = MongoClient() > db = client.test_database # use a database called "test_database" > collection = db.files # and inside that DB, a collection called "files" > > f = open('hashes.txt') # open a file > > # build a document to be inserted > text_file_doc = {"file_name": "hashes.txt"} > # insert the contents into the "file" collection > collection.insert(text_file_doc) > > File names Hshes.txt has follown=ing data You are not yet at the point where you are using the file or its contents, so the file object and the file's contents could be omitted. Generally it is a good idea - to make your script as short as possible as long as it still produces the error. In the process you will often be able to fix the problem yourself. - always provide the tracebacks using cut-and-paste. That is often sufficient to diagnose and fix the problem. > Hash 1: 39331a6a2ea1cf31a5014b2a7c9e8dfad82df0b0666e81ce04cf8173cc5aed > > Hash 2: 0e0ff63b7e5e872b9ea2f0d604b5d5afd6ba05665e52246fa321ead5b79c00ad > > Hash 3: 89241ce841704508be1d0b76c478c9575ec8a7ec8be46742fd5acb0dc72787f3 > > Hash 4: 80283cb08f91b415aae04bcada0da1ca3e37bbe971ae821116b4d29008970bdb From h3ckphy at gmail.com Mon Jun 13 07:18:29 2022 From: h3ckphy at gmail.com (h3ck phy) Date: Mon, 13 Jun 2022 04:18:29 -0700 (PDT) Subject: Suggestion. Replace Any with * Message-ID: <245077da-e2bd-4805-a66b-f3fffe998e47n@googlegroups.com> It would be nice if we could write something like this data: dict[str, *] = {} instead of data: dict[str, Any] = {} In import statement asterisk means "all names" in a module. But in type closure it should mean "all types". From nospam at please.ty Mon Jun 13 09:49:49 2022 From: nospam at please.ty (jak) Date: Mon, 13 Jun 2022 15:49:49 +0200 Subject: fill out bulletins Message-ID: Hello everyone, I would like to write a tool to compile post office bulletins because here, unfortunately, they are still the most convenient way to interface the public administration. I don't want to create a UI to edit the bulletin, I will take the data from some file or database but I'd like to print or save the bulletin to the file with all the fields filled in. To accomplish this, I thought about creating a basic graphic (jpg?) file with the bulletin image, filling in the fields and then saving it in a new file. Can you direct me to a better way? And also, direct me to a library that allows me to accomplish this easily? Thank you in advance. From rosuav at gmail.com Mon Jun 13 13:06:40 2022 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 14 Jun 2022 03:06:40 +1000 Subject: Suggestion. Replace Any with * In-Reply-To: <245077da-e2bd-4805-a66b-f3fffe998e47n@googlegroups.com> References: <245077da-e2bd-4805-a66b-f3fffe998e47n@googlegroups.com> Message-ID: On Tue, 14 Jun 2022 at 01:59, h3ck phy wrote: > > It would be nice if we could write something like this > data: dict[str, *] = {} > instead of > data: dict[str, Any] = {} > > In import statement asterisk means "all names" in a module. > But in type closure it should mean "all types". Type hints are normal Python syntax. For this to be legal in a type hint, it would need to be legal in the rest of Python. What would it mean? some_object[other_object, *] ChrisA From michael.stemper at gmail.com Mon Jun 13 13:11:08 2022 From: michael.stemper at gmail.com (Michael F. Stemper) Date: Mon, 13 Jun 2022 12:11:08 -0500 Subject: fill out bulletins In-Reply-To: References: Message-ID: On 13/06/2022 08.49, jak wrote: > Hello everyone, > I would like to write a tool to compile post office bulletins because > here, unfortunately, they are still the most convenient way to interface > the public administration. I don't want to create a UI to edit the > bulletin, I will take the data from some file or database but I'd like > to print or save the bulletin to the file with all the fields filled in. > To accomplish this, I thought about creating a basic graphic (jpg?) file > with the bulletin image, Please don't create an image. Create something that preserves text as text, so that your recipients can (if they so desire) search on that text, or copy/paste from your bulletin. Somebody suggested TeX/LaTeX. Excellent idea. -- Michael F. Stemper A preposition is something you should never end a sentence with. From mats at wichmann.us Mon Jun 13 17:58:05 2022 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 13 Jun 2022 15:58:05 -0600 Subject: fill out bulletins In-Reply-To: References: Message-ID: <8fabdb92-1f55-727d-adb0-6dc465d89c90@wichmann.us> On 6/13/22 11:11, Michael F. Stemper wrote: > On 13/06/2022 08.49, jak wrote: >> Hello everyone, >> I would like to write a tool to compile post office bulletins because >> here, unfortunately, they are still the most convenient way to interface >> the public administration. I don't want to create a UI to edit the >> bulletin, I will take the data from some file or database but I'd like >> to print or save the bulletin to the file with all the fields filled in. >> To accomplish this, I thought about creating a basic graphic (jpg?) file >> with the bulletin image, > > Please don't create an image. Create something that preserves > text as text, so that your recipients can (if they so desire) > search on that text, or copy/paste from your bulletin. Absolutely agree. We're having a flood of people post code on Twitter and LinkedIn, which don't support code markup/markdown, so they post images. There are several tools that make really pretty pictures... and they're completely useless as you can't pick the code out of them. Hate this. > Somebody suggested TeX/LaTeX. Excellent idea. > Don't know what a "post office bulletin" is, but this sounds like a template problem ("all the fields filled in"). There are a lot of templating engines in the Python world from string handling in the standard library (https://docs.python.org/3/library/string.html#template-strings) to tools like JInja and Cheetah and a host of others. I think there are many of these listed on the wiki - maybe something here would suit your needs? https://wiki.python.org/moin/Templating From nospam at please.ty Mon Jun 13 18:16:12 2022 From: nospam at please.ty (jak) Date: Tue, 14 Jun 2022 00:16:12 +0200 Subject: fill out bulletins References: Message-ID: Il 13/06/2022 16:12, Stefan Ram ha scritto: > jak writes: >> Can you direct me to a better way? > > You could use a word processors with a mail-merge feature or > generate TeX/troff code for the bulletins. > > Of course, for Python, the library PIL/Pillow is available, > which can read or write JPG files and has a "text" method > to write text to images. > > I you want to print the bulletins, you could have a first > pass where the images are printed and then reinsert the same > sheets again to add the text in a second pass. > > I made a few attempts with libreoffice, unfortunately the bulletin is too complicated to get a good result. I also took a look at Tex/LaTeX as you advised me. Of these I just knew that they existed and their use but I didn't want to learn a new script just for a tool and in any case I think I would encounter the same problems I had with the word processor. I think I will use the PIL/Pillow librariesalso because I wanted to dynamically calculate the size of the characters so as not to go beyond the limits of the fields to be filled in in the image. Thanks for the tips. From nospam at please.ty Mon Jun 13 18:32:53 2022 From: nospam at please.ty (jak) Date: Tue, 14 Jun 2022 00:32:53 +0200 Subject: fill out bulletins References: Message-ID: Il 13/06/2022 19:11, Michael F. Stemper ha scritto: > On 13/06/2022 08.49, jak wrote: >> Hello everyone, >> I would like to write a tool to compile post office bulletins because >> here, unfortunately, they are still the most convenient way to interface >> the public administration. I don't want to create a UI to edit the >> bulletin, I will take the data from some file or database but I'd like >> to print or save the bulletin to the file with all the fields filled in. >> To accomplish this, I thought about creating a basic graphic (jpg?) file >> with the bulletin image, > > Please don't create an image. Create something that preserves > text as text, so that your recipients can (if they so desire) > search on that text, or copy/paste from your bulletin. > > Somebody suggested TeX/LaTeX. Excellent idea. > Part of the answer I gave to Stefan, moreover my goal is to get a piece of paper to give to the post office and not a document to share (it could contain personal data). From nospam at please.ty Mon Jun 13 18:41:07 2022 From: nospam at please.ty (jak) Date: Tue, 14 Jun 2022 00:41:07 +0200 Subject: fill out bulletins References: <8fabdb92-1f55-727d-adb0-6dc465d89c90@wichmann.us> Message-ID: Il 13/06/2022 23:58, Mats Wichmann ha scritto: > On 6/13/22 11:11, Michael F. Stemper wrote: >> On 13/06/2022 08.49, jak wrote: >>> Hello everyone, >>> I would like to write a tool to compile post office bulletins because >>> here, unfortunately, they are still the most convenient way to interface >>> the public administration. I don't want to create a UI to edit the >>> bulletin, I will take the data from some file or database but I'd like >>> to print or save the bulletin to the file with all the fields filled in. >>> To accomplish this, I thought about creating a basic graphic (jpg?) file >>> with the bulletin image, >> >> Please don't create an image. Create something that preserves >> text as text, so that your recipients can (if they so desire) >> search on that text, or copy/paste from your bulletin. > > Absolutely agree. We're having a flood of people post code on Twitter > and LinkedIn, which don't support code markup/markdown, so they post > images. There are several tools that make really pretty pictures... and > they're completely useless as you can't pick the code out of them. Hate > this. > >> Somebody suggested TeX/LaTeX. Excellent idea. >> > > Don't know what a "post office bulletin" is, but this sounds like a > template problem ("all the fields filled in"). There are a lot of > templating engines in the Python world from string handling in the > standard library > (https://docs.python.org/3/library/string.html#template-strings) to > tools like JInja and Cheetah and a host of others. I think there are > many of these listed on the wiki - maybe something here would suit your > needs? > > https://wiki.python.org/moin/Templating > If you are interested in seeing what I called "post office bulletin" (English is not my language and I don't know the name, sorry), you can find a sample pdf (fillable) but it works badly here: https://www.guardiacostiera.gov.it/venezia/Documents/Bollettino%20MOD.%20TD123.pdf From python at mrabarnett.plus.com Mon Jun 13 19:34:18 2022 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 14 Jun 2022 00:34:18 +0100 Subject: fill out bulletins In-Reply-To: References: <8fabdb92-1f55-727d-adb0-6dc465d89c90@wichmann.us> Message-ID: <72a6eec9-d7c9-7f7b-4a5c-eca5a509d847@mrabarnett.plus.com> On 2022-06-13 23:41, jak wrote: [snip] > > If you are interested in seeing what I called "post office bulletin" > (English is not my language and I don't know the name, sorry), you can > find a sample pdf (fillable) but it works badly here: > > https://www.guardiacostiera.gov.it/venezia/Documents/Bollettino%20MOD.%20TD123.pdf Probably best to just call it a "form". From greg.ewing at canterbury.ac.nz Mon Jun 13 19:14:39 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Tue, 14 Jun 2022 11:14:39 +1200 Subject: fill out bulletins In-Reply-To: References: Message-ID: Another possibility is to use reportlab to generate a pdf. -- Greg From PythonList at DancesWithMice.info Mon Jun 13 19:46:50 2022 From: PythonList at DancesWithMice.info (dn) Date: Tue, 14 Jun 2022 11:46:50 +1200 Subject: fill out bulletins In-Reply-To: <72a6eec9-d7c9-7f7b-4a5c-eca5a509d847@mrabarnett.plus.com> References: <8fabdb92-1f55-727d-adb0-6dc465d89c90@wichmann.us> <72a6eec9-d7c9-7f7b-4a5c-eca5a509d847@mrabarnett.plus.com> Message-ID: <396f81df-0f63-6250-8d3f-83025966d556@DancesWithMice.info> On 14/06/2022 11.34, MRAB wrote: > On 2022-06-13 23:41, jak wrote: > [snip] >> >> If you are interested in seeing what I called "post office bulletin" >> (English is not my language and I don't know the name, sorry), you can >> find a sample pdf (fillable) but it works badly here: >> >> https://www.guardiacostiera.gov.it/venezia/Documents/Bollettino%20MOD.%20TD123.pdf >> > > Probably best to just call it a "form". pygame might offer a simple way to add text to a 'form' at appropriate x,y co-ordinates. -- Regards, =dn From pkpearson at nowhere.invalid Tue Jun 14 09:28:01 2022 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 14 Jun 2022 13:28:01 GMT Subject: fill out bulletins References: <8fabdb92-1f55-727d-adb0-6dc465d89c90@wichmann.us> Message-ID: On Tue, 14 Jun 2022 00:41:07 +0200, jak wrote: [snip] > > If you are interested in seeing what I called "post office bulletin" > (English is not my language and I don't know the name, sorry), you can > find a sample pdf (fillable) but it works badly here: > > https://www.guardiacostiera.gov.it/venezia/Documents/Bollettino%20MOD.%20TD123.pdf Are these "post office bulletins" always PDFs? -- To email me, substitute nowhere->runbox, invalid->com. From nospam at please.ty Tue Jun 14 09:57:11 2022 From: nospam at please.ty (jak) Date: Tue, 14 Jun 2022 15:57:11 +0200 Subject: fill out bulletins References: <8fabdb92-1f55-727d-adb0-6dc465d89c90@wichmann.us> Message-ID: Il 14/06/2022 15:28, Peter Pearson ha scritto: > On Tue, 14 Jun 2022 00:41:07 +0200, jak wrote: > [snip] >> >> If you are interested in seeing what I called "post office bulletin" >> (English is not my language and I don't know the name, sorry), you can >> find a sample pdf (fillable) but it works badly here: >> >> https://www.guardiacostiera.gov.it/venezia/Documents/Bollettino%20MOD.%20TD123.pdf > > > Are these "post office bulletins" always PDFs? > > Oh no, sadly no. these forms can be found almost exclusively in post offices in paper form and you would need to fill them in by hand (only with black or blue ballpoint pen). I struggled to find a pdf version of them on the web that wasn't pre-compiled. I also tried to get a graphic file by scanning (or photo) but I couldn't get a decent image, probably because I don't have precise enough tools. Ask them for a copy of the document from which they print them, I don't try because I think it's wasted breath. From wlfraed at ix.netcom.com Tue Jun 14 11:15:47 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 14 Jun 2022 11:15:47 -0400 Subject: fill out bulletins References: <8fabdb92-1f55-727d-adb0-6dc465d89c90@wichmann.us> Message-ID: On Tue, 14 Jun 2022 00:41:07 +0200, jak declaimed the following: >If you are interested in seeing what I called "post office bulletin" >(English is not my language and I don't know the name, sorry), you can >find a sample pdf (fillable) but it works badly here: > >https://www.guardiacostiera.gov.it/venezia/Documents/Bollettino%20MOD.%20TD123.pdf While I can't read Italian... But that looks suspiciously like what I'd call a Return Receipt (one side to be filled with "your" address for returning, and the other to be filled/signed by the person accepting the article) https://faq.usps.com/s/article/Return-Receipt-The-Basics#Green_Card Or an archaic Telegram form (NOT the cloud app) -- or even an ARRL Message form https://www.ncarrl.org/nets/mes_form.html In either case -- they should be manageable spending some time laying out the "form" in any decent word processor, and developing the suitable mail-merge definitions and database. Or even a decent report-writer with a relational database. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From avigross at verizon.net Tue Jun 14 13:10:25 2022 From: avigross at verizon.net (Avi Gross) Date: Tue, 14 Jun 2022 17:10:25 +0000 (UTC) Subject: fill out bulletins In-Reply-To: References: <8fabdb92-1f55-727d-adb0-6dc465d89c90@wichmann.us> Message-ID: <781454240.2077072.1655226625962@mail.yahoo.com> I wish this discussion was simplified. It sounds to me like what is wanted is a way to PRINT a filled-out form using some dynamic?text that fits over designated slots in the data. It is not that different from many other tasks?where you overlay some graphics with text. You need a decent version of the graphics with enough pixels and the right size using?something as simple as a scanner at higher resolution OR getting someone to give?you a template in a form you can use. Using a ruler or other tools, map out the rectangles you are going to be printing text in. Use your own algorithms to take each snippet of text you want to print and do wrapping?and resizing of the font or whatever it takes to make it fit. Finally, overlay the text snippets on the image. Then PRINT it on a decent printer. >From what I hear, you seem not to need the original text anymore, but nothing stops?your program with storing bits you will use again later and reusing them, or having a?log of the original text used and so on. Plan B might be to COPY your image on a ream of paper and then replace the paper?in the printer so the next print writes on top of it. Create a template with just text that?when printed will happen to write over the same spots. As to what tools you can use, there are many to choose from. You asked on a Python?list so you may want some of the Python Graphics utilities. In R, I might use ggplot which lets?me set a background layer then draw objects above it at various offsets, as one of many things.? I know many businesses do things like this all the time such as having printers loaded with checks?to be printed, or inserting an envelope into a slot on the printer to have the name and address printedin the right places. -----Original Message----- From: Peter Pearson To: python-list at python.org Sent: Tue, Jun 14, 2022 9:28 am Subject: Re: fill out bulletins On Tue, 14 Jun 2022 00:41:07 +0200, jak wrote: [snip] > > If you are interested in seeing what I called "post office bulletin" > (English is not my language and I don't know the name, sorry), you can > find a sample pdf (fillable) but it works badly here: > > https://www.guardiacostiera.gov.it/venezia/Documents/Bollettino%20MOD.%20TD123.pdf Are these "post office bulletins" always PDFs? -- To email me, substitute nowhere->runbox, invalid->com. -- https://mail.python.org/mailman/listinfo/python-list From travisgriggs at gmail.com Tue Jun 14 14:05:52 2022 From: travisgriggs at gmail.com (Travis Griggs) Date: Tue, 14 Jun 2022 11:05:52 -0700 Subject: mapLast, mapFirst, and just general iterator questions Message-ID: I want to be able to apply different transformations to the first and last elements of an arbitrary sized finite iterator in python3. It's a custom iterator so does not have _reversed_. If the first and last elements are the same (e.g. size 1), it should apply both transforms to the same element. I'm doing this because I have an iterator of time span tuples, and I want to clamp the first and last elements, but know any/all of the middle values are inherently in range. A silly example might be a process that given an iterator of strings, chops the the outer characters off of the value, and uppercases the final value. For example: def iterEmpty(): return iter([]) def iter1(): yield "howdy" def iter2(): yield "howdy" yield "byebye" def iterMany(): yield "howdy" yield "hope" yield "your" yield "day" yield "is" yield "swell" yield "byebye" def mapFirst(stream, transform): try: first = next(stream) except StopIteration: return yield transform(first) yield from stream def mapLast(stream, transform): try: previous = next(stream) except StopIteration: return for item in stream: yield previous previous = item yield transform(previous) def main(): for each in (iterEmpty, iter1, iter2, iterMany): baseIterator = each() chopFirst = mapFirst(baseIterator, lambda x: x[1:-1]) andCapLast = mapLast(chopFirst, lambda x: x.upper()) print(repr(" ".join(andCapLast))) This outputs: '' 'OWD' 'owd BYEBYE' 'owd hope your day is swell BYEBYE' Is this idiomatic? Especially my implementations of mapFirst and mapList there in the middle? Or is there some way to pull this off that is more elegant? I've been doing more with iterators and stacking them (probably because I've been playing with Elixir elsewhere), I am generally curious what the performance tradeoffs of heavy use of iterators and yield functions in python is. I know the argument for avoiding big list copies when moving between stages. Is it one of those things where there's also some overhead with them, where for small stuff, you'd just be better list-ifying the first iterator and then working with lists (where, for example, I could do the first/last clamp operation with just indexing operations). From rosuav at gmail.com Tue Jun 14 14:47:31 2022 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 15 Jun 2022 04:47:31 +1000 Subject: mapLast, mapFirst, and just general iterator questions In-Reply-To: References: Message-ID: On Wed, 15 Jun 2022 at 04:07, Travis Griggs wrote: > def mapFirst(stream, transform): > try: > first = next(stream) > except StopIteration: > return > yield transform(first) > yield from stream Small suggestion: Begin with this: stream = iter(stream) That way, you don't need to worry about whether you're given an iterator or some other iterable (for instance, you can't call next() on a list, but it would make good sense to be able to use your function on a list). (BTW, Python's convention would be to call this "map_first" rather than "mapFirst". But that's up to you.) > def mapLast(stream, transform): > try: > previous = next(stream) > except StopIteration: > return > for item in stream: > yield previous > previous = item > yield transform(previous) Hmm. This might be a place to use multiple assignment, but what you have is probably fine too. > def main(): > for each in (iterEmpty, iter1, iter2, iterMany): > baseIterator = each() > chopFirst = mapFirst(baseIterator, lambda x: x[1:-1]) > andCapLast = mapLast(chopFirst, lambda x: x.upper()) > print(repr(" ".join(andCapLast))) Don't bother with a main() function unless you actually need to be able to use it as a function. Most of the time, it's simplest to just have the code you want, right there in the file. :) Python isn't C or Java, and code doesn't have to get wrapped up in functions in order to exist. > Is this idiomatic? Especially my implementations of mapFirst and mapList there in the middle? Or is there some way to pull this off that is more elegant? > Broadly so. Even with the comments I've made above, I wouldn't say there's anything particularly *wrong* with your code. There are, of course, many ways to do things, and what's "best" depends on what your code is doing, whether it makes sense in context. > I've been doing more with iterators and stacking them (probably because I've been playing with Elixir elsewhere), I am generally curious what the performance tradeoffs of heavy use of iterators and yield functions in python is. I know the argument for avoiding big list copies when moving between stages. Is it one of those things where there's also some overhead with them, where for small stuff, you'd just be better list-ifying the first iterator and then working with lists (where, for example, I could do the first/last clamp operation with just indexing operations). > That's mostly right, but more importantly: Don't worry about performance. Worry instead about whether the code is expressing your intent. If that means using a list instead of an iterator, go for it! If that means using an iterator instead of a list, go for it! Python won't judge you. :) But if you really want to know which one is faster, figure out a reasonable benchmark, and then start playing around with the timeit module. Just remember, it's very very easy to spend hours trying to make the benchmark numbers look better, only to discover that it has negligible impact on your code's actual performance - or, in some cases, it's *worse* than before (because the benchmark wasn't truly representative). So if you want to spend some enjoyable time exploring different options, go for it! And we'd be happy to help out. Just don't force yourself to write bad code "because it's faster". ChrisA From roel at roelschroeven.net Tue Jun 14 15:44:26 2022 From: roel at roelschroeven.net (Roel Schroeven) Date: Tue, 14 Jun 2022 21:44:26 +0200 Subject: mapLast, mapFirst, and just general iterator questions In-Reply-To: References: Message-ID: Chris Angelico schreef op 14/06/2022 om 20:47: > > def main(): > > for each in (iterEmpty, iter1, iter2, iterMany): > > baseIterator = each() > > chopFirst = mapFirst(baseIterator, lambda x: x[1:-1]) > > andCapLast = mapLast(chopFirst, lambda x: x.upper()) > > print(repr(" ".join(andCapLast))) > > Don't bother with a main() function unless you actually need to be > able to use it as a function. Most of the time, it's simplest to just > have the code you want, right there in the file. :) Python isn't C or > Java, and code doesn't have to get wrapped up in functions in order to > exist. Not (necessarily) a main function, but these days the general recommendation seems to be to use the "if __name__ == '__main__':" construct, so that the file can be used as a module as well as as a script. Even for short simple things that can be helpful when doing things like running tests or extracting docstrings. -- "This planet has - or rather had - a problem, which was this: most of the people living on it were unhappy for pretty much of the time. Many solutions were suggested for this problem, but most of these were largely concerned with the movement of small green pieces of paper, which was odd because on the whole it wasn't the small green pieces of paper that were unhappy." -- Douglas Adams From rosuav at gmail.com Tue Jun 14 15:49:26 2022 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 15 Jun 2022 05:49:26 +1000 Subject: mapLast, mapFirst, and just general iterator questions In-Reply-To: References: Message-ID: On Wed, 15 Jun 2022 at 05:45, Roel Schroeven wrote: > > Chris Angelico schreef op 14/06/2022 om 20:47: > > > def main(): > > > for each in (iterEmpty, iter1, iter2, iterMany): > > > baseIterator = each() > > > chopFirst = mapFirst(baseIterator, lambda x: x[1:-1]) > > > andCapLast = mapLast(chopFirst, lambda x: x.upper()) > > > print(repr(" ".join(andCapLast))) > > > > Don't bother with a main() function unless you actually need to be > > able to use it as a function. Most of the time, it's simplest to just > > have the code you want, right there in the file. :) Python isn't C or > > Java, and code doesn't have to get wrapped up in functions in order to > > exist. > Not (necessarily) a main function, but these days the general > recommendation seems to be to use the "if __name__ == '__main__':" > construct, so that the file can be used as a module as well as as a > script. Even for short simple things that can be helpful when doing > things like running tests or extracting docstrings. If it does need to be used as a module as well as a script, sure. But (a) not everything does, and (b) even then, you don't need a main() function; what you need is the name-is-main check. The main function is only necessary when you need to be able to invoke your main entry point externally, AND this main entry point doesn't have a better name. That's fairly rare in my experience. My recommendation is to write the code you need, and only add boilerplate when you actually need it. Don't just start every script with an if-name-is-main block at the bottom just for the sake of doing it. ChrisA From greg.ewing at canterbury.ac.nz Tue Jun 14 19:45:32 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Wed, 15 Jun 2022 11:45:32 +1200 Subject: mapLast, mapFirst, and just general iterator questions In-Reply-To: References: Message-ID: On 15/06/22 7:49 am, Chris Angelico wrote: > If it does need to be used as a module as well as a script, sure. But > (a) not everything does, and (b) even then, you don't need a main() I think this is very much a matter of taste. Personally I find it tidier to put the top level code in a function, because it ties it together visually and lets me have locals that are properly local. If the file is only ever used as a script, I just put an unconditional call to the main function at the bottom. -- Greg From cs at cskk.id.au Tue Jun 14 22:05:37 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Wed, 15 Jun 2022 12:05:37 +1000 Subject: mapLast, mapFirst, and just general iterator questions In-Reply-To: References: Message-ID: On 15Jun2022 05:49, Chris Angelico wrote: >On Wed, 15 Jun 2022 at 05:45, Roel Schroeven wrote: >> Not (necessarily) a main function, but these days the general >> recommendation seems to be to use the "if __name__ == '__main__':" >> construct, so that the file can be used as a module as well as as a >> script. Even for short simple things that can be helpful when doing >> things like running tests or extracting docstrings. > >If it does need to be used as a module as well as a script, sure. But >(a) not everything does, and (b) even then, you don't need a main() >function; what you need is the name-is-main check. The main function >is only necessary when you need to be able to invoke your main entry >point externally, AND this main entry point doesn't have a better >name. That's fairly rare in my experience. While I will lazily not-use-a-function in dev, using a function has the benefit of avoiding accidental global variable use, because assignments within the function will always make local variables. That is a big plus for me all on its own. I've used this practice as far back as Pascal, which also let you write outside-a-function code, and consider it a great avoider of a common potential bug situation. Cheers, Cameron Simpson From z.szenderak at hotmail.com Wed Jun 15 03:13:20 2022 From: z.szenderak at hotmail.com (Zoltan Szenderak) Date: Wed, 15 Jun 2022 07:13:20 +0000 Subject: ModuleNotFoundError In-Reply-To: References: Message-ID: Only on my Windows 10, on my Windows 11 works perfectly. I uninstalled and reinstalled python, it did not help, I tried everything I found online, Stackoverflow, python.org, did not help. Not just this module, others too. They are installed where they are supposed to be and they produce the name not found error. Some modules work. The Path is set in the System Environment Variables list. (env) C:\Users\zszen>req3.py Traceback (most recent call last): File "C:\Users\zszen\env\Scripts\req3.py", line 2, in import requests_html ModuleNotFoundError: No module named 'requests_html' (env) C:\Users\zszen>pip3 install requests_html Requirement already satisfied: requests_html in c:\users\zszen\env\lib\site-packages (0.10.0) Requirement already satisfied: requests in c:\users\zszen\env\lib\site-packages (from requests_html) (2.27.1) Requirement already satisfied: bs4 in c:\users\zszen\env\lib\site-packages (from requests_html) (0.0.1) Requirement already satisfied: fake-useragent in c:\users\zszen\env\lib\site-packages (from requests_html) (0.1.11) Requirement already satisfied: pyppeteer>=0.0.14 in c:\users\zszen\env\lib\site-packages (from requests_html) (1.0.2) Requirement already satisfied: pyquery in c:\users\zszen\env\lib\site-packages (from requests_html) (1.4.3) Requirement already satisfied: parse in c:\users\zszen\env\lib\site-packages (from requests_html) (1.19.0) Requirement already satisfied: w3lib in c:\users\zszen\env\lib\site-packages (from requests_html) (1.22.0) Requirement already satisfied: appdirs<2.0.0,>=1.4.3 in c:\users\zszen\env\lib\site-packages (from pyppeteer>=0.0.14->requests_html) (1.4.4) Requirement already satisfied: websockets<11.0,>=10.0 in c:\users\zszen\env\lib\site-packages (from pyppeteer>=0.0.14->requests_html) (10.3) Requirement already satisfied: urllib3<2.0.0,>=1.25.8 in c:\users\zszen\env\lib\site-packages (from pyppeteer>=0.0.14->requests_html) (1.26.9) Requirement already satisfied: tqdm<5.0.0,>=4.42.1 in c:\users\zszen\env\lib\site-packages (from pyppeteer>=0.0.14->requests_html) (4.64.0) Requirement already satisfied: importlib-metadata>=1.4 in c:\users\zszen\env\lib\site-packages (from pyppeteer>=0.0.14->requests_html) (4.11.4) Requirement already satisfied: pyee<9.0.0,>=8.1.0 in c:\users\zszen\env\lib\site-packages (from pyppeteer>=0.0.14->requests_html) (8.2.2) Requirement already satisfied: certifi>=2021 in c:\users\zszen\env\lib\site-packages (from pyppeteer>=0.0.14->requests_html) (2022.5.18.1) Requirement already satisfied: beautifulsoup4 in c:\users\zszen\env\lib\site-packages (from bs4->requests_html) (4.11.1) Requirement already satisfied: cssselect>0.7.9 in c:\users\zszen\env\lib\site-packages (from pyquery->requests_html) (1.1.0) Requirement already satisfied: lxml>=2.1 in c:\users\zszen\env\lib\site-packages (from pyquery->requests_html) (4.9.0) Requirement already satisfied: charset-normalizer~=2.0.0 in c:\users\zszen\env\lib\site-packages (from requests->requests_html) (2.0.12) Requirement already satisfied: idna<4,>=2.5 in c:\users\zszen\env\lib\site-packages (from requests->requests_html) (3.3) Requirement already satisfied: six>=1.4.1 in c:\users\zszen\env\lib\site-packages (from w3lib->requests_html) (1.16.0) Requirement already satisfied: zipp>=0.5 in c:\users\zszen\env\lib\site-packages (from importlib-metadata>=1.4->pyppeteer>=0.0.14->requests_html) (3.8.0) Requirement already satisfied: colorama in c:\users\zszen\env\lib\site-packages (from tqdm<5.0.0,>=4.42.1->pyppeteer>=0.0.14->requests_html) (0.4.4) Requirement already satisfied: soupsieve>1.2 in c:\users\zszen\env\lib\site-packages (from beautifulsoup4->bs4->requests_html) (2.3.2.post1) (env) C:\Users\zszen> Kind regards, Zoltan From wlfraed at ix.netcom.com Wed Jun 15 11:25:58 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Wed, 15 Jun 2022 11:25:58 -0400 Subject: fill out bulletins References: <8fabdb92-1f55-727d-adb0-6dc465d89c90@wichmann.us> Message-ID: On Tue, 14 Jun 2022 11:15:47 -0400, Dennis Lee Bieber declaimed the following: >On Tue, 14 Jun 2022 00:41:07 +0200, jak declaimed the >following: > >> >>https://www.guardiacostiera.gov.it/venezia/Documents/Bollettino%20MOD.%20TD123.pdf > > In either case -- they should be manageable spending some time laying >out the "form" in any decent word processor, and developing the suitable >mail-merge definitions and database. Or even a decent report-writer with a >relational database. Note: if it is the "individual/one-letter-per-box" areas that are making it seem so difficult for mail-merge... Don't do it that way! Use one mail-merge field for the entire data item, use a monospace (fixed width) font (Courier, Lucida Console, etc.), and adjust the character spacing using the word-processor formatting operation (in Word this is under the Font pop-up dialog, "advanced" tab). Set it to "expanded" spacing and adjust the amount of expansion until your chosen font is spaced properly to appear as one character per form box. https://support.microsoft.com/en-us/office/change-the-spaces-between-text-e9b96011-1c42-45c0-ad8f-e8a6e4a33462 (On LibreOffice Writer, it is under Format/Character..., Position tab on the dialog. At least, it is on the version I have on Debian in VirtualBox.) -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From rosuav at gmail.com Wed Jun 15 15:14:49 2022 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 16 Jun 2022 05:14:49 +1000 Subject: ModuleNotFoundError In-Reply-To: References: Message-ID: On Thu, 16 Jun 2022 at 05:00, Zoltan Szenderak wrote: > > > > Only on my Windows 10, on my Windows 11 works perfectly. I uninstalled and reinstalled python, it did not help, I tried everything I found online, Stackoverflow, python.org, did not help. Not just this module, others too. They are installed where they are supposed to be and they produce the name not found error. Some modules work. The Path is set in the System Environment Variables list. > > (env) C:\Users\zszen>req3.py > Traceback (most recent call last): > File "C:\Users\zszen\env\Scripts\req3.py", line 2, in > import requests_html > ModuleNotFoundError: No module named 'requests_html' > > (env) C:\Users\zszen>pip3 install requests_html > Requirement already satisfied: requests_html in c:\users\zszen\env\lib\site-packages (0.10.0) > Requirement already satisfied: requests in c:\users\zszen\env\lib\site-packages (from requests_html) (2.27.1) > Requirement already satisfied: bs4 in c:\users\zszen\env\lib\site-packages (from requests_html) (0.0.1) > Requirement already satisfied: fake-useragent in c:\users\zszen\env\lib\site-packages (from requests_html) (0.1.11) > Requirement already satisfied: pyppeteer>=0.0.14 in c:\users\zszen\env\lib\site-packages (from requests_html) (1.0.2) > Requirement already satisfied: pyquery in c:\users\zszen\env\lib\site-packages (from requests_html) (1.4.3) > Requirement already satisfied: parse in c:\users\zszen\env\lib\site-packages (from requests_html) (1.19.0) > Requirement already satisfied: w3lib in c:\users\zszen\env\lib\site-packages (from requests_html) (1.22.0) > Requirement already satisfied: appdirs<2.0.0,>=1.4.3 in c:\users\zszen\env\lib\site-packages (from pyppeteer>=0.0.14->requests_html) (1.4.4) > Requirement already satisfied: websockets<11.0,>=10.0 in c:\users\zszen\env\lib\site-packages (from pyppeteer>=0.0.14->requests_html) (10.3) > Requirement already satisfied: urllib3<2.0.0,>=1.25.8 in c:\users\zszen\env\lib\site-packages (from pyppeteer>=0.0.14->requests_html) (1.26.9) > Requirement already satisfied: tqdm<5.0.0,>=4.42.1 in c:\users\zszen\env\lib\site-packages (from pyppeteer>=0.0.14->requests_html) (4.64.0) > Requirement already satisfied: importlib-metadata>=1.4 in c:\users\zszen\env\lib\site-packages (from pyppeteer>=0.0.14->requests_html) (4.11.4) > Requirement already satisfied: pyee<9.0.0,>=8.1.0 in c:\users\zszen\env\lib\site-packages (from pyppeteer>=0.0.14->requests_html) (8.2.2) > Requirement already satisfied: certifi>=2021 in c:\users\zszen\env\lib\site-packages (from pyppeteer>=0.0.14->requests_html) (2022.5.18.1) > Requirement already satisfied: beautifulsoup4 in c:\users\zszen\env\lib\site-packages (from bs4->requests_html) (4.11.1) > Requirement already satisfied: cssselect>0.7.9 in c:\users\zszen\env\lib\site-packages (from pyquery->requests_html) (1.1.0) > Requirement already satisfied: lxml>=2.1 in c:\users\zszen\env\lib\site-packages (from pyquery->requests_html) (4.9.0) > Requirement already satisfied: charset-normalizer~=2.0.0 in c:\users\zszen\env\lib\site-packages (from requests->requests_html) (2.0.12) > Requirement already satisfied: idna<4,>=2.5 in c:\users\zszen\env\lib\site-packages (from requests->requests_html) (3.3) > Requirement already satisfied: six>=1.4.1 in c:\users\zszen\env\lib\site-packages (from w3lib->requests_html) (1.16.0) > Requirement already satisfied: zipp>=0.5 in c:\users\zszen\env\lib\site-packages (from importlib-metadata>=1.4->pyppeteer>=0.0.14->requests_html) (3.8.0) > Requirement already satisfied: colorama in c:\users\zszen\env\lib\site-packages (from tqdm<5.0.0,>=4.42.1->pyppeteer>=0.0.14->requests_html) (0.4.4) > Requirement already satisfied: soupsieve>1.2 in c:\users\zszen\env\lib\site-packages (from beautifulsoup4->bs4->requests_html) (2.3.2.post1) > > (env) C:\Users\zszen> > What does "pip3 --version" tell you, and what happens if you print out sys.version at the top of your script? Also possibly sys.executable, in case your script isn't running from inside the venv that it looks like it ought to be working in. ChrisA From PythonList at DancesWithMice.info Fri Jun 17 00:57:54 2022 From: PythonList at DancesWithMice.info (dn) Date: Fri, 17 Jun 2022 16:57:54 +1200 Subject: Call for speakers/guides (virtual Python User Group meetings) Message-ID: TLDR; our PUG seeks (speakers or guides). Message contains a range of Python-related topics requested by attendees. To follow-up requests from meeting-attendees, herewith a call for speakers/guides. Would you show us what you've learned, please? - state transitions/finite state machines (pref not all 'math' eg IoT or the usual example of a vending machine) - working with the web (several, separate, topics): - web-scraping - building and displaying a web-page, eg flask - async versions of the above, eg fastapi - accessing APIs, building APIs - PyIodide - authentication and identity/membership - working with databases - SQL and RDBMS - NoSQL, eg MongoDB - graph databases - coding with inversion of control for flexible choice of I/O - Python programming - Python idioms - basic coding techniques and tactics - developing from problem to solution - practical follow-up to our series on Software Craftsmanship/SOLID eg implementing SRP, when to split into functions, classes, modules We'll be interested to include any other ideas. What excites you? Perhaps something that has come through the PEP process and was added to Python 3.n recently? Other suggested topics at https://cloud.nzoss.nz/s/6WbkbBzydcqsNaE The Auckland Python Users' Group holds two meetings a month on Wednesday evenings (NZST). A "Coding Evening" which suits a 'live demo' or 'code along with me' type of hands-on approach. Also a "Presentation Evening" which often consists of talk-and-slides. We operate virtually (using BigBlueButton) - so location is irrelevant, but time-zone differences may be! Attendees range from 'Apprentices' to 'Python Masters', all keen to advance in Python. Atmosphere is helpful, humorous, and constructive, ie thoroughly Kiwi! (more information is available to interested-parties) What's in it for you? Apart from a solid addition to your CV, and a burnished record in the Python-community? Any and all help will be given in putting a talk/tutorial together, and/or making the best use of the BBB web-conferencing tool. Please follow-up with Pete and myself - offline from this list. -- Regards =dn, Facilitator and General Factotum to: Pete Mayes, Benevolent Dictator/Leader for life, of: NZPUG - Auckland Branch From z.szenderak at hotmail.com Fri Jun 17 04:03:28 2022 From: z.szenderak at hotmail.com (Zoltan Szenderak) Date: Fri, 17 Jun 2022 08:03:28 +0000 Subject: ModuleNotFoundError Message-ID: Re: https://mail.python.org/pipermail/python-list/2022-June/906698.html How do I reply to: Chris Angelico rosuav at gmail.com so it is listed on the Python list? Chris Angelico rosuav at gmail.com Wed Jun 15 15:14:49 EDT 2022 What does "pip3 --version" tell you, and what happens if you print out sys.version at the top of your script? Also possibly sys.executable, in case your script isn't running from inside the venv that it looks like it ought to be working in. My reply: Pip version pip 22.1.2 from C:\Users\zszen\ENV\lib\site-packages\pip (python 3.10) print(sys.version_info) and executable: Unable to initialize device PRN Kind regards, Zoltan From 2QdxY4RzWzUUiLuE at potatochowder.com Fri Jun 17 06:39:30 2022 From: 2QdxY4RzWzUUiLuE at potatochowder.com (2QdxY4RzWzUUiLuE at potatochowder.com) Date: Fri, 17 Jun 2022 05:39:30 -0500 Subject: ModuleNotFoundError In-Reply-To: References: Message-ID: On 2022-06-17 at 08:03:28 +0000, Zoltan Szenderak wrote: > How do I reply to: Chris Angelico rosuav at gmail.com so it is listed > on the Python list? Please don't. Please continue replying to python-list at python.org; that way, other people can help you, and future programmers can find their issues in the public archives. ChrisA is a regular on this list, and will see your replies on it. From eryksun at gmail.com Fri Jun 17 07:35:34 2022 From: eryksun at gmail.com (Eryk Sun) Date: Fri, 17 Jun 2022 06:35:34 -0500 Subject: ModuleNotFoundError In-Reply-To: References: Message-ID: On 6/17/22, Zoltan Szenderak wrote: > > print(sys.version_info) and executable: > Unable to initialize device PRN That's the command-line "print" program. You need to first start the Python shell via python.exe. The prompt should change to ">>> ". Then run print(sys.version) and print(sys.executable). From z.szenderak at hotmail.com Fri Jun 17 08:24:17 2022 From: z.szenderak at hotmail.com (z.szenderak at hotmail.com) Date: Fri, 17 Jun 2022 13:24:17 +0100 Subject: ModuleNotFoundError In-Reply-To: References: Message-ID: Thank you for your email. C:\Users\zszen>python.exe Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print(sys.version) Traceback (most recent call last): File "", line 1, in NameError: name 'sys' is not defined >>> print(sys.executable) Traceback (most recent call last): File "", line 1, in NameError: name 'sys' is not defined On Fri, Jun 17, 2022, at 12:35 PM, Eryk Sun wrote: > On 6/17/22, Zoltan Szenderak wrote: > > > > print(sys.version_info) and executable: > > Unable to initialize device PRN > > That's the command-line "print" program. You need to first start the > Python shell via python.exe. The prompt should change to ">>> ". Then > run print(sys.version) and print(sys.executable). > From inhahe at gmail.com Fri Jun 17 08:26:21 2022 From: inhahe at gmail.com (inhahe) Date: Fri, 17 Jun 2022 08:26:21 -0400 Subject: ModuleNotFoundError In-Reply-To: References: Message-ID: sys is a built-in module, but it's not in the namespace unless you import it first. before your print statement, enter "import sys" On Fri, Jun 17, 2022 at 8:23 AM wrote: > Thank you for your email. > > C:\Users\zszen>python.exe > Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 > bit (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> print(sys.version) > Traceback (most recent call last): > File "", line 1, in > NameError: name 'sys' is not defined > > >>> print(sys.executable) > Traceback (most recent call last): > File "", line 1, in > NameError: name 'sys' is not defined > > On Fri, Jun 17, 2022, at 12:35 PM, Eryk Sun wrote: > > On 6/17/22, Zoltan Szenderak wrote: > > > > > > print(sys.version_info) and executable: > > > Unable to initialize device PRN > > > > That's the command-line "print" program. You need to first start the > > Python shell via python.exe. The prompt should change to ">>> ". Then > > run print(sys.version) and print(sys.executable). > > > -- > https://mail.python.org/mailman/listinfo/python-list > From inhahe at gmail.com Fri Jun 17 08:30:14 2022 From: inhahe at gmail.com (inhahe) Date: Fri, 17 Jun 2022 08:30:14 -0400 Subject: ModuleNotFoundError In-Reply-To: References: Message-ID: sorry, I may have misused the term "namespace." I'm not sure what the proper word is for the names currently loaded into the global scope. On Fri, Jun 17, 2022 at 8:26 AM inhahe wrote: > sys is a built-in module, but it's not in the namespace unless you import > it first. > before your print statement, enter "import sys" > > On Fri, Jun 17, 2022 at 8:23 AM wrote: > >> Thank you for your email. >> >> C:\Users\zszen>python.exe >> Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 >> 64 bit (AMD64)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> print(sys.version) >> Traceback (most recent call last): >> File "", line 1, in >> NameError: name 'sys' is not defined >> >> >>> print(sys.executable) >> Traceback (most recent call last): >> File "", line 1, in >> NameError: name 'sys' is not defined >> >> On Fri, Jun 17, 2022, at 12:35 PM, Eryk Sun wrote: >> > On 6/17/22, Zoltan Szenderak wrote: >> > > >> > > print(sys.version_info) and executable: >> > > Unable to initialize device PRN >> > >> > That's the command-line "print" program. You need to first start the >> > Python shell via python.exe. The prompt should change to ">>> ". Then >> > run print(sys.version) and print(sys.executable). >> > >> -- >> https://mail.python.org/mailman/listinfo/python-list >> > From joel.goldstick at gmail.com Fri Jun 17 11:26:36 2022 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 17 Jun 2022 11:26:36 -0400 Subject: ModuleNotFoundError In-Reply-To: References: Message-ID: On Fri, Jun 17, 2022 at 8:31 AM inhahe wrote: > > sorry, I may have misused the term "namespace." I'm not sure what the > proper word is for the names currently loaded into the global scope. > > On Fri, Jun 17, 2022 at 8:26 AM inhahe wrote: > > > sys is a built-in module, but it's not in the namespace unless you import > > it first. > > before your print statement, enter "import sys" > > > > On Fri, Jun 17, 2022 at 8:23 AM wrote: > > > >> Thank you for your email. > >> > >> C:\Users\zszen>python.exe > >> Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 > >> 64 bit (AMD64)] on win32 > >> Type "help", "copyright", "credits" or "license" for more information. > >> >>> print(sys.version) > >> Traceback (most recent call last): > >> File "", line 1, in > >> NameError: name 'sys' is not defined > >> > >> >>> print(sys.executable) > >> Traceback (most recent call last): > >> File "", line 1, in > >> NameError: name 'sys' is not defined > >> > >> On Fri, Jun 17, 2022, at 12:35 PM, Eryk Sun wrote: > >> > On 6/17/22, Zoltan Szenderak wrote: > >> > > > >> > > print(sys.version_info) and executable: > >> > > Unable to initialize device PRN > >> > > >> > That's the command-line "print" program. You need to first start the > >> > Python shell via python.exe. The prompt should change to ">>> ". Then > >> > run print(sys.version) and print(sys.executable). > >> > > >> -- > >> https://mail.python.org/mailman/listinfo/python-list > >> > > > -- > https://mail.python.org/mailman/listinfo/python-list sys is a module that is part of 'batteries included' in python. Since it is not part of the language per se, you need to import it -- Joel Goldstick From rshepard at appl-ecosys.com Fri Jun 17 12:19:59 2022 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Fri, 17 Jun 2022 09:19:59 -0700 (PDT) Subject: Tkinter module test: widget class not inserted in application frame Message-ID: I'm not seeing the error source in a small tkinter module I'm testing. The module code: ----------- import tkinter as tk from tkinter import ttk import common_classes as cc class ConactNameInput(tk.Frame): def __init__(self, parent, *args, **kwargs): super().__init__(parent, *args, **kwargs) # A dict to keep track of input widgets self.inputs = {} self.inputs['Last name'] = cc.LabelInput( ContactNameInput, 'lname', input_class = ttk.Entry, input_var = tk.StringVar() ) self.inputs['Last name'].grid(row = 0, column = 0) # self.inputs['First name'] = cc.LabelInput( ContactNameInput, 'fname', input_class = ttk.Entry, input_var = tk.StringVar() ) self.inputs['First name'].grid(row = 0, column = 1) okay_button = tk.Button(self, text="OK", command=self.ok) okay_button.pack(side=tk.LEFT, padx=(20, 0), pady=(0, 20)) cancel_button = tk.Button(self, text="Cancel", command=self.cancel) cancel_button.pack(side=tk.RIGHT, padx=(0, 20), pady=(0, 20)) def okay_button(self): pass def cancel_button(self): Quitter() def get_last_name(self): pass def get_first_name(self): pass class NameApplication(tk.Tk): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.title("Contact Name") self.geometry("800x600") self.resizable(width = False, height = False) ContactNameInput(self).grid(row = 0, column = 0, sticky=('EWNS')) self.columnconfigure(0, weight=1) if __name__ == '__main__': app = NameApplication() app.mainloop() ---------- The python error traceback: ---------- Traceback (most recent call last): File "contact_history_name_input.py", line 60, in app = NameApplication() File "contact_history_name_input.py", line 55, in __init__ ContactNameInput(self).grid(row = 0, column = 0, sticky=('EWNS')) File "contact_history_name_input.py", line 17, in __init__ input_var = tk.StringVar() File "/home/rshepard/development/BusinessTracker/views/common_classes.py", line 46, in __init__ super().__init__(parent, **kwargs) File "/usr/lib64/python3.7/tkinter/__init__.py", line 2744, in __init__ Widget.__init__(self, master, 'frame', cnf, {}, extra) File "/usr/lib64/python3.7/tkinter/__init__.py", line 2292, in __init__ BaseWidget._setup(self, master, cnf) File "/usr/lib64/python3.7/tkinter/__init__.py", line 2262, in _setup self.tk = master.tk AttributeError: type object 'ContactNameInput' has no attribute 'tk' ---------- I'm not correctly placing the NameInput class in the NameApplication frame. What have I missed? Rich From python at mrabarnett.plus.com Fri Jun 17 12:47:24 2022 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 17 Jun 2022 17:47:24 +0100 Subject: Tkinter module test: widget class not inserted in application frame In-Reply-To: References: Message-ID: On 2022-06-17 17:19, Rich Shepard wrote: > I'm not seeing the error source in a small tkinter module I'm testing. > > The module code: > ----------- > import tkinter as tk > from tkinter import ttk > > import common_classes as cc > > class ConactNameInput(tk.Frame): > def __init__(self, parent, *args, **kwargs): > super().__init__(parent, *args, **kwargs) > # A dict to keep track of input widgets > self.inputs = {} > > self.inputs['Last name'] = cc.LabelInput( > ContactNameInput, 'lname', > input_class = ttk.Entry, > input_var = tk.StringVar() > ) > self.inputs['Last name'].grid(row = 0, column = 0) > # > self.inputs['First name'] = cc.LabelInput( > ContactNameInput, 'fname', > input_class = ttk.Entry, > input_var = tk.StringVar() > ) > self.inputs['First name'].grid(row = 0, column = 1) > > okay_button = tk.Button(self, text="OK", > command=self.ok) > okay_button.pack(side=tk.LEFT, padx=(20, 0), pady=(0, 20)) > > cancel_button = tk.Button(self, text="Cancel", > command=self.cancel) > cancel_button.pack(side=tk.RIGHT, padx=(0, 20), pady=(0, 20)) > > def okay_button(self): > pass > > def cancel_button(self): > Quitter() > > def get_last_name(self): > pass > > def get_first_name(self): > pass > > > class NameApplication(tk.Tk): > def __init__(self, *args, **kwargs): > super().__init__(*args, **kwargs) > self.title("Contact Name") > self.geometry("800x600") > self.resizable(width = False, height = False) > ContactNameInput(self).grid(row = 0, column = 0, sticky=('EWNS')) > self.columnconfigure(0, weight=1) > > if __name__ == '__main__': > app = NameApplication() > app.mainloop() > ---------- > > The python error traceback: > ---------- > Traceback (most recent call last): > File "contact_history_name_input.py", line 60, in > app = NameApplication() > File "contact_history_name_input.py", line 55, in __init__ > ContactNameInput(self).grid(row = 0, column = 0, sticky=('EWNS')) > File "contact_history_name_input.py", line 17, in __init__ > input_var = tk.StringVar() > File "/home/rshepard/development/BusinessTracker/views/common_classes.py", line 46, in __init__ > super().__init__(parent, **kwargs) > File "/usr/lib64/python3.7/tkinter/__init__.py", line 2744, in __init__ > Widget.__init__(self, master, 'frame', cnf, {}, extra) > File "/usr/lib64/python3.7/tkinter/__init__.py", line 2292, in __init__ > BaseWidget._setup(self, master, cnf) > File "/usr/lib64/python3.7/tkinter/__init__.py", line 2262, in _setup > self.tk = master.tk > AttributeError: type object 'ContactNameInput' has no attribute 'tk' > ---------- > > I'm not correctly placing the NameInput class in the NameApplication frame. > What have I missed? > You haven't shown the code for common_classes.LabelInput, but I'm guessing that the first argument should be the parent. You're passing in the _class_ ConactNameInput, but I'm guessing that it should be an _instance_ of that class, in this case, 'self'. From rshepard at appl-ecosys.com Fri Jun 17 13:06:12 2022 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Fri, 17 Jun 2022 10:06:12 -0700 (PDT) Subject: Tkinter module test: widget class not inserted in application frame In-Reply-To: References: Message-ID: <932a792-96cd-4e62-306d-5ff48b352336@appl-ecosys.com> On Fri, 17 Jun 2022, MRAB wrote: > You haven't shown the code for common_classes.LabelInput, but I'm guessing > that the first argument should be the parent. Here's the LabelInput class: class LabelInput(tk.Frame): """ A widget containing a label and input together. """ def __init__(self, parent, label='', input_class=ttk.Entry, input_var=None, input_args=None, label_args=None, **kwargs): super().__init__(parent, **kwargs) label_args = label_args or {} input_args = input_args or {} self.variable = input_var, if input_class in (ttk.Checkbutton, ttk.Button, ttk.Radiobutton): input_args["text"] = label input_args["variable"] = input_var else: self.label = ttk.Label(self, text=label, **label_args) self.label.grid(row=0, column=0, sticky=(tk.W + tk.E)) input_args["textvariable"] = input_var self.input = input_class(self, **input_args) self.input.grid(row=1, column=0, sticky=(tk.W + tk.E)) self.columnconfigure(0, weight=1) self.error = getattr(self.input, 'error', tk.StringVar()) self.error_label = ttk.Label(self, textvariable=self.error) self.error_label.grid(row=2, column=0, sticky=(tk.W + tk.E)) def grid(self, sticky=(tk.E + tk.W), **kwargs): super().grid(sticky=sticky, **kwargs) def get(self): try: if self.variable: return self.variable.get() elif type(self.input) == tk.Text: return self.input.get('1.0', tk.END) else: return self.input.get() except (TypeError, tk.TclError): # happens when numeric fields are empty. return '' def set(self, value, *args, **kwargs): if type(self.variable) == tk.BooleanVar: self.variable.set(bool(value)) elif self.variable: self.variable.set(value, *args, **kwargs) elif type(self.input) in (ttk.Checkbutton, ttk.Radiobutton): if value: self.input.select() else: self.input.deselect() elif type(self.input) == tk.Text: self.input.delete('1.0', tk.END) self.input.insert('1.0', value) else: self.input.delete(0, tk.END) self.input.insert(0, value) > You're passing in the _class_ ConactNameInput, but I'm guessing that it > should be an _instance_ of that class, in this case, 'self'. Haven't I done this in the application class? class NameApplication(tk.Tk): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.title("Contact Name") self.geometry("800x600") self.resizable(width = False, height = False) ContactNameInput(self).grid(row = 0, column = 0, sticky=('EWNS')) self.columnconfigure(0, weight=1) If not, where do I specify the instance of the ContactNameInput class? Thanks, Rich -- Richard Shepard, Ph.D. The Environmental Issues Doctor Applied Ecosystem Services, LLC Troutdale, OR 97060 USA 503-667-4517 www[dot]appl-ecosys[dot]com From python at mrabarnett.plus.com Fri Jun 17 14:28:12 2022 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 17 Jun 2022 19:28:12 +0100 Subject: Tkinter module test: widget class not inserted in application frame In-Reply-To: <932a792-96cd-4e62-306d-5ff48b352336@appl-ecosys.com> References: <932a792-96cd-4e62-306d-5ff48b352336@appl-ecosys.com> Message-ID: On 2022-06-17 18:06, Rich Shepard wrote: > On Fri, 17 Jun 2022, MRAB wrote: > >> You haven't shown the code for common_classes.LabelInput, but I'm guessing >> that the first argument should be the parent. > [snip] >> You're passing in the _class_ ConactNameInput, but I'm guessing that it >> should be an _instance_ of that class, in this case, 'self'. > > Haven't I done this in the application class? > class NameApplication(tk.Tk): > def __init__(self, *args, **kwargs): > super().__init__(*args, **kwargs) > self.title("Contact Name") > self.geometry("800x600") > self.resizable(width = False, height = False) > ContactNameInput(self).grid(row = 0, column = 0, sticky=('EWNS')) > self.columnconfigure(0, weight=1) > > If not, where do I specify the instance of the ContactNameInput class? > This: self.inputs['Last name'] = cc.LabelInput( ContactNameInput, 'lname', input_class = ttk.Entry, input_var = tk.StringVar() ) should be this: self.inputs['Last name'] = cc.LabelInput( self, 'lname', input_class = ttk.Entry, input_var = tk.StringVar() ) Also, this: self.inputs['First name'] = cc.LabelInput( ContactNameInput, 'fname', input_class = ttk.Entry, input_var = tk.StringVar() ) should be this: self.inputs['First name'] = cc.LabelInput( self, 'fname', input_class = ttk.Entry, input_var = tk.StringVar() ) From rshepard at appl-ecosys.com Fri Jun 17 14:54:19 2022 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Fri, 17 Jun 2022 11:54:19 -0700 (PDT) Subject: Tkinter module test: widget class not inserted in application frame In-Reply-To: References: <932a792-96cd-4e62-306d-5ff48b352336@appl-ecosys.com> Message-ID: <12769364-9f5f-4574-9c45-164e5e666e13@appl-ecosys.com> On Fri, 17 Jun 2022, MRAB wrote: > This: > > self.inputs['Last name'] = cc.LabelInput( > ContactNameInput, 'lname', > input_class = ttk.Entry, > input_var = tk.StringVar() > ) > > should be this: > > self.inputs['Last name'] = cc.LabelInput( > self, 'lname', > input_class = ttk.Entry, > input_var = tk.StringVar() > ) > > Also, this: > > self.inputs['First name'] = cc.LabelInput( > ContactNameInput, 'fname', > input_class = ttk.Entry, > input_var = tk.StringVar() > ) > > should be this: > > self.inputs['First name'] = cc.LabelInput( > self, 'fname', > input_class = ttk.Entry, > input_var = tk.StringVar() > ) MRAB, Ah! I must have misread Alan Moore's examples, then. I'll need to fix all my views. Thank you, Rich From giorgosgporiotis at gmail.com Fri Jun 17 18:52:54 2022 From: giorgosgporiotis at gmail.com (GIORGOS PORIOTIS) Date: Sat, 18 Jun 2022 01:52:54 +0300 Subject: pycharm issue Message-ID: > Hello i have an issue with my pycharm latest edition, it doesnt take the files in the pycharm window , when i click on > them , also intead of the pycharm picture on my py files i have the idle picture ... From PythonList at DancesWithMice.info Fri Jun 17 19:02:36 2022 From: PythonList at DancesWithMice.info (dn) Date: Sat, 18 Jun 2022 11:02:36 +1200 Subject: pycharm issue In-Reply-To: References: Message-ID: <7bbacdea-0f29-3a85-3cd8-0dae2c3a6d59@DancesWithMice.info> On 18/06/2022 10.52, GIORGOS PORIOTIS wrote: > > Hello i have an issue with my pycharm latest edition, it doesnt take the > files in the pycharm window , when i click on > > them , also intead of the pycharm picture on my py files i have the idle > picture ... This list is for Python (cf PyCharm)! However, many of us use PyCharm... What are you typing or clicking-on to start Python/Idle/PyCharm? Which operating system? -- Regards, =dn From PythonList at DancesWithMice.info Fri Jun 17 19:39:11 2022 From: PythonList at DancesWithMice.info (dn) Date: Sat, 18 Jun 2022 11:39:11 +1200 Subject: pycharm issue In-Reply-To: References: <7bbacdea-0f29-3a85-3cd8-0dae2c3a6d59@DancesWithMice.info> Message-ID: <3155b9ed-45fe-8fd9-fdce-9dcbadd7c0a3@DancesWithMice.info> On 18/06/2022 11.21, Giorgos Poriotis wrote: > I use windows 10 , I click on a shortcut of the pycharm , the icon that > runs the programm Please reply to the list - there are many people here who know more than I, and can help you with MS-Windows issues. Please review https://docs.python.org/3/using/windows.html If it is a matter of choosing which/how to open .py files, that is an MS-Win question. There may be a decision to be made: does clicking on a .py file mean that you wish to edit it (in PyCharm), or do you wish to run the code in the Python interpreter. > *From: *dn > *Sent: *Saturday, June 18, 2022 02:05 > *To: *python-list at python.org > *Subject: *Re: pycharm issue > > ? > > On 18/06/2022 10.52, GIORGOS PORIOTIS wrote: > >>? > Hello i have an issue with my pycharm latest edition, it doesnt > take the > >> files in the pycharm window , when i click on > >>? > them , also intead of the pycharm picture on my py files i have the > idle > >> picture ... > > ? > > This list is for Python (cf PyCharm)! However, many of us use PyCharm... > > ? > > What are you typing or clicking-on to start Python/Idle/PyCharm? > > Which operating system? -- Regards, =dn From wlfraed at ix.netcom.com Fri Jun 17 20:45:49 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 17 Jun 2022 20:45:49 -0400 Subject: Tkinter module test: widget class not inserted in application frame References: Message-ID: <2t7qah1dhkk424kpqh16k562qm41gj3qbk@4ax.com> On Fri, 17 Jun 2022 09:19:59 -0700 (PDT), Rich Shepard declaimed the following: >I'm not seeing the error source in a small tkinter module I'm testing. > >The module code: >----------- >import tkinter as tk >from tkinter import ttk > >import common_classes as cc > >class ConactNameInput(tk.Frame): Presuming this is a cut&paste of the actual code... > ContactNameInput, 'lname', > ContactNameInput, 'fname', > ContactNameInput(self).grid(row = 0, column = 0, sticky=('EWNS')) ... please compare the spelling! -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From rosuav at gmail.com Fri Jun 17 22:36:25 2022 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 18 Jun 2022 12:36:25 +1000 Subject: PEP 401 origin and authorship Message-ID: Somewhere around the place, I remember reading something about how PEP 401 (the retirement of the BDFL and the accession of the FLUFL) came to be. It involved a joke being turned on its originator, I think. But I can't find it back. Anyone have a reference handy? ChrisA From rshepard at appl-ecosys.com Fri Jun 17 22:47:38 2022 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Fri, 17 Jun 2022 19:47:38 -0700 (PDT) Subject: Tkinter module test: widget class not inserted in application frame In-Reply-To: <2t7qah1dhkk424kpqh16k562qm41gj3qbk@4ax.com> References: <2t7qah1dhkk424kpqh16k562qm41gj3qbk@4ax.com> Message-ID: <245cf147-f9e1-fc75-aad0-e8dca81b96e0@appl-ecosys.com> On Fri, 17 Jun 2022, Dennis Lee Bieber wrote: >> ContactNameInput, 'lname', >> ContactNameInput, 'fname', This works if a tk.labelframe is where the widget is placed. In my case, as MRAB taught me, the proper syntax is self,'lname'... self.'fname'... Thanks, Dennis, Rich From hjp-python at hjp.at Sat Jun 18 04:10:34 2022 From: hjp-python at hjp.at (Peter J. Holzer) Date: Sat, 18 Jun 2022 10:10:34 +0200 Subject: Tkinter module test: widget class not inserted in application frame In-Reply-To: <245cf147-f9e1-fc75-aad0-e8dca81b96e0@appl-ecosys.com> References: <2t7qah1dhkk424kpqh16k562qm41gj3qbk@4ax.com> <245cf147-f9e1-fc75-aad0-e8dca81b96e0@appl-ecosys.com> Message-ID: <20220618081034.adyhgyae5n3ln3fm@hjp.at> On 2022-06-17 19:47:38 -0700, Rich Shepard wrote: > On Fri, 17 Jun 2022, Dennis Lee Bieber wrote: > > > > ContactNameInput, 'lname', > > > ContactNameInput, 'fname', > > This works if a tk.labelframe is where the widget is placed. In my case, as > MRAB taught me, the proper syntax is > self,'lname'... There is a comma (U+002C) here ... > self.'fname'... And a dot (U+002E) here. I don't think this is correct. I would also recommend to always add a space after a comma. hp -- _ | Peter J. Holzer | Story must make more sense than reality. |_|_) | | | | | hjp at hjp.at | -- Charles Stross, "Creative writing __/ | http://www.hjp.at/ | challenge!" -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 833 bytes Desc: not available URL: From rshepard at appl-ecosys.com Sat Jun 18 08:06:22 2022 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Sat, 18 Jun 2022 05:06:22 -0700 (PDT) Subject: Tkinter module test: widget class not inserted in application frame In-Reply-To: <20220618081034.adyhgyae5n3ln3fm@hjp.at> References: <2t7qah1dhkk424kpqh16k562qm41gj3qbk@4ax.com> <245cf147-f9e1-fc75-aad0-e8dca81b96e0@appl-ecosys.com> <20220618081034.adyhgyae5n3ln3fm@hjp.at> Message-ID: On Sat, 18 Jun 2022, Peter J. Holzer wrote: > There is a comma (U+002C) here ... > And a dot (U+002E) here. That was a typo when I wrote the message. And I usually add a space after commas and surrounding equal signs, all for easier reading. Thank you, Rich From jschwar at sbcglobal.net Mon Jun 20 14:49:31 2022 From: jschwar at sbcglobal.net (jschwar at sbcglobal.net) Date: Mon, 20 Jun 2022 13:49:31 -0500 Subject: traceback Shows path to my python libraries References: <004301d884d6$7acde010$7069a030$.ref@sbcglobal.net> Message-ID: <004301d884d6$7acde010$7069a030$@sbcglobal.net> I coded an application with a 64-bit executable using cython with the embed option and gcc and I received a traceback showing the path to my python installation. Is that normal or does that mean the application is going outside of my executable to my python libraries? I want it portable so it if is, then it's not portable. The error itself is not an issue. I lost my internet connection, so it's expected and it was retried like it should be. Traceback (most recent call last): File "C:\Users\jschw\AppData\Local\Programs\Python\Python310\lib\site-packages\ur llib3\connectionpool.py", line 703, in urlopen httplib_response = self._make_request( File "C:\Users\jschw\AppData\Local\Programs\Python\Python310\lib\site-packages\ur llib3\connectionpool.py", line 398, in _make_request conn.request(method, url, **httplib_request_kw) File "C:\Users\jschw\AppData\Local\Programs\Python\Python310\lib\site-packages\ur llib3\connection.py", line 239, in request super(HTTPConnection, self).request(method, url, body=body, headers=headers) File "C:\Users\jschw\AppData\Local\Programs\Python\Python310\Lib\http\client.py", line 1282, in request self._send_request(method, url, body, headers, encode_chunked) . Thanks. From usenet at gkbrk.com Sun Jun 19 08:08:09 2022 From: usenet at gkbrk.com (Leo) Date: Sun, 19 Jun 2022 12:08:09 -0000 (UTC) Subject: mapLast, mapFirst, and just general iterator questions References: Message-ID: On Wed, 15 Jun 2022 04:47:31 +1000, Chris Angelico wrote: > Don't bother with a main() function unless you actually need to be > able to use it as a function. Most of the time, it's simplest to > just have the code you want, right there in the file. :) Python > isn't C or Java, and code doesn't have to get wrapped up in > functions in order to exist. Actually a main() function in Python is pretty useful, because Python code on the top level executes a lot slower. I believe this is due to global variable lookups instead of local. Here is benchmark output from a small test. ``` Benchmark 1: python3 test1.py Time (mean ? ?): 662.0 ms ? 44.7 ms Range (min ? max): 569.4 ms ? 754.1 ms Benchmark 2: python3 test2.py Time (mean ? ?): 432.1 ms ? 14.4 ms Range (min ? max): 411.4 ms ? 455.1 ms Summary 'python3 test2.py' ran 1.53 ? 0.12 times faster than 'python3 test1.py' ``` Contents of test1.py: ``` l1 = list(range(5_000_000)) l2 = [] while l1: l2.append(l1.pop()) print(len(l1), len(l2)) ``` Contents of test2.py: ``` def main(): l1 = list(range(5_000_000)) l2 = [] while l1: l2.append(l1.pop()) print(len(l1), len(l2)) main() ``` -- Leo From cyber at sysrq.in Sun Jun 19 10:07:35 2022 From: cyber at sysrq.in (jan Anja) Date: Sun, 19 Jun 2022 14:07:35 -0000 (UTC) Subject: What's up with modern Python programmers rewriting everything in Rust? Message-ID: Dude, it's called CPython for a reason. From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Mon Jun 20 10:54:29 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Mon, 20 Jun 2022 15:54:29 +0100 Subject: What's up with modern Python programmers rewriting everything in Rust? References: Message-ID: ?s 15:07 de 19/06/22, jan Anja escreveu: > Dude, it's called CPython for a reason. IMHO CPython means Core Python, not C Python. From wlfraed at ix.netcom.com Mon Jun 20 11:40:04 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 20 Jun 2022 11:40:04 -0400 Subject: What's up with modern Python programmers rewriting everything in Rust? References: Message-ID: On Mon, 20 Jun 2022 15:54:29 +0100, Paulo da Silva declaimed the following: >?s 15:07 de 19/06/22, jan Anja escreveu: >> Dude, it's called CPython for a reason. > >IMHO CPython means Core Python, not C Python. It is, as I recall, a term for the reference implementation of Python, which was written in C... In contrast to things like Jython -- Python implemented using Java. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Mon Jun 20 12:38:36 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Mon, 20 Jun 2022 17:38:36 +0100 Subject: What's up with modern Python programmers rewriting everything in Rust? References: Message-ID: ?s 16:40 de 20/06/22, Dennis Lee Bieber escreveu: > On Mon, 20 Jun 2022 15:54:29 +0100, Paulo da Silva > declaimed the following: > >> ?s 15:07 de 19/06/22, jan Anja escreveu: >>> Dude, it's called CPython for a reason. >> >> IMHO CPython means Core Python, not C Python. > > It is, as I recall, a term for the reference implementation of Python, > which was written in C... In contrast to things like Jython -- Python > implemented using Java. > > Yes, it is a reference. That's why it is called "Core Python". The "C" has nothing to do with the C programming language. It may well be written in any language. So far it is "C" language. From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Mon Jun 20 15:01:51 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Mon, 20 Jun 2022 20:01:51 +0100 Subject: "CPython" References: Message-ID: ?s 18:19 de 20/06/22, Stefan Ram escreveu: > The same personality traits that make people react > to troll postings might make them spread unconfirmed > ideas about the meaning of "C" in "CPython". > > The /core/ of CPython is written in C. > > CPython is the /canonical/ implementation of Python. > > The "C" in "CPython" stands for C. > > Not so "unconfirmed"! Look at this article, I recently read: https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ There is a sentence in ther that begins with "CPython, short for Core Python, a reference implementation that other Python distributions are derived from, ...". Anyway, I wrote "IMHO". Do you have any credible reference to your assertion "The "C" in "CPython" stands for C."? Thank you. From wlfraed at ix.netcom.com Mon Jun 20 15:31:32 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 20 Jun 2022 15:31:32 -0400 Subject: "CPython" References: Message-ID: On Mon, 20 Jun 2022 20:01:51 +0100, Paulo da Silva declaimed the following: >Not so "unconfirmed"! >Look at this article, I recently read: >https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ > >There is a sentence in ther that begins with "CPython, short for Core >Python, a reference implementation that other Python distributions are >derived from, ...". > >Anyway, I wrote "IMHO". > >Do you have any credible reference to your assertion "The "C" in >"CPython" stands for C."? > Well, let's start at the top... https://www.python.org/download/alternatives/ ("traditional" implying implemented in C). https://en.wikipedia.org/wiki/CPython https://stackoverflow.com/questions/17130975/python-vs-cpython https://www.c-sharpcorner.com/article/why-learn-python-an-introduction-to-python/ https://www.geeksforgeeks.org/difference-various-implementations-python/ There is some plagiarism between a number of web-sites, but they all emphasize the "CPython" is a reference implementation and that it is written in C vs Java (Jython), C# (IronPython -- which M$ may be deprecating these days, based on some stuff in my last Visual Studio update), or other.... -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From rosuav at gmail.com Mon Jun 20 17:01:59 2022 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 21 Jun 2022 07:01:59 +1000 Subject: mapLast, mapFirst, and just general iterator questions In-Reply-To: References: Message-ID: On Tue, 21 Jun 2022 at 06:16, Leo wrote: > > On Wed, 15 Jun 2022 04:47:31 +1000, Chris Angelico wrote: > > > Don't bother with a main() function unless you actually need to be > > able to use it as a function. Most of the time, it's simplest to > > just have the code you want, right there in the file. :) Python > > isn't C or Java, and code doesn't have to get wrapped up in > > functions in order to exist. > > Actually a main() function in Python is pretty useful, because Python > code on the top level executes a lot slower. I believe this is due to > global variable lookups instead of local. > > Here is benchmark output from a small test. > > ``` > Benchmark 1: python3 test1.py > Time (mean ? ?): 662.0 ms ? 44.7 ms > Range (min ? max): 569.4 ms ? 754.1 ms > > Benchmark 2: python3 test2.py > Time (mean ? ?): 432.1 ms ? 14.4 ms > Range (min ? max): 411.4 ms ? 455.1 ms > > Summary > 'python3 test2.py' ran > 1.53 ? 0.12 times faster than 'python3 test1.py' > ``` > > Contents of test1.py: > > ``` > l1 = list(range(5_000_000)) > l2 = [] > > while l1: > l2.append(l1.pop()) > > print(len(l1), len(l2)) > ``` > > Contents of test2.py: > > ``` > def main(): > l1 = list(range(5_000_000)) > l2 = [] > > while l1: > l2.append(l1.pop()) > > print(len(l1), len(l2)) > main() > ``` > To be quite honest, I have never once in my life had a time when the execution time of a script is dominated by global variable lookups in what would be the main function, AND it takes long enough to care about it. Yes, technically it might be faster, but I've probably spent more time reading your post than I'll ever save by putting stuff into a function :) Also, often at least some of those *need* to be global in order to be useful, so you'd lose any advantage you gain. ChrisA From rosuav at gmail.com Mon Jun 20 17:12:02 2022 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 21 Jun 2022 07:12:02 +1000 Subject: "CPython" In-Reply-To: References: Message-ID: On Tue, 21 Jun 2022 at 06:31, Stefan Ram wrote: > > Paulo da Silva writes: > >Do you have any credible reference to your assertion "The "C" in > >"CPython" stands for C."? > > Whether a source is considered "credible" is something > everyone must decide for themselves. > > I can say that the overwhelming majority of results of Web > searches about this topic yields expressions of the view > that the "C" in "CPython" stands for C, "overwhelming > majority" when compared to expressions of other interpretations > of that "C", and "overwhelming majority" meaning something > like more than 90 percent. > > For one example, there seems to be a book "CPython Internals" > which seems to say, according to one Web search engine: > > |The C in CPython is a reference to the C programming > |language, indicating that this Python distribution is > |written in the C language. > Does python.org count as "credible"? https://docs.python.org/3/reference/introduction.html CPython: This is the original and most-maintained implementation of Python, written in C. I think that's about as close as you're going to get to an answer. Given that it is, in that page, being distinguished from Jython (implemented in Python), PyPy (implemented in Python), Python for .NET (implemented for the .NET runtime), and IronPython (one of these is not like the others, whatever, but it's the one originally implemented for .NET), it seems fairly safe to say that the C in CPython means the implementation language. If someone wants to contradict this, they'll need a strong source, like a post from a core dev back when Jython was brand new. ChrisA From roel at roelschroeven.net Mon Jun 20 17:47:20 2022 From: roel at roelschroeven.net (Roel Schroeven) Date: Mon, 20 Jun 2022 23:47:20 +0200 Subject: "CPython" In-Reply-To: References: Message-ID: <37cf47f6-3121-846c-f734-e3784b0581a4@roelschroeven.net> Paulo da Silva schreef op 20/06/2022 om 21:01: > ?s 18:19 de 20/06/22, Stefan Ram escreveu: > > The same personality traits that make people react > > to troll postings might make them spread unconfirmed > > ideas about the meaning of "C" in "CPython". > > > > The /core/ of CPython is written in C. > > > > CPython is the /canonical/ implementation of Python. > > > > The "C" in "CPython" stands for C. > > > > > > Not so "unconfirmed"! > Look at this article, I recently read: > https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ > > There is a sentence in ther that begins with "CPython, short for Core > Python, a reference implementation that other Python distributions are > derived from, ...". Counterpoint: https://wiki.python.org/moin/SummerOfCode/2017/python-core says "The reference implementation of Python is CPython, so named because it's written in C." Even in the absence of other evidence I'd much rather trust a python.org page than a www.analyticsinsight.net page on the subject of Python implementations. But there's more. Apart from www.analyticsinsight.net I can't find any website that mentions "Core Python" as a Python implementation. That's a strong indication that www.analyticsinsight.net is wrong on that point. Frankly that website seems very low quality in general. In that same article they say: "CPython is a descendant of Pyscript built on Pyodide, a port of CPython, or a Python distribution for the browser and Node.js that is based on Webassembly and Emscripten." CPython is definitely not a descendant of Pyscript! Looks like someone found something (semi-) interesting and tried to write something insightful about it, but without really understanding any of it. Other articles don't seem to be any better. So we have an untrustworthy site that's the only one to claim that CPython is short for Core Python, and we have an official site that says CPython is so named because it's written in C. Hm, which one to believe? -- "In the old days, writers used to sit in front of a typewriter and stare out of the window. Nowadays, because of the marvels of convergent technology, the thing you type on and the window you stare out of are now the same thing.? -- Douglas Adams From PythonList at DancesWithMice.info Mon Jun 20 18:00:18 2022 From: PythonList at DancesWithMice.info (dn) Date: Tue, 21 Jun 2022 10:00:18 +1200 Subject: "CPython" In-Reply-To: <37cf47f6-3121-846c-f734-e3784b0581a4@roelschroeven.net> References: <37cf47f6-3121-846c-f734-e3784b0581a4@roelschroeven.net> Message-ID: <529270c9-6e13-b6ac-880b-12f7fbae3468@DancesWithMice.info> On 21/06/2022 09.47, Roel Schroeven wrote: ... > So we have an untrustworthy site that's the only one to claim that > CPython is short for Core Python, and we have an official site that says > CPython is so named because it's written in C. Hm, which one to believe? ...and so you can C that the only important part is the Python! -- Regards, =dn From rosuav at gmail.com Mon Jun 20 18:02:13 2022 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 21 Jun 2022 08:02:13 +1000 Subject: "CPython" In-Reply-To: <37cf47f6-3121-846c-f734-e3784b0581a4@roelschroeven.net> References: <37cf47f6-3121-846c-f734-e3784b0581a4@roelschroeven.net> Message-ID: On Tue, 21 Jun 2022 at 07:48, Roel Schroeven wrote: > > Paulo da Silva schreef op 20/06/2022 om 21:01: > > ?s 18:19 de 20/06/22, Stefan Ram escreveu: > > > The same personality traits that make people react > > > to troll postings might make them spread unconfirmed > > > ideas about the meaning of "C" in "CPython". > > > > > > The /core/ of CPython is written in C. > > > > > > CPython is the /canonical/ implementation of Python. > > > > > > The "C" in "CPython" stands for C. > > > > > > > > > > Not so "unconfirmed"! > > Look at this article, I recently read: > > https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ > > > > There is a sentence in ther that begins with "CPython, short for Core > > Python, a reference implementation that other Python distributions are > > derived from, ...". > > Counterpoint: https://wiki.python.org/moin/SummerOfCode/2017/python-core > says "The reference implementation of Python is CPython, so named > because it's written in C." Even in the absence of other evidence I'd > much rather trust a python.org page than a www.analyticsinsight.net page > on the subject of Python implementations. Be aware that this is a wiki, so anyone can edit it. But that also means you can check the "Info" link to see the history of the page, and in this case, the text in question was added by user TerriOda, who - as can be confirmed in various places - is heavily involved in GSOC Python projects and the like, so I would consider this to be fairly good information. (Though I can't honestly say whether many of the core Python devs read that wiki, so it's always possible that false information stays there untouched.) > But there's more. > > Apart from www.analyticsinsight.net I can't find any website that > mentions "Core Python" as a Python implementation. That's a strong > indication that www.analyticsinsight.net is wrong on that point. Frankly > that website seems very low quality in general. In that same article > they say: > > "CPython is a descendant of Pyscript built on Pyodide, a port of > CPython, or a Python distribution for the browser and Node.js that is > based on Webassembly and Emscripten." > > CPython is definitely not a descendant of Pyscript! Looks like someone > found something (semi-) interesting and tried to write something > insightful about it, but without really understanding any of it. Other > articles don't seem to be any better. > > So we have an untrustworthy site that's the only one to claim that > CPython is short for Core Python, and we have an official site that says > CPython is so named because it's written in C. Hm, which one to believe? > I think that's about as settled as it'll ever be. Like many things, it doesn't necessarily have any stronger origin than "someone started using the term, and it stuck". Reminds me of trying to research the origin of the name "Idle" (or "IDLE" - the Integrated Development and Learning Environment") and being unable to find any proof that it was named after a certain Eric, but nothing to disprove it either... ChrisA From rosuav at gmail.com Mon Jun 20 18:02:38 2022 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 21 Jun 2022 08:02:38 +1000 Subject: "CPython" In-Reply-To: <529270c9-6e13-b6ac-880b-12f7fbae3468@DancesWithMice.info> References: <37cf47f6-3121-846c-f734-e3784b0581a4@roelschroeven.net> <529270c9-6e13-b6ac-880b-12f7fbae3468@DancesWithMice.info> Message-ID: On Tue, 21 Jun 2022 at 08:01, dn wrote: > > On 21/06/2022 09.47, Roel Schroeven wrote: > ... > > > So we have an untrustworthy site that's the only one to claim that > > CPython is short for Core Python, and we have an official site that says > > CPython is so named because it's written in C. Hm, which one to believe? > > > ...and so you can C that the only important part is the Python! I should have cn that coming. ChrisA From PythonList at DancesWithMice.info Mon Jun 20 18:25:06 2022 From: PythonList at DancesWithMice.info (dn) Date: Tue, 21 Jun 2022 10:25:06 +1200 Subject: "CPython" In-Reply-To: References: <37cf47f6-3121-846c-f734-e3784b0581a4@roelschroeven.net> <529270c9-6e13-b6ac-880b-12f7fbae3468@DancesWithMice.info> Message-ID: <607ce494-ac88-5a42-92d4-481b1179f500@DancesWithMice.info> On 21/06/2022 10.02, Chris Angelico wrote: > On Tue, 21 Jun 2022 at 08:01, dn wrote: >> >> On 21/06/2022 09.47, Roel Schroeven wrote: >> ... >> >>> So we have an untrustworthy site that's the only one to claim that >>> CPython is short for Core Python, and we have an official site that says >>> CPython is so named because it's written in C. Hm, which one to believe? >> >> >> ...and so you can C that the only important part is the Python! > > I should have cn that coming. Which is a terribly OT invitation to make the (these days non-PC) Monty Python joke: "No-one expects the Spanish Inquisition" (https://www.youtube.com/watch?v=Cj8n4MfhjUc) -- Regards, =dn From wolfgang.grafen at gmail.com Mon Jun 20 18:43:26 2022 From: wolfgang.grafen at gmail.com (Wolfgang Grafen) Date: Mon, 20 Jun 2022 15:43:26 -0700 (PDT) Subject: Tkinter - cannot import tklib Message-ID: <8f6bca67-0a9c-47b1-aab8-e021ec527c4en@googlegroups.com> Hello all, I am an experienced Python user and struggle with following statement: >>> from tklib import * Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'tklib' I tried to import tklib as shown above on following of my Python installations: Anaconda Python 3.8.3, Portable Python 3.9, Python 3.10.1, Python 2.7.10 with the same negative result. I also tried to find help by googling - without success. Also I did not find a python module called tklib to install. Tkinter, ttk is working fine. There are numerous examples using "from tklib import *" so I assume it works for most. In the tk-tutorial below tklib is used without special explanation, so I assume it should be installed by default with every python installation which has Tkinter integrated. https://tk-tutorial.readthedocs.io/en/latest/intro/intro.html?highlight=app# First time that I cannot help myself. Please help, what do I do wrong? Greetings Wolfgang From python at mrabarnett.plus.com Mon Jun 20 20:03:10 2022 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 21 Jun 2022 01:03:10 +0100 Subject: Tkinter - cannot import tklib In-Reply-To: <8f6bca67-0a9c-47b1-aab8-e021ec527c4en@googlegroups.com> References: <8f6bca67-0a9c-47b1-aab8-e021ec527c4en@googlegroups.com> Message-ID: <1b32dbd4-5152-15b4-7d05-fe25b63022c0@mrabarnett.plus.com> On 2022-06-20 23:43, Wolfgang Grafen wrote: > Hello all, > > I am an experienced Python user and struggle with following statement: > >>>> from tklib import * > Traceback (most recent call last): > File "", line 1, in > ModuleNotFoundError: No module named 'tklib' > > I tried to import tklib as shown above on following of my Python installations: Anaconda Python 3.8.3, Portable Python 3.9, Python 3.10.1, Python 2.7.10 with the same negative result. > > I also tried to find help by googling - without success. Also I did not find a python module called tklib to install. Tkinter, ttk is working fine. > > There are numerous examples using "from tklib import *" so I assume it works for most. In the tk-tutorial below tklib is used without special explanation, so I assume it should be installed by default with every python installation which has Tkinter integrated. > > https://tk-tutorial.readthedocs.io/en/latest/intro/intro.html?highlight=app# > > First time that I cannot help myself. Please help, what do I do wrong? > I'm thinking that maybe that tutorial is about writing a module (called "tklib") to make it easier to write tkinter applications. The tkinter "Text" widget, for example, doesn't have its own scrollbars (you have to add them separately and link them to the widget), so writing a module that defines a text-with-scrollbars widget is a good idea. From wlfraed at ix.netcom.com Mon Jun 20 20:43:18 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 20 Jun 2022 20:43:18 -0400 Subject: Tkinter - cannot import tklib References: <8f6bca67-0a9c-47b1-aab8-e021ec527c4en@googlegroups.com> Message-ID: On Mon, 20 Jun 2022 15:43:26 -0700 (PDT), Wolfgang Grafen declaimed the following: > >There are numerous examples using "from tklib import *" so I assume it works for most. In the tk-tutorial below tklib is used without special explanation, so I assume it should be installed by default with every python installation which has Tkinter integrated. > >https://tk-tutorial.readthedocs.io/en/latest/intro/intro.html?highlight=app# > >First time that I cannot help myself. Please help, what do I do wrong? > From what I can see, you haven't /written/ a tklib module. That tutorial assumes you will create a module containing a number of simplified interfaces to tk widgets. cf: https://tk-tutorial.readthedocs.io/en/latest/radio/radio.html#a-better-radiobutton-class tklib.py will contain the definition of the Radiobutton class. The same probably applies everywhere that you see tklib imported -- whatever classes are used to create widgets need to be defined in that file. https://tk-tutorial.readthedocs.io/en/latest/intro/intro.html?highlight=app# """ In the following section we are going to redefine the tk and ttk objects. To make it easier to use them, we follow these design principles: we keep the excact same class names the parent object is chosen automatically all keyword arguments are forwarded The first widget to consider is the Label which just places static text. Where it makes sense, a label will be combined with a button or entry widget. """ https://tk-tutorial.readthedocs.io/en/latest/check/check.html#a-better-checkbutton-class etc. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Mon Jun 20 20:53:38 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Tue, 21 Jun 2022 01:53:38 +0100 Subject: "CPython" References: Message-ID: ?s 20:01 de 20/06/22, Paulo da Silva escreveu: > ?s 18:19 de 20/06/22, Stefan Ram escreveu: >> ?? The same personality traits that make people react >> ?? to troll postings might make them spread unconfirmed >> ?? ideas about the meaning of "C" in "CPython". >> >> ?? The /core/ of CPython is written in C. >> >> ?? CPython is the /canonical/ implementation of Python. >> >> ?? The "C" in "CPython" stands for C. >> >> > > Not so "unconfirmed"! > Look at this article, I recently read: > https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ > > > There is a sentence in ther that begins with "CPython, short for Core > Python, a reference implementation that other Python distributions are > derived from, ...". > > Anyway, I wrote "IMHO". > > Do you have any credible reference to your assertion "The "C" in > "CPython" stands for C."? > > Thank you. Well ... I read the responses and they are not touching the point! I just answered, with my opinion based on articles I have read in the past. Certainly I could not be sure. That's why I responded as an opinion (IMHO) and not as an assertion. Stefan Ram responded with a, at least, not very polite post. That's why I needed to somehow "defend" why I posted that response, and, BTW, trying to learn why he said that the C in CPython means "written in C". I still find very strange, to not say weird, that a compiler or interpreter has a name based in the language it was written. But, again, is just my opinion and nothing more. I rest my case. Thank you all. From rosuav at gmail.com Mon Jun 20 21:33:23 2022 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 21 Jun 2022 11:33:23 +1000 Subject: "CPython" In-Reply-To: References: Message-ID: On Tue, 21 Jun 2022 at 11:13, Paulo da Silva wrote: > > ?s 20:01 de 20/06/22, Paulo da Silva escreveu: > > ?s 18:19 de 20/06/22, Stefan Ram escreveu: > >> The same personality traits that make people react > >> to troll postings might make them spread unconfirmed > >> ideas about the meaning of "C" in "CPython". > >> > >> The /core/ of CPython is written in C. > >> > >> CPython is the /canonical/ implementation of Python. > >> > >> The "C" in "CPython" stands for C. > >> > >> > > > > Not so "unconfirmed"! > > Look at this article, I recently read: > > https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ > > > > > > There is a sentence in ther that begins with "CPython, short for Core > > Python, a reference implementation that other Python distributions are > > derived from, ...". > > > > Anyway, I wrote "IMHO". > > > > Do you have any credible reference to your assertion "The "C" in > > "CPython" stands for C."? > > > > Thank you. > > Well ... I read the responses and they are not touching the point! > I just answered, with my opinion based on articles I have read in the > past. Certainly I could not be sure. That's why I responded as an > opinion (IMHO) and not as an assertion. > Stefan Ram responded with a, at least, not very polite post. > That's why I needed to somehow "defend" why I posted that response, and, > BTW, trying to learn why he said that the C in CPython means "written in C". > > I still find very strange, to not say weird, that a compiler or > interpreter has a name based in the language it was written. But, again, > is just my opinion and nothing more. > Not sure why it's strange. The point is to distinguish "CPython" from "Jython" or "Brython" or "PyPy" or any of the other implementations. Yes, CPython has a special place because it's the reference implementation and the most popular, but the one thing that makes it distinct from all the others is that it's implemented in C. I could, perhaps, create my own interpreter and name it "RosuavPython" after myself, but when something's made by a team, it's usually more useful to pick something that is fundamental to it (Brython is designed to be run in a browser, Jython is written in Python to make it easy to call on Java classes, etc). ChrisA From python at mrabarnett.plus.com Mon Jun 20 22:20:16 2022 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 21 Jun 2022 03:20:16 +0100 Subject: "CPython" In-Reply-To: References: Message-ID: On 2022-06-21 02:33, Chris Angelico wrote: > On Tue, 21 Jun 2022 at 11:13, Paulo da Silva > wrote: >> >> ?s 20:01 de 20/06/22, Paulo da Silva escreveu: >> > ?s 18:19 de 20/06/22, Stefan Ram escreveu: >> >> The same personality traits that make people react >> >> to troll postings might make them spread unconfirmed >> >> ideas about the meaning of "C" in "CPython". >> >> >> >> The /core/ of CPython is written in C. >> >> >> >> CPython is the /canonical/ implementation of Python. >> >> >> >> The "C" in "CPython" stands for C. >> >> >> >> >> > >> > Not so "unconfirmed"! >> > Look at this article, I recently read: >> > https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ >> > >> > >> > There is a sentence in ther that begins with "CPython, short for Core >> > Python, a reference implementation that other Python distributions are >> > derived from, ...". >> > >> > Anyway, I wrote "IMHO". >> > >> > Do you have any credible reference to your assertion "The "C" in >> > "CPython" stands for C."? >> > >> > Thank you. >> >> Well ... I read the responses and they are not touching the point! >> I just answered, with my opinion based on articles I have read in the >> past. Certainly I could not be sure. That's why I responded as an >> opinion (IMHO) and not as an assertion. >> Stefan Ram responded with a, at least, not very polite post. >> That's why I needed to somehow "defend" why I posted that response, and, >> BTW, trying to learn why he said that the C in CPython means "written in C". >> >> I still find very strange, to not say weird, that a compiler or >> interpreter has a name based in the language it was written. But, again, >> is just my opinion and nothing more. >> > > Not sure why it's strange. The point is to distinguish "CPython" from > "Jython" or "Brython" or "PyPy" or any of the other implementations. > Yes, CPython has a special place because it's the reference > implementation and the most popular, but the one thing that makes it > distinct from all the others is that it's implemented in C. > And just to make it clear, the interpreter/compiler _itself_ is still called "python". "CPython" is a name/term that was applied retroactively to that particular implementation when another implementation appeared. > I could, perhaps, create my own interpreter and name it "RosuavPython" > after myself, but when something's made by a team, it's usually more > useful to pick something that is fundamental to it (Brython is > designed to be run in a browser, Jython is written in Python to make > it easy to call on Java classes, etc). > > ChrisA From avigross at verizon.net Mon Jun 20 22:52:28 2022 From: avigross at verizon.net (Avi Gross) Date: Tue, 21 Jun 2022 02:52:28 +0000 (UTC) Subject: "CPython" In-Reply-To: References: Message-ID: <1925863570.3590960.1655779948214@mail.yahoo.com> This leads to the extremely important question of what would an implementation of Python,?written completely in C++, be called? C++Python CPython++ C+Python+ DPython SeaPython? SeeSeaSiPython I don't even want to think fo what sound a C# Python would make. OK, my apologies to all. Being an interpreted language, it makes sense for a good part of the interpreter to include parts made in other languages and also add-on libraries in even older languages like FORTRAN.? Quite a few languages, including some like R, are also partially based on C in similar ways.? -----Original Message----- From: Paulo da Silva To: python-list at python.org Sent: Mon, Jun 20, 2022 8:53 pm Subject: Re: "CPython" ?s 20:01 de 20/06/22, Paulo da Silva escreveu: > ?s 18:19 de 20/06/22, Stefan Ram escreveu: >> ?? The same personality traits that make people react >> ?? to troll postings might make them spread unconfirmed >> ?? ideas about the meaning of "C" in "CPython". >> >> ?? The /core/ of CPython is written in C. >> >> ?? CPython is the /canonical/ implementation of Python. >> >> ?? The "C" in "CPython" stands for C. >> >> > > Not so "unconfirmed"! > Look at this article, I recently read: > https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ > > > There is a sentence in ther that begins with "CPython, short for Core > Python, a reference implementation that other Python distributions are > derived from, ...". > > Anyway, I wrote "IMHO". > > Do you have any credible reference to your assertion "The "C" in > "CPython" stands for C."? > > Thank you. Well ... I read the responses and they are not touching the point! I just answered, with my opinion based on articles I have read in the past. Certainly I could not be sure. That's why I responded as an opinion (IMHO) and not as an assertion. Stefan Ram responded with a, at least, not very polite post. That's why I needed to somehow "defend" why I posted that response, and, BTW, trying to learn why he said that the C in CPython means "written in C". I still find very strange, to not say weird, that a compiler or interpreter has a name based in the language it was written. But, again, is just my opinion and nothing more. I rest my case. Thank you all. -- https://mail.python.org/mailman/listinfo/python-list From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Mon Jun 20 22:38:14 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Tue, 21 Jun 2022 03:38:14 +0100 Subject: "CPython" References: Message-ID: ?s 02:33 de 21/06/22, Chris Angelico escreveu: > On Tue, 21 Jun 2022 at 11:13, Paulo da Silva > wrote: >> >> ?s 20:01 de 20/06/22, Paulo da Silva escreveu: >>> ?s 18:19 de 20/06/22, Stefan Ram escreveu: >>>> The same personality traits that make people react >>>> to troll postings might make them spread unconfirmed >>>> ideas about the meaning of "C" in "CPython". >>>> >>>> The /core/ of CPython is written in C. >>>> >>>> CPython is the /canonical/ implementation of Python. >>>> >>>> The "C" in "CPython" stands for C. >>>> >>>> >>> >>> Not so "unconfirmed"! >>> Look at this article, I recently read: >>> https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ >>> >>> >>> There is a sentence in ther that begins with "CPython, short for Core >>> Python, a reference implementation that other Python distributions are >>> derived from, ...". >>> >>> Anyway, I wrote "IMHO". >>> >>> Do you have any credible reference to your assertion "The "C" in >>> "CPython" stands for C."? >>> >>> Thank you. >> >> Well ... I read the responses and they are not touching the point! >> I just answered, with my opinion based on articles I have read in the >> past. Certainly I could not be sure. That's why I responded as an >> opinion (IMHO) and not as an assertion. >> Stefan Ram responded with a, at least, not very polite post. >> That's why I needed to somehow "defend" why I posted that response, and, >> BTW, trying to learn why he said that the C in CPython means "written in C". >> >> I still find very strange, to not say weird, that a compiler or >> interpreter has a name based in the language it was written. But, again, >> is just my opinion and nothing more. >> > > Not sure why it's strange. The point is to distinguish "CPython" from > "Jython" or "Brython" or "PyPy" or any of the other implementations. Notice that they are, for example, Jython and not JPython. There is also Cython that is a different thing. And YES. You have the right to not feel that as strange. Regards Paulo From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Mon Jun 20 22:56:07 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Tue, 21 Jun 2022 03:56:07 +0100 Subject: "CPython" References: Message-ID: ?s 03:20 de 21/06/22, MRAB escreveu: > On 2022-06-21 02:33, Chris Angelico wrote: >> On Tue, 21 Jun 2022 at 11:13, Paulo da Silva >> wrote: >>> >>> ?s 20:01 de 20/06/22, Paulo da Silva escreveu: >>> > ?s 18:19 de 20/06/22, Stefan Ram escreveu: >>> >>??? The same personality traits that make people react >>> >>??? to troll postings might make them spread unconfirmed >>> >>??? ideas about the meaning of "C" in "CPython". >>> >> >>> >>??? The /core/ of CPython is written in C. >>> >> >>> >>??? CPython is the /canonical/ implementation of Python. >>> >> >>> >>??? The "C" in "CPython" stands for C. >>> >> >>> >> >>> > >>> > Not so "unconfirmed"! >>> > Look at this article, I recently read: >>> > >>> https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ >>> >>> > >>> > >>> > There is a sentence in ther that begins with "CPython, short for Core >>> > Python, a reference implementation that other Python distributions are >>> > derived from, ...". >>> > >>> > Anyway, I wrote "IMHO". >>> > >>> > Do you have any credible reference to your assertion "The "C" in >>> > "CPython" stands for C."? >>> > >>> > Thank you. >>> >>> Well ... I read the responses and they are not touching the point! >>> I just answered, with my opinion based on articles I have read in the >>> past. Certainly I could not be sure. That's why I responded as an >>> opinion (IMHO) and not as an assertion. >>> Stefan Ram responded with a, at least, not very polite post. >>> That's why I needed to somehow "defend" why I posted that response, and, >>> BTW, trying to learn why he said that the C in CPython means "written >>> in C". >>> >>> I still find very strange, to not say weird, that a compiler or >>> interpreter has a name based in the language it was written. But, again, >>> is just my opinion and nothing more. >>> >> >> Not sure why it's strange. The point is to distinguish "CPython" from >> "Jython" or "Brython" or "PyPy" or any of the other implementations. >> Yes, CPython has a special place because it's the reference >> implementation and the most popular, but the one thing that makes it >> distinct from all the others is that it's implemented in C. >> > And just to make it clear, the interpreter/compiler _itself_ is still > called "python". "CPython" is a name/term that was applied retroactively > to that particular implementation when another implementation appeared. Yes, but that does not necessarily means that the C has to refer to the language of implementation. It may well be a "core" reference to distinguish that implementation from others with different behaviors. Let's say they reimplement "reference python" CPython in Rust. What is better? Change the "reference python" CPython name to RPython, for example, or let it as CPython? It's my opinion that it should stay as CPython. After all who cares in which language it is implemented? Regards. Paulo From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Tue Jun 21 00:29:52 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Tue, 21 Jun 2022 05:29:52 +0100 Subject: Subtract n months from datetime Message-ID: Hi! I implemented a part of a script to subtract n months from datetime. Basically I subtracted n%12 from year and n//12 from the month adding 12 months when it goes<=0. Then used try when converting to datetime again. So, if the day is for example 31 for a 30 days month it raises a ValuError exception. Then I subtract 1 to day and repeat. The code seems too naive and very very complicated! What is the best way to achieve this? Any existent module? At the very end, what I want is to subtract nx where x can be y, m, w, d for respectively years, months, weeks or days. I feel I am missing something here ... Thanks. Paulo From pbryan at anode.ca Tue Jun 21 00:44:48 2022 From: pbryan at anode.ca (Paul Bryan) Date: Mon, 20 Jun 2022 21:44:48 -0700 Subject: Subtract n months from datetime In-Reply-To: References: Message-ID: <78f4b51d7a7b3fbe68032724f607a1038d03a32b.camel@anode.ca> Here's how my code does it: import calendar def add_months(value: date, n: int): ? """Return a date value with n months added (or subtracted if negative).""" ? year = value.year + (value.month - 1 + n) // 12 ? month = (value.month - 1 + n) % 12 + 1 ? day = min(value.day, calendar.monthrange(year, month)[1]) ? return date(year, month, day) Paul On Tue, 2022-06-21 at 05:29 +0100, Paulo da Silva wrote: > Hi! > > I implemented a part of a script to subtract n months from datetime. > Basically I subtracted n%12 from year and n//12 from the month adding > 12 > months when it goes<=0. Then used try when converting to datetime > again. > So, if the day is for example 31 for a 30 days month it raises a > ValuError exception. Then I subtract 1 to day and repeat. > > The code seems too naive and very very complicated! > What is the best way to achieve this? Any existent module? > > At the very end, what I want is to subtract nx where x can be y, m, > w, d > for respectively years, months, weeks or days. > > I feel I am missing something here ... > > Thanks. > Paulo > From rosuav at gmail.com Tue Jun 21 01:12:08 2022 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 21 Jun 2022 15:12:08 +1000 Subject: "CPython" In-Reply-To: <1925863570.3590960.1655779948214@mail.yahoo.com> References: <1925863570.3590960.1655779948214@mail.yahoo.com> Message-ID: On Tue, 21 Jun 2022 at 12:53, Avi Gross via Python-list wrote: > > I don't even want to think fo what sound a C# Python would make. Probably about 277 Hz... ChrisA From rosuav at gmail.com Tue Jun 21 01:15:31 2022 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 21 Jun 2022 15:15:31 +1000 Subject: "CPython" In-Reply-To: References: Message-ID: On Tue, 21 Jun 2022 at 13:12, Paulo da Silva wrote: > > ?s 03:20 de 21/06/22, MRAB escreveu: > > On 2022-06-21 02:33, Chris Angelico wrote: > >> On Tue, 21 Jun 2022 at 11:13, Paulo da Silva > >> wrote: > >>> > >>> ?s 20:01 de 20/06/22, Paulo da Silva escreveu: > >>> > ?s 18:19 de 20/06/22, Stefan Ram escreveu: > >>> >> The same personality traits that make people react > >>> >> to troll postings might make them spread unconfirmed > >>> >> ideas about the meaning of "C" in "CPython". > >>> >> > >>> >> The /core/ of CPython is written in C. > >>> >> > >>> >> CPython is the /canonical/ implementation of Python. > >>> >> > >>> >> The "C" in "CPython" stands for C. > >>> >> > >>> >> > >>> > > >>> > Not so "unconfirmed"! > >>> > Look at this article, I recently read: > >>> > > >>> https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ > >>> > >>> > > >>> > > >>> > There is a sentence in ther that begins with "CPython, short for Core > >>> > Python, a reference implementation that other Python distributions are > >>> > derived from, ...". > >>> > > >>> > Anyway, I wrote "IMHO". > >>> > > >>> > Do you have any credible reference to your assertion "The "C" in > >>> > "CPython" stands for C."? > >>> > > >>> > Thank you. > >>> > >>> Well ... I read the responses and they are not touching the point! > >>> I just answered, with my opinion based on articles I have read in the > >>> past. Certainly I could not be sure. That's why I responded as an > >>> opinion (IMHO) and not as an assertion. > >>> Stefan Ram responded with a, at least, not very polite post. > >>> That's why I needed to somehow "defend" why I posted that response, and, > >>> BTW, trying to learn why he said that the C in CPython means "written > >>> in C". > >>> > >>> I still find very strange, to not say weird, that a compiler or > >>> interpreter has a name based in the language it was written. But, again, > >>> is just my opinion and nothing more. > >>> > >> > >> Not sure why it's strange. The point is to distinguish "CPython" from > >> "Jython" or "Brython" or "PyPy" or any of the other implementations. > >> Yes, CPython has a special place because it's the reference > >> implementation and the most popular, but the one thing that makes it > >> distinct from all the others is that it's implemented in C. > >> > > And just to make it clear, the interpreter/compiler _itself_ is still > > called "python". "CPython" is a name/term that was applied retroactively > > to that particular implementation when another implementation appeared. > Yes, but that does not necessarily means that the C has to refer to the > language of implementation. It may well be a "core" reference to > distinguish that implementation from others with different behaviors. > > Let's say they reimplement "reference python" CPython in Rust. What is > better? Change the "reference python" CPython name to RPython, for > example, or let it as CPython? > It's my opinion that it should stay as CPython. > After all who cares in which language it is implemented? > It is HIGHLY unlikely that the reference implementation would change overnight. Far far more likely, if the reference implementation were to change, would be that the new interpreter is built for a number of years as an alternative, and then eventually becomes the more popular implementation, and finally, the core devs begin using that more than CPython, and perhaps deprecating CPython altogether. If that were to happen, the other implementation would have its own name for all those years, and would keep it after being promoted to reference implementation. Also, "PyPy" is a perfectly fine name and doesn't need to be changed. ChrisA From bouncingcats at gmail.com Tue Jun 21 06:32:51 2022 From: bouncingcats at gmail.com (David) Date: Tue, 21 Jun 2022 20:32:51 +1000 Subject: Tkinter - cannot import tklib In-Reply-To: <8f6bca67-0a9c-47b1-aab8-e021ec527c4en@googlegroups.com> References: <8f6bca67-0a9c-47b1-aab8-e021ec527c4en@googlegroups.com> Message-ID: On Tue, 21 Jun 2022 at 09:22, Wolfgang Grafen wrote: > I am an experienced Python user and struggle with following statement: > > >>> from tklib import * > Traceback (most recent call last): > File "", line 1, in > ModuleNotFoundError: No module named 'tklib' [...] > I did not find a python module called tklib to install. Ok, see below for how to find that file. [...] > I assume it should be installed by default with every python installation It appears that your assumption is wrong. It appears to me that the missing file is part of the tk-tutorial project. > https://tk-tutorial.readthedocs.io/en/latest/intro/intro.html?highlight=app# > First time that I cannot help myself. Please help, what do I do wrong? Hi, here is a description how I found the file you seek: Go to https://tk-tutorial.readthedocs.io/en/latest/intro/intro.html At the top right of the page, see hyperlink "Edit on GitHub". Click hyperlink takes you to https://github.com/rasql/tk-tutorial/blob/master/docs/intro/intro.rst which is the same content rendered from 'rst' format I assume. At top left of that page, see hyperlinks "tk-tutorial"/"docs"/"intro" and "rasql"/"tk-tutorial". Click one of the "tk-tutorial" hyperlinks to go to the top directory of the project at: https://github.com/rasql/tk-tutorial On that page near the very top, see a list of hyperlinks to directories and files of the project. One of those hyperlinks is labelled "tklib.py". Click that link to see the file at https://github.com/rasql/tk-tutorial/blob/master/tklib.py On that page, click the "Raw" button. Then you can use "save as" in your browser. Or you can just download it by some other method from the link given in the previous paragraph. From Richard at Damon-Family.org Tue Jun 21 07:59:59 2022 From: Richard at Damon-Family.org (Richard Damon) Date: Tue, 21 Jun 2022 07:59:59 -0400 Subject: Subtract n months from datetime In-Reply-To: References: Message-ID: On 6/21/22 12:29 AM, Paulo da Silva wrote: > Hi! > > I implemented a part of a script to subtract n months from datetime. > Basically I subtracted n%12 from year and n//12 from the month adding > 12 months when it goes<=0. Then used try when converting to datetime > again. So, if the day is for example 31 for a 30 days month it raises > a ValuError exception. Then I subtract 1 to day and repeat. > > The code seems too naive and very very complicated! > What is the best way to achieve this? Any existent module? > > At the very end, what I want is to subtract nx where x can be y, m, w, > d for respectively years, months, weeks or days. > > I feel I am missing something here ... > > Thanks. > Paulo > The biggest issue with "subtracting months" is getting the right definition of what you mean by that, especially in the corner cases, once that is established, programming it is fairly easy. The problem is that a month isn't a fixed unit of time, but is a period anywhere from 28 to 31 days. (you get the same problem for years, but the difference is more special case, the presence or absent of Feb 29th.) The normal definition of this operation has the strange property that if you subtract a month, then add a month, you sometimes don't get back to the same day as you started with. Also subtracting one month, and then subtracting another month might get you a different day than subtracting 2 months at once (Think of Mar 31st). In short, this sort of date operation IS hard, and application specific, so while there may be pre-built modules that have this operation, you need to see if it uses a compatible definition of what you want. One alternative, which breaks other expectations, is to think of a month as 30 or 30.5 (so 2 months are 61 days) days, and add that. It says that often a month later than a given day isn't the same day of the month, but does make some operations less surprising. (This is hard to do to a date expressed as year-month-day, but trivial in some other formats like a timestamp.) -- Richard Damon From grant.b.edwards at gmail.com Tue Jun 21 09:09:02 2022 From: grant.b.edwards at gmail.com (Grant Edwards) Date: Tue, 21 Jun 2022 06:09:02 -0700 (PDT) Subject: "CPython" References: Message-ID: <62b1c2ee.1c69fb81.d310e.7eaf@mx.google.com> On 2022-06-21, Chris Angelico wrote: > Not sure why it's strange. The point is to distinguish "CPython" from > "Jython" or "Brython" or "PyPy" or any of the other implementations. > Yes, CPython has a special place because it's the reference > implementation and the most popular, but the one thing that makes it > distinct from all the others is that it's implemented in C. I've been using CPython (and reading this list) for over 20 years, and there's no doubt in my mind that the C in CPython has always been interpreted by 99+ percent of the Python community as meaning the implementation language. Sort of like ckermit was the original implementation of Kermit written in C. At the time, the other popular implementations (for DOS, IBM, etc.) were written in assembly. -- Grant From eryksun at gmail.com Tue Jun 21 09:21:04 2022 From: eryksun at gmail.com (Eryk Sun) Date: Tue, 21 Jun 2022 08:21:04 -0500 Subject: "CPython" In-Reply-To: References: Message-ID: On 6/20/22, Paulo da Silva wrote: > > Yes, but that does not necessarily means that the C has to refer to the > language of implementation. It may well be a "core" reference to > distinguish that implementation from others with different behaviors. If the reference implementation and API ever switched to a different programming language, I'd personally be fine with changing the 'C" in "CPython" to mean "canonical", but not "core". The term "core" is used for building the interpreter core with access to internals (i.e. Py_BUILD_CORE, Py_BUILD_CORE_BUILTIN, Py_BUILD_CORE_MODULE, and Include/internal/pycore*.h). It does not refer to the overall implementation and API for embedding and extension modules. From drsalists at gmail.com Tue Jun 21 10:06:15 2022 From: drsalists at gmail.com (Dan Stromberg) Date: Tue, 21 Jun 2022 07:06:15 -0700 Subject: Subtract n months from datetime In-Reply-To: <78f4b51d7a7b3fbe68032724f607a1038d03a32b.camel@anode.ca> References: <78f4b51d7a7b3fbe68032724f607a1038d03a32b.camel@anode.ca> Message-ID: On Mon, Jun 20, 2022 at 9:45 PM Paul Bryan wrote: > Here's how my code does it: > > > import calendar > > def add_months(value: date, n: int): > """Return a date value with n months added (or subtracted if > negative).""" > year = value.year + (value.month - 1 + n) // 12 > month = (value.month - 1 + n) % 12 + 1 > day = min(value.day, calendar.monthrange(year, month)[1]) > return date(year, month, day) > This looks interesting. You also could add or subtract the average number of seconds in a month: 2629743.75 This has the strange property that the time of day, or even calendar day, could change. However, it is round-trippable. From greg.ewing at canterbury.ac.nz Tue Jun 21 03:48:20 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Tue, 21 Jun 2022 19:48:20 +1200 Subject: "CPython" In-Reply-To: References: Message-ID: On 21/06/22 2:38 pm, Paulo da Silva wrote: > Notice that they are, for example, Jython and not JPython. Jython *was* originally called JPython, but that was judged to be a trademark violation and they were made to change it. I don't know how MicroPython has escaped the same fate to date. -- Greg From greg.ewing at canterbury.ac.nz Tue Jun 21 03:49:30 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Tue, 21 Jun 2022 19:49:30 +1200 Subject: "CPython" In-Reply-To: References: <1925863570.3590960.1655779948214@mail.yahoo.com> Message-ID: On 21/06/22 2:52 pm, Avi Gross wrote: > > This leads to the extremely important question of what would an implementation of Python,?written completely in C++, be called? (Pronounced with a comical stutter) "C-p-p-python!") -- Greg From greg.ewing at canterbury.ac.nz Tue Jun 21 03:53:51 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Tue, 21 Jun 2022 19:53:51 +1200 Subject: "CPython" In-Reply-To: References: Message-ID: On 21/06/22 2:56 pm, Paulo da Silva wrote: > Let's say they reimplement "reference python" CPython in Rust. What is > better? Change the "reference python" CPython name to RPython, for > example, or let it as CPython? The C implementation would still be called CPython, and the new implementation might be called RPython, or RustyPython, or whatever. The names are independent of which one is currently blessed as the reference implementation. Although if it were called RPython, no doubt a new debate would flare up over whether the "R" stands for "Rust" or "Reference"... -- Greg From nospam at please.ty Tue Jun 21 04:11:36 2022 From: nospam at please.ty (jak) Date: Tue, 21 Jun 2022 10:11:36 +0200 Subject: "CPython" References: Message-ID: Il 21/06/2022 04:56, Paulo da Silva ha scritto: > ?s 03:20 de 21/06/22, MRAB escreveu: >> On 2022-06-21 02:33, Chris Angelico wrote: >>> On Tue, 21 Jun 2022 at 11:13, Paulo da Silva >>> wrote: >>>> >>>> ?s 20:01 de 20/06/22, Paulo da Silva escreveu: >>>> > ?s 18:19 de 20/06/22, Stefan Ram escreveu: [snip] > After all who cares in which language it is implemented? > > Regards. > Paulo Why are you asking this? The Facebook platform which is mainly developed in Rust are converting it to C to make it faster and lighter. If as often happens, many people complain about the speed of python, what would be the purpose of translating python using a slower language? From auriocus at gmx.de Tue Jun 21 04:37:50 2022 From: auriocus at gmx.de (Christian Gollwitzer) Date: Tue, 21 Jun 2022 09:37:50 +0100 Subject: "CPython" In-Reply-To: References: <37cf47f6-3121-846c-f734-e3784b0581a4@roelschroeven.net> Message-ID: Am 20.06.22 um 22:47 schrieb Roel Schroeven: > indication that www.analyticsinsight.net is wrong on that point. Frankly > that website seems very low quality in general. In that same article > they say: > > "CPython is a descendant of Pyscript built on Pyodide, a port of > CPython, or a Python distribution for the browser and Node.js that is > based on Webassembly and Emscripten." > > CPython is definitely not a descendant of Pyscript! Looks like someone > found something (semi-) interesting and tried to write something > insightful about it, but without really understanding any of it. Other > articles don't seem to be any better. To me, this sentence is so badly cobbled together that it could be the output of a KI of some sort (GPT-3) trying to summarize stuff from the web. It doesn't make any sense at all on a semantic level. Christian From chethu.kumar88 at gmail.com Tue Jun 21 05:04:52 2022 From: chethu.kumar88 at gmail.com (Chethan Kumar S) Date: Tue, 21 Jun 2022 02:04:52 -0700 (PDT) Subject: Logging into single file from multiple modules in python when TimedRotatingFileHandler is used Message-ID: <35c0eaa7-b299-4e5b-a409-1daf10bbc0f8n@googlegroups.com> Hi all, Need help with below query on python logging module. I have a main process which makes use of different other modules. And these modules also use other modules. I need to log all the logs into single log file. Due to use of TimedRotatingFileHandler, my log behaves differently after midnight. I got to know why it is so but couldn't get how I can solve it. Issue was because of serialization in logging when multiple processes are involved. Below is log_config.py which is used by all other modules to get the logger and log. import logging import sys from logging.handlers import TimedRotatingFileHandler FORMATTER = logging.Formatter("%(asctime)s ? %(name)s ? %(message)s") LOG_FILE = "my_app.log" def get_file_handler(): file_handler = TimedRotatingFileHandler(LOG_FILE, when='midnight') file_handler.setFormatter(FORMATTER) return file_handler def get_logger(logger_name): logger = logging.getLogger(logger_name) logger.setLevel(logging.DEBUG) # better to have too much log than not enough logger.addHandler(get_file_handler()) #with this pattern, it's rarely necessary to propagate the error up to parent logger.propagate = False return logger All other modules call, 'logging = log_config.get_logger(name)' and use it to log. I came to know about QueueHandler and QueueListener but not sure how to use them in my code. How can I use these to serialize logs to single file.? Any help is appreciated. Thanks, Chethan From greg.ewing at canterbury.ac.nz Tue Jun 21 05:11:16 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Tue, 21 Jun 2022 21:11:16 +1200 Subject: "CPython" In-Reply-To: References: <37cf47f6-3121-846c-f734-e3784b0581a4@roelschroeven.net> Message-ID: On 21/06/22 8:37 pm, Christian Gollwitzer wrote: > Am 20.06.22 um 22:47 schrieb Roel Schroeven: >> "CPython is a descendant of Pyscript built on Pyodide, a port of >> CPython, or a Python distribution for the browser and Node.js that is >> based on Webassembly and Emscripten." >> > To me, this sentence is so badly cobbled together that it could be the > output of a KI of some sort (GPT-3) trying to summarize stuff from the > web. It looks to me like the output of a Markov chain that's been fed with all the latest programming buzzwords. -- Greg From kagushdsty at gmail.com Tue Jun 21 07:22:29 2022 From: kagushdsty at gmail.com (Brian Karinga) Date: Tue, 21 Jun 2022 14:22:29 +0300 Subject: Python installation Message-ID: Hello, I hope this email finds you well. I have been trying to download and install the latest version of python on my windows device. However, when I run the program, three options arise. These are: Modify Repair Uninstall I have executed the modify and repair options several times but nothing has changed. Please advise on what the problem could be and how it can be resolved. I look forward to hearing from you. Thank you, Brian. From wlfraed at ix.netcom.com Tue Jun 21 08:29:43 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 21 Jun 2022 08:29:43 -0400 Subject: "CPython" References: Message-ID: On Tue, 21 Jun 2022 01:53:38 +0100, Paulo da Silva declaimed the following: >I still find very strange, to not say weird, that a compiler or >interpreter has a name based in the language it was written. But, again, >is just my opinion and nothing more. > The whole purpose for that was to differentiate from Python /language/ implemented in OTHER languages. IronPython is a M$ .NET/C# implementation, Jython is a JVM/Java implementation. When you just say "Python" you are referring to ALL of those implementations. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From greg.ewing at canterbury.ac.nz Tue Jun 21 08:31:38 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Wed, 22 Jun 2022 00:31:38 +1200 Subject: "CPython" In-Reply-To: <87y1xql62k.fsf@nightsong.com> References: <87y1xql62k.fsf@nightsong.com> Message-ID: On 21/06/22 9:27 pm, Paul Rubin wrote: > What? I never heard of such a dispute. The PSF got after someone about > it? Sheesh. Upon further research, it seems it wasn't the *Python* trademark that was at issue. From the Jython FAQ page: 1.2 How does Jython relate to JPython? Jython is the successor to JPython. The Jython project was created in accordance with the CNRI JPython 1.1.x license, in order to ensure the continued existence and development of this important piece of Python software. The intent is to manage this project with the same open policies that are serving CPython so well. The name had to be changed to something other than JPython, because of paragraph 4 in the JPython-1.1 license: 4. Licensee may not use CNRI trademarks or trade name, including JPython [...] to endorse or promote products [...] So there was no dispute, they were just following the terms of a licence. -- Greg From wlfraed at ix.netcom.com Tue Jun 21 08:34:26 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 21 Jun 2022 08:34:26 -0400 Subject: "CPython" References: Message-ID: On Tue, 21 Jun 2022 19:53:51 +1200, Greg Ewing declaimed the following: >Although if it were called RPython, no doubt a new debate would >flare up over whether the "R" stands for "Rust" or "Reference"... Or does RPython refer to a Python integrated into the R statistics system? Actually -- RPython is already taken... https://rpython.readthedocs.io/en/latest/ """ RPython is a translation and support framework for producing implementations of dynamic languages, emphasizing a clean separation between language specification and implementation aspects. By separating concerns in this way, our implementation of Python - and other dynamic languages - is able to automatically generate a Just-in-Time compiler for any dynamic language. It also allows a mix-and-match approach to implementation decisions, including many that have historically been outside of a user?s control, such as target platform, memory and threading models, garbage collection strategies, and optimizations applied, including whether or not to have a JIT in the first place. """ -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From wlfraed at ix.netcom.com Tue Jun 21 08:36:53 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 21 Jun 2022 08:36:53 -0400 Subject: "CPython" References: <1925863570.3590960.1655779948214@mail.yahoo.com> Message-ID: tOn Tue, 21 Jun 2022 02:52:28 +0000 (UTC), Avi Gross declaimed the following: > >I don't even want to think fo what sound a C# Python would make. A musical hiss on a frequency of 277.183Hz (for the C# above middle-C) -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Tue Jun 21 12:02:24 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Tue, 21 Jun 2022 17:02:24 +0100 Subject: Subtract n months from datetime References: <78f4b51d7a7b3fbe68032724f607a1038d03a32b.camel@anode.ca> Message-ID: ?s 05:44 de 21/06/22, Paul Bryan escreveu: > Here's how my code does it: > > > import calendar > > def add_months(value: date, n: int): > ? """Return a date value with n months added (or subtracted if > negative).""" > ? year = value.year + (value.month - 1 + n) // 12 > ? month = (value.month - 1 + n) % 12 + 1 > ? day = min(value.day, calendar.monthrange(year, month)[1]) > ? return date(year, month, day) > > Paul I have a datetime, not a date. Anyway, the use of calendar.monthrange simplifies the task a lot. Assuming dtnow has the current datetime and dtn the number of months to be subtracted, here is my solution (the code was not cleaned yet - just a test): dtnow_t=list(dtnow.timetuple()[:6]+(dtnow.microsecond,)) y=dtnow_t[0] # y,m,d,*_=dtnow_t seems slower m=dtnow_t[1] d=dtnow_t[2] dy,dm=divmod(dtn,12) y-=dy m-=dm if m<1: m+=12 y-=1 daysinmonth=calendar.monthrange(y,m)[1] d=min(d,daysinmonth) dtnow_t[0]=y dtnow_t[1]=m dtnow_t[2]=d bt=datetime.datetime(*dtnow_t) Any comments are welcome. Thank you. Paulo > > On Tue, 2022-06-21 at 05:29 +0100, Paulo da Silva wrote: >> Hi! >> >> I implemented a part of a script to subtract n months from datetime. >> Basically I subtracted n%12 from year and n//12 from the month adding >> 12 >> months when it goes<=0. Then used try when converting to datetime >> again. >> So, if the day is for example 31 for a 30 days month it raises a >> ValuError exception. Then I subtract 1 to day and repeat. >> >> The code seems too naive and very very complicated! >> What is the best way to achieve this? Any existent module? >> >> At the very end, what I want is to subtract nx where x can be y, m, >> w, d >> for respectively years, months, weeks or days. >> >> I feel I am missing something here ... >> >> Thanks. >> Paulo >> > From dieter at handshake.de Tue Jun 21 12:11:00 2022 From: dieter at handshake.de (Dieter Maurer) Date: Tue, 21 Jun 2022 18:11:00 +0200 Subject: traceback Shows path to my python libraries In-Reply-To: <004301d884d6$7acde010$7069a030$@sbcglobal.net> References: <004301d884d6$7acde010$7069a030$.ref@sbcglobal.net> <004301d884d6$7acde010$7069a030$@sbcglobal.net> Message-ID: <25265.60820.914077.850136@ixdm.fritz.box> jschwar at sbcglobal.net wrote at 2022-6-20 13:49 -0500: >I coded an application with a 64-bit executable using cython with the embed >option and gcc and I received a traceback showing the path to my python >installation. Is that normal or does that mean the application is going >outside of my executable to my python libraries? I want it portable so it >if is, then it's not portable. The tracebacks are primarily for the developers. Therefore, they identify source locations. When you use `cython`, the compilation to "C" gets references to the `cython` source (because those references are meaningful for the developers). When a traceback is generated, the `cython` source need not be available (you will then not see the source line, only the line number and file information). From python at mrabarnett.plus.com Tue Jun 21 12:42:09 2022 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 21 Jun 2022 17:42:09 +0100 Subject: "CPython" In-Reply-To: <1925863570.3590960.1655779948214@mail.yahoo.com> References: <1925863570.3590960.1655779948214@mail.yahoo.com> Message-ID: On 2022-06-21 03:52, Avi Gross via Python-list wrote: > > This leads to the extremely important question of what would an implementation of Python,?written completely in C++, be called? > C++Python > CPython++ > C+Python+ > DPython > SeaPython? > SeeSeaSiPython > CincPython? FYI, there's a language called D, so DPython would be written in that. > I don't even want to think fo what sound a C# Python would make. > OK, my apologies to all. Being an interpreted language, it makes sense for a good part of the interpreter to include parts made in other languages and also add-on libraries in even older languages like FORTRAN.? Quite a few languages, including some like R, are also partially based on C in similar ways. [snip] From python at mrabarnett.plus.com Tue Jun 21 12:44:51 2022 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 21 Jun 2022 17:44:51 +0100 Subject: "CPython" In-Reply-To: References: Message-ID: <8a8f46f4-923a-c698-536c-ad430234939d@mrabarnett.plus.com> On 2022-06-21 03:38, Paulo da Silva wrote: > ?s 02:33 de 21/06/22, Chris Angelico escreveu: >> On Tue, 21 Jun 2022 at 11:13, Paulo da Silva >> wrote: >>> >>> ?s 20:01 de 20/06/22, Paulo da Silva escreveu: >>>> ?s 18:19 de 20/06/22, Stefan Ram escreveu: >>>>> The same personality traits that make people react >>>>> to troll postings might make them spread unconfirmed >>>>> ideas about the meaning of "C" in "CPython". >>>>> >>>>> The /core/ of CPython is written in C. >>>>> >>>>> CPython is the /canonical/ implementation of Python. >>>>> >>>>> The "C" in "CPython" stands for C. >>>>> >>>>> >>>> >>>> Not so "unconfirmed"! >>>> Look at this article, I recently read: >>>> https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ >>>> >>>> >>>> There is a sentence in ther that begins with "CPython, short for Core >>>> Python, a reference implementation that other Python distributions are >>>> derived from, ...". >>>> >>>> Anyway, I wrote "IMHO". >>>> >>>> Do you have any credible reference to your assertion "The "C" in >>>> "CPython" stands for C."? >>>> >>>> Thank you. >>> >>> Well ... I read the responses and they are not touching the point! >>> I just answered, with my opinion based on articles I have read in the >>> past. Certainly I could not be sure. That's why I responded as an >>> opinion (IMHO) and not as an assertion. >>> Stefan Ram responded with a, at least, not very polite post. >>> That's why I needed to somehow "defend" why I posted that response, and, >>> BTW, trying to learn why he said that the C in CPython means "written in C". >>> >>> I still find very strange, to not say weird, that a compiler or >>> interpreter has a name based in the language it was written. But, again, >>> is just my opinion and nothing more. >>> >> >> Not sure why it's strange. The point is to distinguish "CPython" from >> "Jython" or "Brython" or "PyPy" or any of the other implementations. > Notice that they are, for example, Jython and not JPython. > There is also Cython that is a different thing. > > And YES. You have the right to not feel that as strange. > Jython was originally called JPython. From avigross at verizon.net Tue Jun 21 13:04:45 2022 From: avigross at verizon.net (Avi Gross) Date: Tue, 21 Jun 2022 17:04:45 +0000 (UTC) Subject: "CPython" In-Reply-To: References: Message-ID: <259173376.3747752.1655831085755@mail.yahoo.com> If we want to be humorous, RPython would obviously either be written in R, which?really is not designed well for such purposes, or would be some kind of synthesis?that already exists that allows you to run R and python code interchangeably on?sort of shared data that I sometimes do in RSTUDIO. I like the way you think Greg. I did not consider how the ++ in C++ is a bit like stuttering?and since python also starts with a P the effect would be something like C-p-p-python. My problem with that idea is, believe it or not, that it is too negative. What you?meant to be seen as a dash is a minus sign to me. And both C and C++ not only?have both a pre and post autoincrement variable using ++x and x++, they also have?autodecrement operators using a minus sign such as --x and x-- and it can get?pretty weird trying to figure out if some code is legal, let alone what it does, without?parentheses. I mean what the heck does this do? y = x++-++x The truth is that although I remember Bjarne trying to figure out a good name for his?somewhat improved language and his choice of C++ rather than D or some other gimmick,?you could argue he also removed a bit from C. But who would call a language C-- ?? Back to serious. This discussion is more about names but is it? Some of the implementations of Python are not just written in some computer language but?also in a sort of environment. Arguably some core of functionality has to be pretty much?consistent to the language definition. But each may add interesting twists on its own and?that can include the ability to easily link in code and libraries written in that language?or used in that environment. You can have different supersets of a language. And it can impact where you might use the language as one reason people may not understand?for using C is that a compiler was available for just about anywhere that either ran in that?environment or could be run on another to produce lower-level code to copy to it. It was?also possible to embed code in C that was evaluated differently in each environment for some?level of fine-tuning. Some of that may eventually have been true for other implementations but I suspect not for some?deliberately designed to fit what one party wants and with no care that it be shared elsewhere?especially as the C version was already available there. Or am I wrong? After all, others who kept improving C thought the ++ concept was best removed! -----Original Message----- From: Greg Ewing To: python-list at python.org Sent: Tue, Jun 21, 2022 3:53 am Subject: Re: "CPython" On 21/06/22 2:56 pm, Paulo da Silva wrote: > Let's say they reimplement "reference python" CPython in Rust. What is > better? Change the "reference python" CPython name to RPython, for > example, or let it as CPython? The C implementation would still be called CPython, and the new implementation might be called RPython, or RustyPython, or whatever. The names are independent of which one is currently blessed as the reference implementation. Although if it were called RPython, no doubt a new debate would flare up over whether the "R" stands for "Rust" or "Reference"... -- Greg -- https://mail.python.org/mailman/listinfo/python-list From ikorot01 at gmail.com Tue Jun 21 13:14:27 2022 From: ikorot01 at gmail.com (Igor Korot) Date: Tue, 21 Jun 2022 12:14:27 -0500 Subject: Python installation In-Reply-To: References: Message-ID: Hi, On Tue, Jun 21, 2022 at 11:43 AM Brian Karinga wrote: > > Hello, > > I hope this email finds you well. > > I have been trying to download and install the latest version of python on > my windows device. However, when I run the program, three options arise. > These are: > > Modify > Repair > Uninstall > > I have executed the modify and repair options several times but nothing has > changed. Please advise on what the problem could be and how it can be > resolved. Is it possible that Python is already installed? Open "Command Prompt" window, type python and press "Enter". What do you see on the screen? Thank you. > > I look forward to hearing from you. > > Thank you, > Brian. > -- > https://mail.python.org/mailman/listinfo/python-list From sam.z.ezeh at gmail.com Tue Jun 21 13:24:10 2022 From: sam.z.ezeh at gmail.com (Sam Ezeh) Date: Tue, 21 Jun 2022 18:24:10 +0100 Subject: Python installation In-Reply-To: References: Message-ID: Inside my Windows virtual machine only entering `py` as the command brings up the repl, if that helps. Kind Regards, Sam Ezeh On Tue, 21 Jun 2022 at 18:15, Igor Korot wrote: > > Hi, > > On Tue, Jun 21, 2022 at 11:43 AM Brian Karinga wrote: > > > > Hello, > > > > I hope this email finds you well. > > > > I have been trying to download and install the latest version of python on > > my windows device. However, when I run the program, three options arise. > > These are: > > > > Modify > > Repair > > Uninstall > > > > I have executed the modify and repair options several times but nothing has > > changed. Please advise on what the problem could be and how it can be > > resolved. > > Is it possible that Python is already installed? > > Open "Command Prompt" window, type python and press "Enter". > > What do you see on the screen? > > Thank you. > > > > > I look forward to hearing from you. > > > > Thank you, > > Brian. > > -- > > https://mail.python.org/mailman/listinfo/python-list > -- > https://mail.python.org/mailman/listinfo/python-list From 2QdxY4RzWzUUiLuE at potatochowder.com Tue Jun 21 13:24:27 2022 From: 2QdxY4RzWzUUiLuE at potatochowder.com (2QdxY4RzWzUUiLuE at potatochowder.com) Date: Tue, 21 Jun 2022 12:24:27 -0500 Subject: "CPython" In-Reply-To: <259173376.3747752.1655831085755@mail.yahoo.com> References: <259173376.3747752.1655831085755@mail.yahoo.com> Message-ID: On 2022-06-21 at 17:04:45 +0000, Avi Gross via Python-list wrote: > My problem with that idea is, believe it or not, that it is too negative. What you?meant to be seen as a dash is a minus sign to me. And both C and C++ not only?have both a pre and post autoincrement variable using ++x and x++, they also have?autodecrement operators using a minus sign such as --x and x-- and it can get?pretty weird trying to figure out if some code is legal, let alone what it does, without?parentheses. I mean what the heck does this do? > > y = x++-++x That code evokes (or at least can evoke) nasal demons. https://en.wikipedia.org/wiki/Undefined_behavior From wlfraed at ix.netcom.com Tue Jun 21 14:07:05 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 21 Jun 2022 14:07:05 -0400 Subject: Python installation References: Message-ID: On Tue, 21 Jun 2022 14:22:29 +0300, Brian Karinga declaimed the following: >I have been trying to download and install the latest version of python on >my windows device. However, when I run the program, three options arise. >These are: > >Modify >Repair >Uninstall > You are (re-)running the INSTALLER. Once you've run it, hide it away someplace and only look at it if you need to -- well -- repair or modify the installation. Python is not an IDE (it is not something like Visual Studio where one opens a massive suite of editing/debugging tools which will eventually invoke Visual C/C++/C#/BASIC compilers). It is a command line interpreter which might (depending on install setting) configure the system to use it to run files with .py (or .pyw for GUI applications where a console window is not desired... note that running a .py by clicking on it will open a console window, and that window will close when the program exits -- so that option is often useless). -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From jkn_gg at nicorp.f9.co.uk Tue Jun 21 16:22:22 2022 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Tue, 21 Jun 2022 13:22:22 -0700 (PDT) Subject: "CPython" In-Reply-To: References: <62b1c2ee.1c69fb81.d310e.7eaf@mx.google.com> Message-ID: On Tuesday, June 21, 2022 at 2:09:27 PM UTC+1, Grant Edwards wrote: > On 2022-06-21, Chris Angelico wrote: > > > Not sure why it's strange. The point is to distinguish "CPython" from > > "Jython" or "Brython" or "PyPy" or any of the other implementations. > > Yes, CPython has a special place because it's the reference > > implementation and the most popular, but the one thing that makes it > > distinct from all the others is that it's implemented in C. > I've been using CPython (and reading this list) for over 20 years, and > there's no doubt in my mind that the C in CPython has always been > interpreted by 99+ percent of the Python community as meaning the > implementation language. > > Sort of like ckermit was the original > implementation of Kermit written in C. At the time, the other popular > implementations (for DOS, IBM, etc.) were written in assembly. > Same here, on both counts (20+ years on this Usenet group, and CPython == "the canonical C implementation of Python") Actually, on all three counts - I remember ckermit as well ;-) Fourthly... J^n From cs at cskk.id.au Tue Jun 21 17:55:29 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Wed, 22 Jun 2022 07:55:29 +1000 Subject: Subtract n months from datetime In-Reply-To: References: Message-ID: On 21Jun2022 17:02, Paulo da Silva wrote: >I have a datetime, not a date. Then you need a date. I would break the datetime into a date and a time, then do the months stuff to the date, then compose a new datetime from the result. >Anyway, the use of calendar.monthrange simplifies the task a lot. Hmm, yes it would. The important thing to remember about any solutions mentioned is that dates and datetimes have different semantics. Specificly, you can't add fixed elapsed times such as seconds to do "calendar like" arithmetic, which works in days etc because months have varying numbers of days, and days have varying numbers of seconds (not merely the odd leap second but also the horrors of timezones and summer/winter time shifts). So working with the calendar component (days upwards) is a meaningful thing. But working in, say, seconds with the _bjective_ of doing days or months is nearly pointless. Cheers, Cameron Simpson From greg.ewing at canterbury.ac.nz Tue Jun 21 20:51:51 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Wed, 22 Jun 2022 12:51:51 +1200 Subject: "CPython" In-Reply-To: References: <1925863570.3590960.1655779948214@mail.yahoo.com> Message-ID: On 22/06/22 4:42 am, MRAB wrote: > On 2022-06-21 03:52, Avi Gross via Python-list wrote: >> >> This leads to the extremely important question of what would an >> implementation of Python,?written completely in C++, be called? >> C++Python >> CPython++ >> C+Python+ >> DPython >> SeaPython? >> SeeSeaSiPython >> > CincPython? Python+=1 -- Greg From lal at solute.de Wed Jun 22 06:06:57 2022 From: lal at solute.de (Lars Liedtke) Date: Wed, 22 Jun 2022 12:06:57 +0200 Subject: Logging into single file from multiple modules in python when TimedRotatingFileHandler is used In-Reply-To: <35c0eaa7-b299-4e5b-a409-1daf10bbc0f8n@googlegroups.com> References: <35c0eaa7-b299-4e5b-a409-1daf10bbc0f8n@googlegroups.com> Message-ID: <150277d2-0b68-bc1b-cf2b-5ff8ae38e890@solute.de> -- Lars Liedtke Software Entwickler Phone: Fax: +49 721 98993- E-mail: lal at solute.de solute GmbH Zeppelinstra?e 15 76185 Karlsruhe Germany Marken der solute GmbH | brands of solute GmbH billiger.de | Shopping.de Gesch?ftsf?hrer | Managing Director: Dr. Thilo Gans, Bernd Vermaaten Webseite | www.solute.de Sitz | Registered Office: Karlsruhe Registergericht | Register Court: Amtsgericht Mannheim Registernummer | Register No.: HRB 110579 USt-ID | VAT ID: DE234663798 Informationen zum Datenschutz | Information about privacy policy http://solute.de/ger/datenschutz/grundsaetze-der-datenverarbeitung.php Am 21.06.22 um 11:04 schrieb Chethan Kumar S: > I have a main process which makes use of different other modules. And these modules also use other modules. I need to log all the logs into single log file. Due to use of TimedRotatingFileHandler, my log behaves differently after midnight. I got to know why it is so but couldn't get how I can solve it. > Issue was because of serialization in logging when multiple processes are involved. Could be unrelated and only a part of a solution, but if you are on a unixoid system, you could use logrotate, instead of TimedRotatingFileHandler. logfrotate ensures that the logging service does not realize, its logs have been rotated. So it can log as if nothing has happened. I don't know, if that helps with your multiple processes, or is a solution at all. Cheers Lars From barry at barrys-emacs.org Wed Jun 22 07:06:24 2022 From: barry at barrys-emacs.org (Barry Scott) Date: Wed, 22 Jun 2022 12:06:24 +0100 Subject: Logging into single file from multiple modules in python when TimedRotatingFileHandler is used In-Reply-To: <150277d2-0b68-bc1b-cf2b-5ff8ae38e890@solute.de> References: <35c0eaa7-b299-4e5b-a409-1daf10bbc0f8n@googlegroups.com> <150277d2-0b68-bc1b-cf2b-5ff8ae38e890@solute.de> Message-ID: > On 22 Jun 2022, at 11:06, Lars Liedtke wrote: > > Could be unrelated and only a part of a solution, but if you are on a unixoid system, you could use logrotate, instead of TimedRotatingFileHandler. logfrotate ensures that the logging service does not realize, its logs have been rotated. So it can log as if nothing has happened. The process that is writing the file must be told that rotation has happened for it to work. Other wise all the logs keep being write to the original file via the FD that the process has. logrotate's config include how to tell the process the log file needs reopening. Barry From lal at solute.de Wed Jun 22 07:10:40 2022 From: lal at solute.de (Lars Liedtke) Date: Wed, 22 Jun 2022 13:10:40 +0200 Subject: Logging into single file from multiple modules in python when TimedRotatingFileHandler is used In-Reply-To: References: <35c0eaa7-b299-4e5b-a409-1daf10bbc0f8n@googlegroups.com> <150277d2-0b68-bc1b-cf2b-5ff8ae38e890@solute.de> Message-ID: <56f0cabb-fee8-dd6a-a434-6645db7a0428@solute.de> > The process that is writing the file must be told that rotation has > happened for it to work. > Other wise all the logs keep being write to the original file via the > FD that the process has. > > logrotate's config include how to tell the process the log file needs > reopening. > Thanks for clearing. -- Lars Liedtke Software Entwickler Phone: Fax: +49 721 98993- E-mail: lal at solute.de solute GmbH Zeppelinstra?e 15 76185 Karlsruhe Germany Marken der solute GmbH | brands of solute GmbH billiger.de | Shopping.de Gesch?ftsf?hrer | Managing Director: Dr. Thilo Gans, Bernd Vermaaten Webseite | www.solute.de Sitz | Registered Office: Karlsruhe Registergericht | Register Court: Amtsgericht Mannheim Registernummer | Register No.: HRB 110579 USt-ID | VAT ID: DE234663798 Informationen zum Datenschutz | Information about privacy policy http://solute.de/ger/datenschutz/grundsaetze-der-datenverarbeitung.php From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Wed Jun 22 12:59:00 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Wed, 22 Jun 2022 17:59:00 +0100 Subject: Subtract n months from datetime [Why?] References: Message-ID: ?s 05:29 de 21/06/22, Paulo da Silva escreveu: As a general response to some comments ... Suppose we need to delete records from a database older than ... Today, it's usual to specify days. For example you have to keep some gov papers for 90 days. This seems to come from computers era. In our minds, however, we immediately think 90 days=3 months. For example, one may want to delete some files older than 9 months. It's far more intuitive than 270 days. When we talk about years it is still going. For example I need to keep my receipts for 5 years because IRS audits. Accepting this, it's intuitive, for example, that 3 months before July, 31 is April, 30. The same happens for the years. 5 years before February, 29 is February, 28. Again, this is my opinion and that's the way I like it :-) Regards Paulo From python at mrabarnett.plus.com Wed Jun 22 13:48:52 2022 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 22 Jun 2022 18:48:52 +0100 Subject: Subtract n months from datetime [Why?] In-Reply-To: References: Message-ID: On 2022-06-22 17:59, Paulo da Silva wrote: > ?s 05:29 de 21/06/22, Paulo da Silva escreveu: > > As a general response to some comments ... > > Suppose we need to delete records from a database older than ... > Today, it's usual to specify days. For example you have to keep some gov > papers for 90 days. This seems to come from computers era. In our minds, > however, we immediately think 90 days=3 months. > For example, one may want to delete some files older than 9 months. It's > far more intuitive than 270 days. > When we talk about years it is still going. For example I need to keep > my receipts for 5 years because IRS audits. > Accepting this, it's intuitive, for example, that 3 months before July, > 31 is April, 30. > The same happens for the years. 5 years before February, 29 is February, 28. > > Again, this is my opinion and that's the way I like it :-) > What makes sense depends on where you're looking from. It's 28 February, you need to keep it for 5 years, therefore you could reason that you can dispose of it on 28 February, 5 years hence. However, that happens to be a leap year. Should you still have it on 29 February? From dieter at handshake.de Wed Jun 22 13:52:03 2022 From: dieter at handshake.de (Dieter Maurer) Date: Wed, 22 Jun 2022 19:52:03 +0200 Subject: Logging into single file from multiple modules in python when TimedRotatingFileHandler is used In-Reply-To: <35c0eaa7-b299-4e5b-a409-1daf10bbc0f8n@googlegroups.com> References: <35c0eaa7-b299-4e5b-a409-1daf10bbc0f8n@googlegroups.com> Message-ID: <25267.22211.234339.424277@ixdm.fritz.box> Chethan Kumar S wrote at 2022-6-21 02:04 -0700: > ... >I have a main process which makes use of different other modules. And these modules also use other modules. I need to log all the logs into single log file. Due to use of TimedRotatingFileHandler, my log behaves differently after midnight. I got to know why it is so but couldn't get how I can solve it. >Issue was because of serialization in logging when multiple processes are involved. > >Below is log_config.py which is used by all other modules to get the logger and log. >import logging >import sys >from logging.handlers import TimedRotatingFileHandler > >FORMATTER = logging.Formatter("%(asctime)s ? %(name)s ? %(message)s") The usual logging usage pattern is: the individual components decide what to log but how the logging happens it decided centrally - common for all components. This implies that usually the individual components do not handle handlers or formatters but use the configuration set up centrally. From Marco.Sulla.Python at gmail.com Wed Jun 22 14:47:37 2022 From: Marco.Sulla.Python at gmail.com (Marco Sulla) Date: Wed, 22 Jun 2022 20:47:37 +0200 Subject: Subtract n months from datetime In-Reply-To: References: Message-ID: The package arrow has a simple shift method for months, weeks etc https://arrow.readthedocs.io/en/latest/#replace-shift From barry at barrys-emacs.org Wed Jun 22 15:25:52 2022 From: barry at barrys-emacs.org (Barry Scott) Date: Wed, 22 Jun 2022 20:25:52 +0100 Subject: Subtract n months from datetime [Why?] In-Reply-To: References: Message-ID: <28DFCB16-ADEC-4ADB-BEAF-6104C849460B@barrys-emacs.org> > On 22 Jun 2022, at 17:59, Paulo da Silva wrote: > > ?s 05:29 de 21/06/22, Paulo da Silva escreveu: > > As a general response to some comments ... > > Suppose we need to delete records from a database older than ... > Today, it's usual to specify days. For example you have to keep some gov papers for 90 days. This seems to come from computers era. In our minds, however, we immediately think 90 days=3 months. > For example, one may want to delete some files older than 9 months. It's far more intuitive than 270 days. > When we talk about years it is still going. For example I need to keep my receipts for 5 years because IRS audits. > Accepting this, it's intuitive, for example, that 3 months before July, 31 is April, 30. > The same happens for the years. 5 years before February, 29 is February, 28. The advantage of 30 days, 90 days etc is that a contract or law does not need to tell you how to deal with the problems of calendar months. As you say in peoples thoughts that 1 month or 3 months etc. But an accounts department will know how to to the number of days till they have to pay up. Barry > > Again, this is my opinion and that's the way I like it :-) > Regards > Paulo > -- > https://mail.python.org/mailman/listinfo/python-list From python at mrabarnett.plus.com Wed Jun 22 16:52:02 2022 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 22 Jun 2022 21:52:02 +0100 Subject: Subtract n months from datetime [Why?] In-Reply-To: <28DFCB16-ADEC-4ADB-BEAF-6104C849460B@barrys-emacs.org> References: <28DFCB16-ADEC-4ADB-BEAF-6104C849460B@barrys-emacs.org> Message-ID: <3b5474f5-aeae-6f93-30ff-b566bd6be878@mrabarnett.plus.com> On 2022-06-22 20:25, Barry Scott wrote: > > >> On 22 Jun 2022, at 17:59, Paulo da Silva wrote: >> >> ?s 05:29 de 21/06/22, Paulo da Silva escreveu: >> >> As a general response to some comments ... >> >> Suppose we need to delete records from a database older than ... >> Today, it's usual to specify days. For example you have to keep some gov papers for 90 days. This seems to come from computers era. In our minds, however, we immediately think 90 days=3 months. >> For example, one may want to delete some files older than 9 months. It's far more intuitive than 270 days. >> When we talk about years it is still going. For example I need to keep my receipts for 5 years because IRS audits. >> Accepting this, it's intuitive, for example, that 3 months before July, 31 is April, 30. >> The same happens for the years. 5 years before February, 29 is February, 28. > > The advantage of 30 days, 90 days etc is that a contract or law does not need to tell you > how to deal with the problems of calendar months. > > As you say in peoples thoughts that 1 month or 3 months etc. But an accounts department > will know how to to the number of days till they have to pay up. > OT, but in the UK, when the Gregorian Calendar was adopted, there were complaints. It's often believed that they were just being superstitious about "losing" 11 days, but the truth is that they were complaining that rent was paid by the month, but wages by the number of days worked. That month was a lot shorter, with far fewer working days, yet they were still expected to pay the same rent! From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Wed Jun 22 20:56:10 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Thu, 23 Jun 2022 01:56:10 +0100 Subject: Subtract n months from datetime [Why?] References: <28DFCB16-ADEC-4ADB-BEAF-6104C849460B@barrys-emacs.org> Message-ID: ?s 20:25 de 22/06/22, Barry Scott escreveu: > > >> On 22 Jun 2022, at 17:59, Paulo da Silva wrote: >> >> ?s 05:29 de 21/06/22, Paulo da Silva escreveu: >> >> As a general response to some comments ... >> >> Suppose we need to delete records from a database older than ... >> Today, it's usual to specify days. For example you have to keep some gov papers for 90 days. This seems to come from computers era. In our minds, however, we immediately think 90 days=3 months. >> For example, one may want to delete some files older than 9 months. It's far more intuitive than 270 days. >> When we talk about years it is still going. For example I need to keep my receipts for 5 years because IRS audits. >> Accepting this, it's intuitive, for example, that 3 months before July, 31 is April, 30. >> The same happens for the years. 5 years before February, 29 is February, 28. > > The advantage of 30 days, 90 days etc is that a contract or law does not need to tell you > how to deal with the problems of calendar months. > > As you say in peoples thoughts that 1 month or 3 months etc. But an accounts department > will know how to to the number of days till they have to pay up. > Yes. But my point is to justify why I want months. And it depends on the application. Let's suppose a program for Joe User to clean something - files, for example. There are no rules except for the comfort of the user. He would prefer to be able to say 9 months back instead of 270 days. And by 9 months, he expects to count down 9 months. Not 270 days. That's what happens with the script I am writing. Paulo From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Wed Jun 22 21:00:16 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Thu, 23 Jun 2022 02:00:16 +0100 Subject: Subtract n months from datetime References: Message-ID: ?s 19:47 de 22/06/22, Marco Sulla escreveu: > The package arrow has a simple shift method for months, weeks etc > > https://arrow.readthedocs.io/en/latest/#replace-shift At first look it seems pretty good! I didn't know it. Thank you Marco. Paulo From Karsten.Hilbert at gmx.net Thu Jun 23 02:36:10 2022 From: Karsten.Hilbert at gmx.net (Karsten Hilbert) Date: Thu, 23 Jun 2022 08:36:10 +0200 Subject: Aw: Re: Subtract n months from datetime [Why?] In-Reply-To: References: Message-ID: > What makes sense depends on where you're looking from. > > It's 28 February, you need to keep it for 5 years, therefore you could > reason that you can dispose of it on 28 February, 5 years hence. > > However, that happens to be a leap year. > > Should you still have it on 29 February? Nope because that's *after* the 5 years (they end Feb 28). If it originates on March 1st, however, you shouldn't dispose of it on Feb 29th just yet. Karsten From ward.davidj at gmail.com Thu Jun 23 10:29:41 2022 From: ward.davidj at gmail.com (David J W) Date: Thu, 23 Jun 2022 08:29:41 -0600 Subject: "CPython" Message-ID: >> Let's say they reimplement "reference python" CPython in Rust. What is >> better? Change the "reference python" CPython name to RPython, for >> example, or let it as CPython? >The C implementation would still be called CPython, and the new >implementation might be called RPython, or RustyPython, or whatever. >The names are independent of which one is currently blessed as the >reference implementation. I am at the pre planning stages of making a Rust implementation of the Python virtual machine and to avoid ambiguity I've been working with Rython as the name. I tried looking for a Monty Python themed name but the good ones seem to be taken. Otherwise as for a timeline, solo I figure it's going to take me a couple years to get something that actually passes cpython's python unit-tests. From nsh531 at gmail.com Thu Jun 23 08:31:35 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Thu, 23 Jun 2022 15:31:35 +0300 Subject: argparse modify Message-ID: how to solve this (argparse) traceback: Traceback (most recent call last): File "u:\oracle\RTR.py", line 10, in class sre_constants(): File "u:\oracle\RTR.py", line 77, in sre_constants MAXREPEAT = _NamedIntConstant(32,name=str(32)) TypeError: 'name' is an invalid keyword argument for int() code: class sre_constants(): # # Secret Labs' Regular Expression Engine # # various symbols used by the regular expression engine. # run this script to update the _sre include files! # # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. # # See the sre.py file for information on usage and redistribution. # """Internal support module for sre""" # update when constants are added or removed MAGIC = 20171005 from _sre import MAXREPEAT, MAXGROUPS # SRE standard exception (access as sre.error) # should this really be here? class error(Exception): """Exception raised for invalid regular expressions. Attributes: msg: The unformatted error message pattern: The regular expression pattern pos: The index in the pattern where compilation failed (may be None) lineno: The line corresponding to pos (may be None) colno: The column corresponding to pos (may be None) """ __module__ = 're' def __init__(self, msg, pattern=None, pos=None): self.msg = msg self.pattern = pattern self.pos = pos if pattern is not None and pos is not None: msg = '%s at position %d' % (msg, pos) if isinstance(pattern, str): newline = '\n' else: newline = b'\n' self.lineno = pattern.count(newline, 0, pos) + 1 self.colno = pos - pattern.rfind(newline, 0, pos) if newline in pattern: msg = '%s (line %d, column %d)' % (msg, self.lineno, self.colno) else: self.lineno = self.colno = None super().__init__(msg) class _NamedIntConstant(int): def __init__(cls, value): self = super(_NamedIntConstant, cls).__init__(cls, value) self.name = name return self def __repr__(self): return self.name __reduce__ = None MAXREPEAT = _NamedIntConstant(32,name=str(32)) def _makecodes(names): names = names.strip().split() items = [_NamedIntConstant(i, name) for i, name in enumerate(names)] globals().update({item.name: item for item in items}) return items -- From pfoosion at gmail.com Thu Jun 23 09:14:57 2022 From: pfoosion at gmail.com (Richard David) Date: Thu, 23 Jun 2022 06:14:57 -0700 (PDT) Subject: 3.11.0b4? Message-ID: <5d39b504-fa96-4f6c-816a-deac31cbd6e8n@googlegroups.com> Is there a new scheduled date for releasing 3.11.0b4? Are there issues with b4 that have implications for b3? I realize it will be released when ready and am not trying to push or harass anyone involved. It just seems that versions are usually released on schedule so I'm wondering if there's some problem. From avigross at verizon.net Thu Jun 23 11:42:25 2022 From: avigross at verizon.net (Avi Gross) Date: Thu, 23 Jun 2022 15:42:25 +0000 (UTC) Subject: "CPython" In-Reply-To: References: Message-ID: <204719546.4317459.1655998945320@mail.yahoo.com> David, I am curious why you are undertaking the effort to take a language already?decades old and showing signs of being a tad rusty into a language?that suggests further oxidation. More seriously, I am interested in what this can gain and the intended user?base. I studied Rust for a while and it has it's features but have had no?opportunity to use it. Is it expected to make a faster version of Python,?or enable better connections to libraries and so on?? What I mean is that if you are planning on making it pass all tests for?python functionality, are you also adding unique features or ... ? My preference is to have names that fully include what they are about.?So the name "python" would be left intact rather than mangled, even if?the name itself happens to be totally meaningless. So may I suggest?something like """rustic-python""" ? -----Original Message----- From: David J W To: python-list at python.org Sent: Thu, Jun 23, 2022 10:29 am Subject: Re: "CPython" >> Let's say they reimplement "reference python" CPython in Rust. What is >> better? Change the "reference python" CPython name to RPython, for >> example, or let it as CPython? >The C implementation would still be called CPython, and the new >implementation might be called RPython, or RustyPython, or whatever. >The names are independent of which one is currently blessed as the >reference implementation. I am at the pre planning stages of making a Rust implementation of the Python virtual machine and to avoid ambiguity I've been working with Rython as the name.? I tried looking for a Monty Python themed name but the good ones seem to be taken. Otherwise as for a timeline, solo I figure it's going to take me a couple years to get something that actually passes cpython's python unit-tests. -- https://mail.python.org/mailman/listinfo/python-list From dieter at handshake.de Thu Jun 23 12:57:31 2022 From: dieter at handshake.de (Dieter Maurer) Date: Thu, 23 Jun 2022 18:57:31 +0200 Subject: argparse modify In-Reply-To: References: Message-ID: <25268.39803.483755.686736@ixdm.fritz.box> ??? ???? wrote at 2022-6-23 15:31 +0300: >how to solve this (argparse) > > >traceback: >Traceback (most recent call last): > File "u:\oracle\RTR.py", line 10, in > class sre_constants(): > File "u:\oracle\RTR.py", line 77, in sre_constants > MAXREPEAT = _NamedIntConstant(32,name=str(32)) >TypeError: 'name' is an invalid keyword argument for int() This does not look like an `argparse` problem: the traceback comes from `oracle/RTR.py`. From wlfraed at ix.netcom.com Thu Jun 23 18:32:34 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Thu, 23 Jun 2022 18:32:34 -0400 Subject: argparse modify References: <25268.39803.483755.686736@ixdm.fritz.box> Message-ID: On Thu, 23 Jun 2022 18:57:31 +0200, "Dieter Maurer" declaimed the following: >??? ???? wrote at 2022-6-23 15:31 +0300: >>how to solve this (argparse) >> MAXREPEAT = _NamedIntConstant(32,name=str(32)) >>TypeError: 'name' is an invalid keyword argument for int() > >This does not look like an `argparse` problem: >the traceback comes from `oracle/RTR.py`. And the listed code looks quite suspicious to me... >> class _NamedIntConstant(int): >> def __init__(cls, value): >> self = super(_NamedIntConstant, cls).__init__(cls, value) >> self.name = name >> return self There does not appear to be any provision for keyword arguments at all. The only use of "name" is to an undefined object. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From mats at wichmann.us Thu Jun 23 19:01:42 2022 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 23 Jun 2022 17:01:42 -0600 Subject: argparse modify In-Reply-To: References: <25268.39803.483755.686736@ixdm.fritz.box> Message-ID: <46893e56-1b9c-d650-5f83-17424f82d2c3@wichmann.us> On 6/23/22 16:32, Dennis Lee Bieber wrote: > On Thu, 23 Jun 2022 18:57:31 +0200, "Dieter Maurer" > declaimed the following: > >> ??? ???? wrote at 2022-6-23 15:31 +0300: >>> how to solve this (argparse) > >>> MAXREPEAT = _NamedIntConstant(32,name=str(32)) >>> TypeError: 'name' is an invalid keyword argument for int() >> >> This does not look like an `argparse` problem: >> the traceback comes from `oracle/RTR.py`. > > And the listed code looks quite suspicious to me... > >>> class _NamedIntConstant(int): >>> def __init__(cls, value): >>> self = super(_NamedIntConstant, cls).__init__(cls, value) >>> self.name = name >>> return self > > There does not appear to be any provision for keyword arguments at all. > The only use of "name" is to an undefined object. Indeed... a more typical version of this might be something like: class _NamedIntConstant(int): def __init__(self, name, **kwargs): self.name = name super().__init__(**kwargs) Assuming: that the "value" in your init method signature was supposed to be 'name' since that's what you use later - and would explain your exception! In Python init methods are initializers, not creators (despite that many materials call them constructors) - when you get to it, "self" already exists, so you don't want to assign to it. And you don't return it - again, it already exists, all you're doing here is setting it up, and part of that you delegated to the parent class's initializer. Also note that while it's claimed to be fine These Days, inheriting from a base type like this is sometimes tricky, sometimes broken... be somewhat aware. From rosuav at gmail.com Thu Jun 23 19:10:43 2022 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 24 Jun 2022 09:10:43 +1000 Subject: argparse modify In-Reply-To: <46893e56-1b9c-d650-5f83-17424f82d2c3@wichmann.us> References: <25268.39803.483755.686736@ixdm.fritz.box> <46893e56-1b9c-d650-5f83-17424f82d2c3@wichmann.us> Message-ID: On Fri, 24 Jun 2022 at 09:03, Mats Wichmann wrote: > Also note that while it's claimed to be fine These Days, inheriting from > a base type like this is sometimes tricky, sometimes broken... be > somewhat aware. Depends on your definition of "broken". If you want to make a custom integer type, you'll probably find that arithmetic operations on it just return vanilla ints again, but in this case, it seems to be more akin to IntEnum than to an arithmetic type. so it should be safe. But that said: why not just use IntEnum? It looks like the purpose of it is simply to be a name for a number, and that's something that an enum does well (even if it's not strictly "enumerated" in that sense). ChrisA From nsh531 at gmail.com Fri Jun 24 01:28:18 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Fri, 24 Jun 2022 08:28:18 +0300 Subject: argparse modify In-Reply-To: <25268.39803.483755.686736@ixdm.fritz.box> References: <25268.39803.483755.686736@ixdm.fritz.box> Message-ID: I copied code from argparse library and modified it ?????? ??? ?????, 23 ????? 2022, ??? Dieter Maurer : > ??? ???? wrote at 2022-6-23 15:31 +0300: > >how to solve this (argparse) > > > > > >traceback: > >Traceback (most recent call last): > > File "u:\oracle\RTR.py", line 10, in > > class sre_constants(): > > File "u:\oracle\RTR.py", line 77, in sre_constants > > MAXREPEAT = _NamedIntConstant(32,name=str(32)) > >TypeError: 'name' is an invalid keyword argument for int() > > This does not look like an `argparse` problem: > the traceback comes from `oracle/RTR.py`. > -- From dieter at handshake.de Fri Jun 24 01:59:39 2022 From: dieter at handshake.de (Dieter Maurer) Date: Fri, 24 Jun 2022 07:59:39 +0200 Subject: argparse modify In-Reply-To: References: <25268.39803.483755.686736@ixdm.fritz.box> Message-ID: <25269.21195.892443.191805@ixdm.fritz.box> ??? ???? wrote at 2022-6-24 08:28 +0300: >I copied code from argparse library and modified it > >?????? ??? ?????, 23 ????? 2022, ??? Dieter Maurer : > >> ??? ???? wrote at 2022-6-23 15:31 +0300: >> >how to solve this (argparse) >> > >> > >> >traceback: >> >Traceback (most recent call last): >> > File "u:\oracle\RTR.py", line 10, in >> > class sre_constants(): >> > File "u:\oracle\RTR.py", line 77, in sre_constants >> > MAXREPEAT = _NamedIntConstant(32,name=str(32)) >> >TypeError: 'name' is an invalid keyword argument for int() The exception information tells you: ` _NamedIntConstant(32,name=str(32))` raises a `TypeError`: `_NamedIntConstant` does not know the keyword parameter `name`. Thus, something is wrong with the `_NamedIntConstant` definition. From nsh531 at gmail.com Fri Jun 24 02:07:19 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Fri, 24 Jun 2022 09:07:19 +0300 Subject: Fwd: argparse modify In-Reply-To: <25269.21195.892443.191805@ixdm.fritz.box> References: <25268.39803.483755.686736@ixdm.fritz.box> <25269.21195.892443.191805@ixdm.fritz.box> Message-ID: ------------ ????? ??????? ---------- ???: *Dieter Maurer* ?????: ??? ????, 24 ????? 2022 ????: argparse modify ??: ??????? ????: "python-list-request at python.org" , " python-list at python.org" ??? ???? wrote at 2022-6-24 08:28 +0300: >I copied code from argparse library and modified it > >?????? ??? ?????, 23 ????? 2022, ??? Dieter Maurer : > >> ??? ???? wrote at 2022-6-23 15:31 +0300: >> >how to solve this (argparse) >> > >> > >> >traceback: >> >Traceback (most recent call last): >> > File "u:\oracle\RTR.py", line 10, in >> > class sre_constants(): >> > File "u:\oracle\RTR.py", line 77, in sre_constants >> > MAXREPEAT = _NamedIntConstant(32,name=str(32)) >> >TypeError: 'name' is an invalid keyword argument for int() The exception information tells you: ` _NamedIntConstant(32,name=str(32))` raises a `TypeError`: `_NamedIntConstant` does not know the keyword parameter `name`. Thus, something is wrong with the `_NamedIntConstant` definition. Do you have an idea for fixing it? -- From nsh531 at gmail.com Fri Jun 24 03:45:35 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Fri, 24 Jun 2022 10:45:35 +0300 Subject: argparse modify Message-ID: Can you help me for solve it ?????? ??? ????, 24 ????? 2022, ??? Dennis Lee Bieber : > On Thu, 23 Jun 2022 18:57:31 +0200, "Dieter Maurer" > declaimed the following: > > >??? ???? wrote at 2022-6-23 15:31 +0300: > >>how to solve this (argparse) > > >> MAXREPEAT = _NamedIntConstant(32,name=str(32)) > >>TypeError: 'name' is an invalid keyword argument for int() > > > >This does not look like an `argparse` problem: > >the traceback comes from `oracle/RTR.py`. > > And the listed code looks quite suspicious to me... > > >> class _NamedIntConstant(int): > >> def __init__(cls, value): > >> self = super(_NamedIntConstant, cls).__init__(cls, value) > >> self.name = name > >> return self > > There does not appear to be any provision for keyword arguments at > all. > The only use of "name" is to an undefined object. > > > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com http://wlfraed.microdiversity. > freeddns.org/ > -- > https://mail.python.org/mailman/listinfo/python-list > -- From nsh531 at gmail.com Fri Jun 24 04:43:19 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Fri, 24 Jun 2022 11:43:19 +0300 Subject: sre_constants MODIFIED CLASS - ERROR Message-ID: class _NamedIntConstant(int): def __new__(cls, value, name): self = super(_NamedIntConstant, cls).__new__(cls, value) self.name = name return self def __repr__(self): return self.name __reduce__ = None MAXREPEAT = _NamedIntConstant(32,name=str(32)) what's the problem with the code???? From rosuav at gmail.com Fri Jun 24 04:48:25 2022 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 24 Jun 2022 18:48:25 +1000 Subject: sre_constants MODIFIED CLASS - ERROR In-Reply-To: References: Message-ID: ?On Fri, 24 Jun 2022 at 18:43, ???? ?????? wrote:? > > class _NamedIntConstant(int): > def __new__(cls, value, name): > self = super(_NamedIntConstant, cls).__new__(cls, value) > self.name = name > return self > > def __repr__(self): > return self.name > > __reduce__ = None > MAXREPEAT = _NamedIntConstant(32,name=str(32)) > > what's the problem with the code???? You ripped a bunch of code from the standard library without understanding what it does, and now it doesn't work. The problem is more with your methodology than your code. Why are you doing this? Why not simply use what's there? If you REALLY need to make source-level changes, make *changes*, don't try to lift small parts out. Also, you will need to spend some hours getting to know the code that you're mutating. Is there an alternative newsgroup for lazy-python-users-who-dont-want-to-do-the-work at groups.google.com ? ChrisA From nsh531 at gmail.com Fri Jun 24 04:55:49 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Fri, 24 Jun 2022 11:55:49 +0300 Subject: sre_constants MODIFIED CLASS - ERROR In-Reply-To: References: Message-ID: I did the changes on local copy of this code ??????? ??? ??, 24 ????? 2022 ?-11:50 ??? ?Chris Angelico?? :? > ?On Fri, 24 Jun 2022 at 18:43, ???? ?????? wrote:? > > > > class _NamedIntConstant(int): > > def __new__(cls, value, name): > > self = super(_NamedIntConstant, cls).__new__(cls, value) > > self.name = name > > return self > > > > def __repr__(self): > > return self.name > > > > __reduce__ = None > > MAXREPEAT = _NamedIntConstant(32,name=str(32)) > > > > what's the problem with the code???? > > You ripped a bunch of code from the standard library without > understanding what it does, and now it doesn't work. The problem is > more with your methodology than your code. > > Why are you doing this? Why not simply use what's there? > > If you REALLY need to make source-level changes, make *changes*, don't > try to lift small parts out. Also, you will need to spend some hours > getting to know the code that you're mutating. > > Is there an alternative newsgroup for > lazy-python-users-who-dont-want-to-do-the-work at groups.google.com ? > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -- From roel at roelschroeven.net Fri Jun 24 05:01:14 2022 From: roel at roelschroeven.net (Roel Schroeven) Date: Fri, 24 Jun 2022 11:01:14 +0200 Subject: sre_constants MODIFIED CLASS - ERROR In-Reply-To: References: Message-ID: Op 24/06/2022 om 10:43 schreef ??? ????: > what's the problem with the code???? Have you seen the replies from Mats Wichmann and Chris Angelico, who helpfully pointed out some problems with your code and possible improvements? Please take those into account instead of asking the same thing over and over. -- "Il semble que la perfection soit atteinte non quand il n'y a plus rien ? ajouter, mais quand il n'y a plus rien ? retrancher." "Perfectie is niet bereikt als er niets meer toe te voegen is, maar als er niets meer weg te nemen is." -- Antoine de Saint-Exup?ry From nsh531 at gmail.com Fri Jun 24 05:10:21 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Fri, 24 Jun 2022 12:10:21 +0300 Subject: sre_constants MODIFIED CLASS - ERROR In-Reply-To: References: Message-ID: OK. I lifted the full library to a HUGE python file that was saved on LAN in MY WORK Do I need to lift many other libraries to the file? I glad to any answer From roel at roelschroeven.net Fri Jun 24 07:29:57 2022 From: roel at roelschroeven.net (Roel Schroeven) Date: Fri, 24 Jun 2022 13:29:57 +0200 Subject: argparse modify In-Reply-To: References: <25268.39803.483755.686736@ixdm.fritz.box> Message-ID: <34398839-f956-6315-2a2c-dac5bc2c0013@roelschroeven.net> Op 24/06/2022 om 0:32 schreef Dennis Lee Bieber: > On Thu, 23 Jun 2022 18:57:31 +0200, "Dieter Maurer" > declaimed the following: > > >??? ???? wrote at 2022-6-23 15:31 +0300: > >>how to solve this (argparse) > > >> MAXREPEAT = _NamedIntConstant(32,name=str(32)) > >>TypeError: 'name' is an invalid keyword argument for int() > > > >This does not look like an `argparse` problem: > >the traceback comes from `oracle/RTR.py`. > > And the listed code looks quite suspicious to me... > > >> class _NamedIntConstant(int): > >> def __init__(cls, value): > >> self = super(_NamedIntConstant, cls).__init__(cls, value) > >> self.name = name > >> return self > > There does not appear to be any provision for keyword arguments at all. > The only use of "name" is to an undefined object. > The code seems to be a copy of Lib/re/_constants.py (or Lib/sre_constants.py before commit 1be3260a90f16aae334d993aecf7b70426f98013), but in _constants.py that class uses __new__ instead of __init__: ??? class _NamedIntConstant(int): ??????? def __new__(cls, value, name): ??????????? self = super(_NamedIntConstant, cls).__new__(cls, value) ??????????? self.name = name ??????????? return self ??????? def __repr__(self): ??????????? return self.name ??????? __reduce__ = None (unless still older versions did use __init__) It's used there as a kind of enum. I guess that code was originally written before Python had enum.Enum. _makecodes() uses it so create named int objects from its arguments, with automatically generated consecutive int values, places them in the global namespace (feels like a code smell to me) and also returns them. ??? def _makecodes(*names): ??????? items = [_NamedIntConstant(i, name) for i, name in enumerate(names)] ??????? globals().update({item.name: item for item in items}) ??????? return items ??? # operators ??? OPCODES = _makecodes( ??????? # failure=0 success=1 (just because it looks better that way :-) ??????? 'FAILURE', 'SUCCESS', ??????? 'ANY', 'ANY_ALL', ??????? 'ASSERT', 'ASSERT_NOT', ??????? 'AT', ??????? # ... ??????? ) ??? ????, are you trying to use that semi-enum functionality? Most likely you're better of using enum.Enum instead. -- "You can fool some of the people all the time, and all of the people some of the time, but you cannot fool all of the people all of the time." -- Abraham Lincoln "You can fool too many of the people too much of the time." -- James Thurber From roel at roelschroeven.net Fri Jun 24 07:34:06 2022 From: roel at roelschroeven.net (Roel Schroeven) Date: Fri, 24 Jun 2022 13:34:06 +0200 Subject: sre_constants MODIFIED CLASS - ERROR In-Reply-To: References: Message-ID: Op 24/06/2022 om 11:10 schreef ??? ????: > OK. I lifted the full library to a HUGE python file that was saved on LAN > in MY WORK > Do I need to lift many other libraries to the file? > I glad to any answer Answer this: what is it that your _actually_ trying to do? What is the ultimate goal of all that copying and changing? Cause there is almost always a better and easier way. -- "You can fool some of the people all the time, and all of the people some of the time, but you cannot fool all of the people all of the time." -- Abraham Lincoln "You can fool too many of the people too much of the time." -- James Thurber From nsh531 at gmail.com Fri Jun 24 08:14:50 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Fri, 24 Jun 2022 15:14:50 +0300 Subject: sre_constants MODIFIED CLASS - ERROR In-Reply-To: References: Message-ID: My TARGET is to bind many code libraries to one Huge code file that works optimally and do optimizations if needed. In this file have code of huge part of falconpy, ALL code of re, argparse, are and many other code libraries This code file is contained 10k lines of python code ?????? ??? ??, 24 ????? 2022, 14:37, ??? Roel Schroeven ?< roel at roelschroeven.net>: > Op 24/06/2022 om 11:10 schreef ??? ????: > > OK. I lifted the full library to a HUGE python file that was saved on LAN > > in MY WORK > > Do I need to lift many other libraries to the file? > > I glad to any answer > Answer this: what is it that your _actually_ trying to do? What is the > ultimate goal of all that copying and changing? Cause there is almost > always a better and easier way. > > -- > "You can fool some of the people all the time, and all of the people some > of the time, but you cannot fool all of the people all of the time." > -- Abraham Lincoln > "You can fool too many of the people too much of the time." > -- James Thurber > > -- > https://mail.python.org/mailman/listinfo/python-list > From nsh531 at gmail.com Fri Jun 24 08:16:14 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Fri, 24 Jun 2022 15:16:14 +0300 Subject: argparse modify In-Reply-To: <34398839-f956-6315-2a2c-dac5bc2c0013@roelschroeven.net> References: <25268.39803.483755.686736@ixdm.fritz.box> <34398839-f956-6315-2a2c-dac5bc2c0013@roelschroeven.net> Message-ID: Thanks a lot. I will read documentation of enum module ?????? ??? ??, 24 ????? 2022, 14:33, ??? Roel Schroeven ?< roel at roelschroeven.net>: > Op 24/06/2022 om 0:32 schreef Dennis Lee Bieber: > > On Thu, 23 Jun 2022 18:57:31 +0200, "Dieter Maurer" > > declaimed the following: > > > > >??? ???? wrote at 2022-6-23 15:31 +0300: > > >>how to solve this (argparse) > > > > >> MAXREPEAT = _NamedIntConstant(32,name=str(32)) > > >>TypeError: 'name' is an invalid keyword argument for int() > > > > > >This does not look like an `argparse` problem: > > >the traceback comes from `oracle/RTR.py`. > > > > And the listed code looks quite suspicious to me... > > > > >> class _NamedIntConstant(int): > > >> def __init__(cls, value): > > >> self = super(_NamedIntConstant, cls).__init__(cls, value) > > >> self.name = name > > >> return self > > > > There does not appear to be any provision for keyword arguments at > all. > > The only use of "name" is to an undefined object. > > > The code seems to be a copy of Lib/re/_constants.py (or > Lib/sre_constants.py before commit > 1be3260a90f16aae334d993aecf7b70426f98013), but in _constants.py that > class uses __new__ instead of __init__: > > class _NamedIntConstant(int): > def __new__(cls, value, name): > self = super(_NamedIntConstant, cls).__new__(cls, value) > self.name = name > return self > > def __repr__(self): > return self.name > > __reduce__ = None > > (unless still older versions did use __init__) > > It's used there as a kind of enum. I guess that code was originally > written before Python had enum.Enum. _makecodes() uses it so create > named int objects from its arguments, with automatically generated > consecutive int values, places them in the global namespace (feels like > a code smell to me) and also returns them. > > def _makecodes(*names): > items = [_NamedIntConstant(i, name) for i, name in > enumerate(names)] > globals().update({item.name: item for item in items}) > return items > > # operators > OPCODES = _makecodes( > # failure=0 success=1 (just because it looks better that way :-) > 'FAILURE', 'SUCCESS', > > 'ANY', 'ANY_ALL', > 'ASSERT', 'ASSERT_NOT', > 'AT', > # ... > ) > > ??? ????, are you trying to use that semi-enum functionality? Most > likely you're better of using enum.Enum instead. > > -- > "You can fool some of the people all the time, and all of the people some > of the time, but you cannot fool all of the people all of the time." > -- Abraham Lincoln > "You can fool too many of the people too much of the time." > -- James Thurber > -- > https://mail.python.org/mailman/listinfo/python-list > From rosuav at gmail.com Fri Jun 24 08:26:23 2022 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 24 Jun 2022 22:26:23 +1000 Subject: sre_constants MODIFIED CLASS - ERROR In-Reply-To: References: Message-ID: ?On Fri, 24 Jun 2022 at 22:16, ???? ?????? wrote:? > > My TARGET is to bind many code libraries to one Huge code file that works > optimally and do optimizations if needed. > In this file have code of huge part of falconpy, ALL code of re, argparse, > are and many other code libraries > > This code file is contained 10k lines of python code > Did you check the license terms of all of those libraries? Are you even legally allowed to do that? ChrisA From nsh531 at gmail.com Fri Jun 24 08:41:58 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Fri, 24 Jun 2022 15:41:58 +0300 Subject: sre_constants MODIFIED CLASS - ERROR In-Reply-To: References: Message-ID: Where found the license of those libraries? P. S. The copied and modified code used only for internal use ?????? ??? ??, 24 ????? 2022, 15:28, ??? Chris Angelico ?: > ?On Fri, 24 Jun 2022 at 22:16, ???? ?????? wrote:? > > > > My TARGET is to bind many code libraries to one Huge code file that > works > > optimally and do optimizations if needed. > > In this file have code of huge part of falconpy, ALL code of re, > argparse, > > are and many other code libraries > > > > This code file is contained 10k lines of python code > > > > Did you check the license terms of all of those libraries? Are you > even legally allowed to do that? > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > From roel at roelschroeven.net Fri Jun 24 10:18:35 2022 From: roel at roelschroeven.net (Roel Schroeven) Date: Fri, 24 Jun 2022 16:18:35 +0200 Subject: sre_constants MODIFIED CLASS - ERROR In-Reply-To: References: Message-ID: <53468319-73f6-e319-3833-9406813932d3@roelschroeven.net> Op 24/06/2022 om 14:14 schreef ??? ????: > My TARGET? is to bind many code libraries to one Huge code file that > works optimally and do optimizations if needed. > In this file have code of huge part of falconpy, ALL code of re, > argparse, are and many other code libraries Don't do that. Sorry, it's just as simple as that. Don't do that. All those modules are not designed to put together like that, all their namespaces merged together. Don't do it. Even if you could eventually get it to work, it would not be any more optimal. If you need more performance, look into things like Pypy or Cython. -- "Experience is that marvelous thing that enables you to recognize a mistake when you make it again." -- Franklin P. Jones From nsh531 at gmail.com Fri Jun 24 11:27:33 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Fri, 24 Jun 2022 18:27:33 +0300 Subject: sre_constants MODIFIED CLASS - ERROR In-Reply-To: <53468319-73f6-e319-3833-9406813932d3@roelschroeven.net> References: <53468319-73f6-e319-3833-9406813932d3@roelschroeven.net> Message-ID: I copied most of the libraries from cython ?????? ??? ??, 24 ????? 2022, 17:18, ??? Roel Schroeven ?< roel at roelschroeven.net>: > Op 24/06/2022 om 14:14 schreef ??? ????: > > My TARGET is to bind many code libraries to one Huge code file that > > works optimally and do optimizations if needed. > > In this file have code of huge part of falconpy, ALL code of re, > > argparse, are and many other code libraries > Don't do that. Sorry, it's just as simple as that. Don't do that. All > those modules are not designed to put together like that, all their > namespaces merged together. Don't do it. > Even if you could eventually get it to work, it would not be any more > optimal. > > If you need more performance, look into things like Pypy or Cython. > > -- > "Experience is that marvelous thing that enables you to recognize a > mistake when you make it again." > -- Franklin P. Jones > > From mats at wichmann.us Fri Jun 24 11:35:37 2022 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 24 Jun 2022 09:35:37 -0600 Subject: 3.11.0b4? In-Reply-To: <5d39b504-fa96-4f6c-816a-deac31cbd6e8n@googlegroups.com> References: <5d39b504-fa96-4f6c-816a-deac31cbd6e8n@googlegroups.com> Message-ID: <9d125ede-a033-bd50-6c13-97cc17de0a4e@wichmann.us> On 6/23/22 07:14, Richard David wrote: > Is there a new scheduled date for releasing 3.11.0b4? Are there issues with b4 that have implications for b3? > > I realize it will be released when ready and am not trying to push or harass anyone involved. It just seems that versions are usually released on schedule so I'm wondering if there's some problem. Was an update today in python-dev (there are still release blockers) From ward.davidj at gmail.com Fri Jun 24 11:57:23 2022 From: ward.davidj at gmail.com (David J W) Date: Fri, 24 Jun 2022 09:57:23 -0600 Subject: "CPython" In-Reply-To: <204719546.4317459.1655998945320@mail.yahoo.com> References: <204719546.4317459.1655998945320@mail.yahoo.com> Message-ID: The main motivation for a Python virtual machine in Rust is to strengthen my knowledge with Rust which currently has some gnarly bits to it but otherwise is an impressive low level language. Rust's future is looking very bright as even Linus Torvalds agrees with most of its design choices and is allowing it to be used as a linux kernel module language. Skipping ahead to the subject of names, Rython was chosen because "Python" is trademarked by the PSF so anything with the complete word Python in it is out. A close runner up would have been Camelot but that is already taken. Going backward to the issue of use and audience. Making Rython a real virtual machine that passes the CPython unit-tests is the only goal. I am actively following the faster CPython fork that Mike Shannon, GVR, and others are working on with the intention to try and incorporate what they discover into my project but I don't think Rython will be dramatically faster than Cpython because I am going to implement the same PyObject reference counting garbage collector and unless faster CPython creates a JIT component, Rython won't have one either. Additionally Ryhon won't have the must have killer libraries like numpy so it's a moot point if my project turns out to be dramatically faster. To sum things up, I've been retired for over a decade so I have plenty of free time. Initially I thought I might invest time into becoming a core python developer but looking into it further, all I will say is that doesn't feel like a very appealing use of my time. On Thu, Jun 23, 2022 at 9:42 AM Avi Gross wrote: > David, > > I am curious why you are undertaking the effort to take a language already > decades old and showing signs of being a tad rusty into a language > that suggests further oxidation. > > More seriously, I am interested in what this can gain and the intended > user > base. I studied Rust for a while and it has it's features but have had no > opportunity to use it. Is it expected to make a faster version of Python, > or enable better connections to libraries and so on? > > What I mean is that if you are planning on making it pass all tests for > python functionality, are you also adding unique features or ... ? > > My preference is to have names that fully include what they are about. > So the name "python" would be left intact rather than mangled, even if > the name itself happens to be totally meaningless. So may I suggest > something like """rustic-python""" ? > > > > -----Original Message----- > From: David J W > To: python-list at python.org > Sent: Thu, Jun 23, 2022 10:29 am > Subject: Re: "CPython" > > >> Let's say they reimplement "reference python" CPython in Rust. What is > >> better? Change the "reference python" CPython name to RPython, for > >> example, or let it as CPython? > > >The C implementation would still be called CPython, and the new > >implementation might be called RPython, or RustyPython, or whatever. > >The names are independent of which one is currently blessed as the > >reference implementation. > > I am at the pre planning stages of making a Rust implementation of the > Python virtual machine and to avoid ambiguity I've been working with Rython > as the name. I tried looking for a Monty Python themed name but the good > ones seem to be taken. > > Otherwise as for a timeline, solo I figure it's going to take me a couple > years to get something that actually passes cpython's python unit-tests. > -- > https://mail.python.org/mailman/listinfo/python-list > From avigross at verizon.net Fri Jun 24 12:24:55 2022 From: avigross at verizon.net (Avi Gross) Date: Fri, 24 Jun 2022 16:24:55 +0000 (UTC) Subject: "CPython" In-Reply-To: References: <204719546.4317459.1655998945320@mail.yahoo.com> Message-ID: <458858099.4609641.1656087895881@mail.yahoo.com> David, I understand now. As a project for your own edification I can understand it, albeit it is a more substantial?effort than many people might choose, LOL! So unless it starts being used heavily and adopted by some organization, the result of your effort will?not necessarily be compatible with many modules now available or keep up with changes as python?adds features or fixes bugs. I am curious about why something like numpy could not be integrated into what you do. Of course,?if you are the only user, ... My hobbies to spend my time may not be as ambitious, but are quite a bit more varied! LOL! -----Original Message----- From: David J W To: Avi Gross Cc: python-list at python.org Sent: Fri, Jun 24, 2022 11:57 am Subject: Re: "CPython" The main motivation for a Python virtual machine in Rust is to strengthen my knowledge with Rust which currently has some gnarly bits to it but otherwise is an impressive low level language.? ?Rust's future is looking very bright as even Linus Torvalds agrees with most of its design choices and is allowing it to be used as a linux kernel module language.? ? Skipping ahead?to the subject of names, Rython was chosen because "Python" is trademarked?by the PSF so anything with the complete word Python in it is out.? ?A close runner up would have been Camelot but that is already taken. Going backward to the issue of use and audience.? Making Rython a real virtual machine that passes the CPython unit-tests is the only goal.? ?I am actively following the faster CPython fork that Mike Shannon, GVR, and others are working on with the intention to try and incorporate what they discover into my project but I don't think Rython will be dramatically faster than Cpython because I am going to implement the same PyObject reference counting garbage collector and unless faster CPython creates a JIT component, Rython won't have one either.? Additionally Ryhon?won't have the must have killer libraries like numpy so it's a moot point if my project turns out to be dramatically faster. To sum things up, I've been retired for over a decade so I have plenty of free time.? ?Initially I thought I might invest time into becoming a core python developer but looking into it further, all I will say is?that doesn't feel like a very appealing use of my time. On Thu, Jun 23, 2022 at 9:42 AM Avi Gross wrote: David, I am curious why you are undertaking the effort to take a language already?decades old and showing signs of being a tad rusty into a language?that suggests further oxidation. More seriously, I am interested in what this can gain and the intended user?base. I studied Rust for a while and it has it's features but have had no?opportunity to use it. Is it expected to make a faster version of Python,?or enable better connections to libraries and so on?? What I mean is that if you are planning on making it pass all tests for?python functionality, are you also adding unique features or ... ? My preference is to have names that fully include what they are about.?So the name "python" would be left intact rather than mangled, even if?the name itself happens to be totally meaningless. So may I suggest?something like """rustic-python""" ? -----Original Message----- From: David J W To: python-list at python.org Sent: Thu, Jun 23, 2022 10:29 am Subject: Re: "CPython" >> Let's say they reimplement "reference python" CPython in Rust. What is >> better? Change the "reference python" CPython name to RPython, for >> example, or let it as CPython? >The C implementation would still be called CPython, and the new >implementation might be called RPython, or RustyPython, or whatever. >The names are independent of which one is currently blessed as the >reference implementation. I am at the pre planning stages of making a Rust implementation of the Python virtual machine and to avoid ambiguity I've been working with Rython as the name.? I tried looking for a Monty Python themed name but the good ones seem to be taken. Otherwise as for a timeline, solo I figure it's going to take me a couple years to get something that actually passes cpython's python unit-tests. -- https://mail.python.org/mailman/listinfo/python-list From pfoosion at gmail.com Thu Jun 23 19:02:02 2022 From: pfoosion at gmail.com (Richard David) Date: Thu, 23 Jun 2022 16:02:02 -0700 (PDT) Subject: 3.11.0b4? In-Reply-To: <5d39b504-fa96-4f6c-816a-deac31cbd6e8n@googlegroups.com> References: <5d39b504-fa96-4f6c-816a-deac31cbd6e8n@googlegroups.com> Message-ID: <8ff94a59-52b1-4c66-b4cb-cf72e6a8296bn@googlegroups.com> On Thursday, June 23, 2022 at 9:15:19 AM UTC-4, Richard David wrote: > Is there a new scheduled date for releasing 3.11.0b4? Are there issues with b4 that have implications for b3? > > I realize it will be released when ready and am not trying to push or harass anyone involved. It just seems that versions are usually released on schedule so I'm wondering if there's some problem. See https://groups.google.com/g/dev-python/c/_3My1hukw6M/m/bz6I_p6kAQAJ From nospam at please.ty Fri Jun 24 09:44:06 2022 From: nospam at please.ty (jak) Date: Fri, 24 Jun 2022 15:44:06 +0200 Subject: open text file References: Message-ID: Il 24/06/2022 15:10, simone zambonardi ha scritto: > Good morning, I need to read a text file. How come when I open it (running the script) it says this? The text file is type RFT > > {\rtf1\ansi\ansicpg1252\cocoartf2636 > \cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;} > {\colortbl;\red255\green255\blue255;} > {\*\expandedcolortbl;;} > \paperw11900\paperh16840\margl1440\margr1440\vieww11520\viewh8400\viewkind0 > \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0 > > \f0\fs24 \cf0 > > But even with in .txt it gives me this long string. I think it is a formatting problem . > thank you I don't see the script you are talking about but it is normal to find those strings inside a file of type '.rtf'. RTF documents are not simple text documents (https://en.wikipedia.org/wiki/Rich_Text_Format) so if you want to extract the text contained in these documents you will need to use a library that can do this (eg: https://pypi.org/project/striprtf/) ...or write a parser yourself. From nospam at please.ty Fri Jun 24 10:03:08 2022 From: nospam at please.ty (jak) Date: Fri, 24 Jun 2022 16:03:08 +0200 Subject: open text file References: Message-ID: Il 24/06/2022 15:44, jak ha scritto: > Il 24/06/2022 15:10, simone zambonardi ha scritto: >> Good morning, I need to read a text file. How come when I open it >> (running the script) it says this? The text file is type RFT >> >> {\rtf1\ansi\ansicpg1252\cocoartf2636 >> \cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 >> Helvetica;} >> {\colortbl;\red255\green255\blue255;} >> {\*\expandedcolortbl;;} >> \paperw11900\paperh16840\margl1440\margr1440\vieww11520\viewh8400\viewkind0 >> >> \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0 >> >> >> \f0\fs24 \cf0 >> >> But even with in .txt it gives me this long string. I think it is a >> formatting problem . >> thank you > > > I don't see the script you are talking about but it is normal to find > those strings inside a file of type '.rtf'. RTF documents are not simple > text documents (https://en.wikipedia.org/wiki/Rich_Text_Format) so if > you want to extract the text contained in these documents you will need > to use a library that can do this > (eg: https://pypi.org/project/striprtf/) > ...or write a parser yourself. P.S. renaming the file extension does not change its content but it is useful for the system to select the app that knows how to manage it From pfoosion at gmail.com Fri Jun 24 13:13:51 2022 From: pfoosion at gmail.com (Richard David) Date: Fri, 24 Jun 2022 10:13:51 -0700 (PDT) Subject: 3.11.0b4? In-Reply-To: References: <9d125ede-a033-bd50-6c13-97cc17de0a4e@wichmann.us> <5d39b504-fa96-4f6c-816a-deac31cbd6e8n@googlegroups.com> Message-ID: <4e235682-d986-4f80-b3e2-b381ebddd39fn@googlegroups.com> On Friday, June 24, 2022 at 11:36:06 AM UTC-4, Mats Wichmann wrote: > On 6/23/22 07:14, Richard David wrote: > > Is there a new scheduled date for releasing 3.11.0b4? Are there issues with b4 that have implications for b3? > > > > I realize it will be released when ready and am not trying to push or harass anyone involved. It just seems that versions are usually released on schedule so I'm wondering if there's some problem. > Was an update today in python-dev (there are still release blockers) For the record: https://groups.google.com/g/dev-python/c/_S8YGysqsxc This does seem an unusually long delay. In any event, it's clearly better to make sure it's working properly than to rush to keep to some schedule. From wlfraed at ix.netcom.com Fri Jun 24 14:13:40 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 24 Jun 2022 14:13:40 -0400 Subject: argparse modify References: <25268.39803.483755.686736@ixdm.fritz.box> <46893e56-1b9c-d650-5f83-17424f82d2c3@wichmann.us> Message-ID: On Thu, 23 Jun 2022 17:01:42 -0600, Mats Wichmann declaimed the following: >Assuming: that the "value" in your init method signature was supposed to >be 'name' since that's what you use later - and would explain your >exception! > Since it is a "named int", I'd expect value to the integer value of this "constant" (and there should probably be a generic setter that... bars changing value or name later). If a "name" keyword argument is not supplied, using the str() of the value for the name might be valid. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From wlfraed at ix.netcom.com Fri Jun 24 14:19:00 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 24 Jun 2022 14:19:00 -0400 Subject: sre_constants MODIFIED CLASS - ERROR References: Message-ID: <1tvbbh591jb44meafa6kqq4n8st0ut2mn8@4ax.com> On Fri, 24 Jun 2022 15:14:50 +0300, ??? ???? declaimed the following: >My TARGET is to bind many code libraries to one Huge code file that works >optimally and do optimizations if needed. >In this file have code of huge part of falconpy, ALL code of re, argparse, >are and many other code libraries > >This code file is contained 10k lines of python code > Which means any program that just uses regular expressions has to import, parse, and byte-code compile all 10K lines. There is a reason Python doesn't make super all-in-one libraries. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From wlfraed at ix.netcom.com Fri Jun 24 14:28:13 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 24 Jun 2022 14:28:13 -0400 Subject: sre_constants MODIFIED CLASS - ERROR References: <53468319-73f6-e319-3833-9406813932d3@roelschroeven.net> Message-ID: <020cbht1kf696f5q0e8f0qi73o3860nr54@4ax.com> On Fri, 24 Jun 2022 18:27:33 +0300, ??? ???? declaimed the following: >I copied most of the libraries from cython I doubt that... cython is a specialized Python COMPILER system. "CPython" is the common interpreted Python language (implemented in C), and is the most likely source of the packages you are mongrelizing.. https://cython.org/ """ Cython is an optimising static compiler for both the Python programming language and the extended Cython programming language (based on Pyrex). It makes writing C extensions for Python as easy as Python itself. """ """ The Cython language is a superset of the Python language that additionally supports calling C functions and declaring C types on variables and class attributes. This allows the compiler to generate very efficient C code from Cython code. The C code is generated once and then compiles with all major C/C++ compilers in CPython 2.6, 2.7 (2.4+ with Cython 0.20.x) as well as 3.3 and all later versions. """ -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From nsh531 at gmail.com Sat Jun 25 14:51:49 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Sat, 25 Jun 2022 21:51:49 +0300 Subject: sre_constants MODIFIED CLASS - ERROR In-Reply-To: <020cbht1kf696f5q0e8f0qi73o3860nr54@4ax.com> References: <53468319-73f6-e319-3833-9406813932d3@roelschroeven.net> <020cbht1kf696f5q0e8f0qi73o3860nr54@4ax.com> Message-ID: correction: This is CPYTHON * and not * CYTHON https://github.com/python/cpython/blob/3.10/Lib/sre_constants.py ??????? ???, 25 ????? 2022 ?-3:27 ??? ?Dennis Lee Bieber?? :? > On Fri, 24 Jun 2022 18:27:33 +0300, ??? ???? declaimed > the following: > > >I copied most of the libraries from cython > > I doubt that... cython is a specialized Python COMPILER system. > "CPython" is the common interpreted Python language (implemented in C), and > is the most likely source of the packages you are mongrelizing.. > > https://cython.org/ > """ > Cython is an optimising static compiler for both the Python programming > language and the extended Cython programming language (based on Pyrex). It > makes writing C extensions for Python as easy as Python itself. > """ > """ > The Cython language is a superset of the Python language that additionally > supports calling C functions and declaring C types on variables and class > attributes. This allows the compiler to generate very efficient C code from > Cython code. The C code is generated once and then compiles with all major > C/C++ compilers in CPython 2.6, 2.7 (2.4+ with Cython 0.20.x) as well as > 3.3 and all later versions. > """ > > > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com > http://wlfraed.microdiversity.freeddns.org/ > -- > https://mail.python.org/mailman/listinfo/python-list > -- From nsh531 at gmail.com Sun Jun 26 06:48:24 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Sun, 26 Jun 2022 13:48:24 +0300 Subject: why this code giving recursion error???? Message-ID: def compile(p, flags=0): # internal: convert pattern list to internal format if (isinstance(p,str)): pattern = p p = sre_parse.parse(p, flags) else: pattern = None code = _code(p, flags) if flags & SRE_FLAG_DEBUG: print() dis(code) # map in either direction groupindex = p.state.groupdict indexgroup = [None] * p.state.groups for k, i in groupindex.items(): indexgroup[i] = k return sre_compile.compile( pattern, flags | p.state.flags, code, p.state.groups-1, groupindex, tuple(indexgroup) ) -- From nsh531 at gmail.com Sun Jun 26 06:50:01 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Sun, 26 Jun 2022 13:50:01 +0300 Subject: why this code giving recursion error???? In-Reply-To: References: Message-ID: stack trace: File "\\Weank-fs\users$\NetanelST\ORACLE\RTR.py", line 5387, in class bottle: File "\\Weank-fs\users$\NetanelST\ORACLE\RTR.py", line 5694, in bottle class Router(object): File "\\Weank-fs\users$\NetanelST\ORACLE\RTR.py", line 5736, in Router rule_syntax = re.compile('(\\\\*)' File "\\Weank-fs\users$\NetanelST\ORACLE\RTR.py", line 375, in compile return sre_compile.compile(pattern, flags) File "\\Weank-fs\users$\NetanelST\ORACLE\RTR.py", line 2752, in compile return sre_compile.compile( File "\\Weank-fs\users$\NetanelST\ORACLE\RTR.py", line 2752, in compile return sre_compile.compile( File "\\Weank-fs\users$\NetanelST\ORACLE\RTR.py", line 2752, in compile return sre_compile.compile( [Previous line repeated 1005 more times] File "\\Weank-fs\users$\NetanelST\ORACLE\RTR.py", line 2736, in compile p = sre_parse.parse(p, flags) File "\\Weank-fs\users$\NetanelST\ORACLE\RTR.py", line 1822, in parse p = sre_parse._parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0) File "\\Weank-fs\users$\NetanelST\ORACLE\RTR.py", line 1234, in _parse_sub itemsappend(sre_parse._parse(source, state, verbose, nested + 1, File "\\Weank-fs\users$\NetanelST\ORACLE\RTR.py", line 1708, in _parse p = sre_parse._parse_sub(source, state, sub_verbose, nested + 1) File "\\Weank-fs\users$\NetanelST\ORACLE\RTR.py", line 1234, in _parse_sub itemsappend(sre_parse._parse(source, state, verbose, nested + 1, File "\\Weank-fs\users$\NetanelST\ORACLE\RTR.py", line 1708, in _parse p = sre_parse._parse_sub(source, state, sub_verbose, nested + 1) File "\\Weank-fs\users$\NetanelST\ORACLE\RTR.py", line 1234, in _parse_sub itemsappend(sre_parse._parse(source, state, verbose, nested + 1, File "\\Weank-fs\users$\NetanelST\ORACLE\RTR.py", line 1707, in _parse not (del_flags & SRE_FLAG_VERBOSE)) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\enum.py", line 987, in __and__ if not isinstance(other, (self.__class__, int)): ??????? ??? ??, 26 ????? 2022 ?-13:48 ??? ??? ???? :? > def compile(p, flags=0): > # internal: convert pattern list to internal format > > if (isinstance(p,str)): > pattern = p > p = sre_parse.parse(p, flags) > else: > pattern = None > > code = _code(p, flags) > > if flags & SRE_FLAG_DEBUG: > print() > dis(code) > > # map in either direction > groupindex = p.state.groupdict > indexgroup = [None] * p.state.groups > for k, i in groupindex.items(): > indexgroup[i] = k > > return sre_compile.compile( > pattern, flags | p.state.flags, code, > p.state.groups-1, > groupindex, tuple(indexgroup) > ) > > > -- > > -- From PythonList at DancesWithMice.info Sun Jun 26 06:55:16 2022 From: PythonList at DancesWithMice.info (dn) Date: Sun, 26 Jun 2022 22:55:16 +1200 Subject: why this code giving recursion error???? In-Reply-To: References: Message-ID: <06db728d-446d-0058-462f-0f2914102953@DancesWithMice.info> On 26/06/2022 22.48, ??? ???? wrote: > def compile(p, flags=0): > # internal: convert pattern list to internal format > > if (isinstance(p,str)): > pattern = p > p = sre_parse.parse(p, flags) > else: > pattern = None > > code = _code(p, flags) > > if flags & SRE_FLAG_DEBUG: > print() > dis(code) > > # map in either direction > groupindex = p.state.groupdict > indexgroup = [None] * p.state.groups > for k, i in groupindex.items(): > indexgroup[i] = k > > return sre_compile.compile( > pattern, flags | p.state.flags, code, > p.state.groups-1, > groupindex, tuple(indexgroup) > ) Why would any code give a recursion error? With recursion problems, the first question to ask is: how does this thing stop? Have you built some test-data with only a handful of items, and thus a predictable result. Does that result occur? If not, where are the differences occurring? -- Regards, =dn From nsh531 at gmail.com Sun Jun 26 06:56:27 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Sun, 26 Jun 2022 13:56:27 +0300 Subject: why this code giving recursion error???? In-Reply-To: References: Message-ID: and i ask also what's the problem with this function: def _code(p, flags): flags = p.state.flags | flags code = [] # compile info block sre_compile._compile_info(code, p, flags) # compile the pattern sre_compile._compile(code, p.data, flags) code.append(SUCCESS) return code ??????? ??? ??, 26 ????? 2022 ?-13:48 ??? ??? ???? :? > def compile(p, flags=0): > # internal: convert pattern list to internal format > > if (isinstance(p,str)): > pattern = p > p = sre_parse.parse(p, flags) > else: > pattern = None > > code = _code(p, flags) > > if flags & SRE_FLAG_DEBUG: > print() > dis(code) > > # map in either direction > groupindex = p.state.groupdict > indexgroup = [None] * p.state.groups > for k, i in groupindex.items(): > indexgroup[i] = k > > return sre_compile.compile( > pattern, flags | p.state.flags, code, > p.state.groups-1, > groupindex, tuple(indexgroup) > ) > > > -- > > -- From nsh531 at gmail.com Sun Jun 26 07:00:02 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Sun, 26 Jun 2022 14:00:02 +0300 Subject: why this code giving recursion error???? In-Reply-To: <06db728d-446d-0058-462f-0f2914102953@DancesWithMice.info> References: <06db728d-446d-0058-462f-0f2914102953@DancesWithMice.info> Message-ID: I FIXED THE CODE ??????? ??? ??, 26 ????? 2022 ?-13:57 ??? ?dn?? :? > On 26/06/2022 22.48, ??? ???? wrote: > > def compile(p, flags=0): > > # internal: convert pattern list to internal format > > > > if (isinstance(p,str)): > > pattern = p > > p = sre_parse.parse(p, flags) > > else: > > pattern = None > > > > code = _code(p, flags) > > > > if flags & SRE_FLAG_DEBUG: > > print() > > dis(code) > > > > # map in either direction > > groupindex = p.state.groupdict > > indexgroup = [None] * p.state.groups > > for k, i in groupindex.items(): > > indexgroup[i] = k > > > > return sre_compile.compile( > > pattern, flags | p.state.flags, code, > > p.state.groups-1, > > groupindex, tuple(indexgroup) > > ) > > > Why would any code give a recursion error? > > With recursion problems, the first question to ask is: how does this > thing stop? > > Have you built some test-data with only a handful of items, and thus a > predictable result. Does that result occur? If not, where are the > differences occurring? > -- > Regards, > =dn > -- > https://mail.python.org/mailman/listinfo/python-list > -- From PythonList at DancesWithMice.info Sun Jun 26 07:01:56 2022 From: PythonList at DancesWithMice.info (dn) Date: Sun, 26 Jun 2022 23:01:56 +1200 Subject: why this code giving recursion error???? In-Reply-To: References: <06db728d-446d-0058-462f-0f2914102953@DancesWithMice.info> Message-ID: On 26/06/2022 23.00, ??? ???? wrote: > I FIXED THE CODE? For the benefit of future-readers: how did you go about fixing it? What was wrong? -- Regards, =dn From rob.cliffe at btinternet.com Sun Jun 26 18:14:13 2022 From: rob.cliffe at btinternet.com (Rob Cliffe) Date: Sun, 26 Jun 2022 23:14:13 +0100 Subject: REPL with multiple function definitions Message-ID: This 2-line program def f(): pass def g(): pass runs silently (no Exception).? But: 23:07:02 c:\>python 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. >>> def f(): pass ... def g(): pass ? File "", line 2 ??? def g(): pass ??? ^ SyntaxError: invalid syntax >>> Is there a good reason for this? Thanks Rob Cliffe From rosuav at gmail.com Sun Jun 26 18:37:00 2022 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 27 Jun 2022 08:37:00 +1000 Subject: REPL with multiple function definitions In-Reply-To: References: Message-ID: On Mon, 27 Jun 2022 at 08:15, Rob Cliffe via Python-list wrote: > > This 2-line program > > def f(): pass > def g(): pass > > runs silently (no Exception). But: > > 23:07:02 c:\>python > 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. > >>> def f(): pass > ... def g(): pass > File "", line 2 > def g(): pass > ^ > SyntaxError: invalid syntax > >>> > > Is there a good reason for this? The REPL compiles one statement at a time. A file is allowed to contain multiple statements. ChrisA From roel at roelschroeven.net Sun Jun 26 18:37:55 2022 From: roel at roelschroeven.net (Roel Schroeven) Date: Mon, 27 Jun 2022 00:37:55 +0200 Subject: REPL with multiple function definitions In-Reply-To: References: Message-ID: Rob Cliffe via Python-list schreef op 27/06/2022 om 0:14: > This 2-line program > > def f(): pass > def g(): pass > > runs silently (no Exception).? But: > > 23:07:02 c:\>python > 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. > >>> def f(): pass > ... def g(): pass > ? File "", line 2 > ??? def g(): pass > ??? ^ > SyntaxError: invalid syntax > >>> > > Is there a good reason for this? The REPL requires an extra empty line to indicate the end of multi-line constructs. You can see it by the prompt: as long as the REPL prints '... '? as prompt, that means it puts everything you type in the same multi-line construct. To enter a new multi-line construct (such as a function definition, a for-loop, an if-statement, ...), press enter directly at the prompt; the REPL should than use '>>> ' as the prompt again. (Alternatives like IPython (https://ipython.readthedocs.io/en/stable/) are a bit more loose regarding how to enter multi-line constructs) -- "Iceland is the place you go to remind yourself that planet Earth is a machine... and that all organic life that has ever existed amounts to a greasy film that has survived on the exterior of that machine thanks to furious improvisation." -- Sam Hughes, Ra From jon+usenet at unequivocal.eu Sun Jun 26 18:22:32 2022 From: jon+usenet at unequivocal.eu (Jon Ribbens) Date: Sun, 26 Jun 2022 22:22:32 -0000 (UTC) Subject: REPL with multiple function definitions References: Message-ID: On 2022-06-26, Rob Cliffe wrote: > This 2-line program > > def f(): pass > def g(): pass > > runs silently (no Exception).? But: > > 23:07:02 c:\>python > 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. > >>> def f(): pass > ... def g(): pass > ? File "", line 2 > ??? def g(): pass > ??? ^ > SyntaxError: invalid syntax > >>> > > Is there a good reason for this? For some reason, the REPL can't cope with one-line blocks like that. If you put a blank line after each one-block line then it will work. From nsh531 at gmail.com Mon Jun 27 04:10:47 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Mon, 27 Jun 2022 11:10:47 +0300 Subject: [bottlepy/bottle] How to modify server adapters? (Issue #1385) In-Reply-To: References: Message-ID: I looked on code but I still need help on this topic I also need help with wsgiref ?????? ??? ???, 27 ????? 2022, ??? Marcel Hellkamp : > Bottle is just a single file and server adapters are often just a couple > of lines long. "Look at the code" is often the best advice. You so do not > need server adapters to run a server. Bottle apps are WSGI apps. Just > follow the documentation of the WSGI server you want to use. > > ? > Reply to this email directly, view it on GitHub > , > or unsubscribe > > . > You are receiving this because you authored the thread.Message ID: > > -- From hjp-python at hjp.at Mon Jun 27 06:45:03 2022 From: hjp-python at hjp.at (Peter J. Holzer) Date: Mon, 27 Jun 2022 12:45:03 +0200 Subject: Subtract n months from datetime In-Reply-To: References: Message-ID: <20220627104503.wwxa2y2273aoqqv2@hjp.at> On 2022-06-21 05:29:52 +0100, Paulo da Silva wrote: > I implemented a part of a script to subtract n months from datetime. > Basically I subtracted n%12 from year and n//12 from the month adding 12 > months when it goes<=0. Then used try when converting to datetime again. So, > if the day is for example 31 for a 30 days month it raises a ValuError > exception. Then I subtract 1 to day and repeat. For a recent longish discussion of that matter see the threads starting at https://mail.python.org/pipermail/python-list/2022-April/905985.html and https://mail.python.org/pipermail/python-list/2022-April/906045.html (the latter also contains some prototype code). (I apologize for not pursuing that further at the time. I wanted to bolster that case with some real world applications, but I was a bit swamped with Real Work? and didn't find anything suitable.) hp -- _ | Peter J. Holzer | Story must make more sense than reality. |_|_) | | | | | hjp at hjp.at | -- Charles Stross, "Creative writing __/ | http://www.hjp.at/ | challenge!" -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 833 bytes Desc: not available URL: From hjp-python at hjp.at Mon Jun 27 06:56:28 2022 From: hjp-python at hjp.at (Peter J. Holzer) Date: Mon, 27 Jun 2022 12:56:28 +0200 Subject: Logging into single file from multiple modules in python when TimedRotatingFileHandler is used In-Reply-To: <35c0eaa7-b299-4e5b-a409-1daf10bbc0f8n@googlegroups.com> References: <35c0eaa7-b299-4e5b-a409-1daf10bbc0f8n@googlegroups.com> Message-ID: <20220627105628.w3ljisnfp4ixfkmf@hjp.at> On 2022-06-21 02:04:52 -0700, Chethan Kumar S wrote: > I have a main process which makes use of different other modules. And > these modules also use other modules. I need to log all the logs into > single log file. Due to use of TimedRotatingFileHandler, my log > behaves differently after midnight. I got to know why it is so but > couldn't get how I can solve it. > Issue was because of serialization in logging when multiple processes ^^^^^^^^^^^^^^^^^^ > are involved. I think this is crucial point. Not "multiple modules" (as you wrote in the subject), but "multiple processes". If each of multiple processes wants to rotate the logfile itself, it is very likely that they will work at cross-purposes. Somebody already suggested using logrotate (or similar external tools). You can then use WatchedFileHandler (https://docs.python.org/3/library/logging.handlers.html#watchedfilehandler) to automatically detect when a logile has been rotated. Alternatively you can use a central logging service (like syslog) which handles all that stuff. hp -- _ | Peter J. Holzer | Story must make more sense than reality. |_|_) | | | | | hjp at hjp.at | -- Charles Stross, "Creative writing __/ | http://www.hjp.at/ | challenge!" -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 833 bytes Desc: not available URL: From nsh531 at gmail.com Mon Jun 27 03:08:41 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Mon, 27 Jun 2022 10:08:41 +0300 Subject: Bottle server adepter - how to modify ? Message-ID: Tnx -- From nsh531 at gmail.com Mon Jun 27 04:23:44 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Mon, 27 Jun 2022 11:23:44 +0300 Subject: [bottlepy/bottle] How to modify server adapters? (Issue #1385) In-Reply-To: References: Message-ID: I sent this to mailing list ?????? ??? ???, 27 ????? 2022, ??? Marcel Hellkamp : > Then ask specific questions. Also, this is an issue tracker, not a support > forum. Try the mailing-list. > > ? > Reply to this email directly, view it on GitHub > , > or unsubscribe > > . > You are receiving this because you authored the thread.Message ID: > > -- From nsh531 at gmail.com Tue Jun 28 03:57:59 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Tue, 28 Jun 2022 10:57:59 +0300 Subject: why function throws an error? Message-ID: def add_route(self, route): # """ Add a route object, but do not change the :data:`Route.app` # attribute.""" self.routes.append(route) self.router.add(route.rule, route.method, route, name=route.name ) # if DEBUG: route.prepare() -- From mirkok.lists at googlemail.com Tue Jun 28 05:11:24 2022 From: mirkok.lists at googlemail.com (Mirko) Date: Tue, 28 Jun 2022 11:11:24 +0200 Subject: why function throws an error? In-Reply-To: References: Message-ID: <4d4c0a0a-8cdf-4f88-d865-fdde459ef7f4@googlemail.com> Am 28.06.22 um 09:57 schrieb ??? ????: > def add_route(self, route): > # """ Add a route object, but do not change the :data:`Route.app` > # attribute.""" > self.routes.append(route) > self.router.add(route.rule, route.method, route, name=route.name > ) > # if DEBUG: route.prepare() > -- > Are you still trying to combine different modules into one large module? That is not going to help you. First, you need to rewrite all those modules to seamlessly work together. This will likely be a huge task. Let's say you have a module that defines some function route(): def route(): print("route") Another module defines a variable called "route": route = True A third module needs to call the function from the first module, but this fails now because the second module has overwritten (shadowed) the former function with a variable: route = True route() Traceback (most recent call last): File "", line 1, in TypeError: 'bool' object is not callable You would need to find all those cases where one module overwrites variables or functions from other modules. And sometimes those cases will be difficult to spot. Python is not designed for what you are trying to do. Even if you get this done, it will not help you. You can't just throw everything into a single file and then magically optimize it. When you have this huge final module, what do you think you can do with it to be faster? If you have performance problems with some module, you have several options to optimize it: - Find a better algorithm. - Rewrite performance-critical parts in Cython or even C and import the compiled module. - Use a JIT compiler such as PyPy From lal at solute.de Tue Jun 28 04:18:42 2022 From: lal at solute.de (Lars Liedtke) Date: Tue, 28 Jun 2022 10:18:42 +0200 Subject: why function throws an error? In-Reply-To: References: Message-ID: Hey, Which error does it throw? Could you please send the stacktrace as well? Cheers Lars -- Lars Liedtke Software Entwickler Phone: Fax: +49 721 98993- E-mail: lal at solute.de solute GmbH Zeppelinstra?e 15 76185 Karlsruhe Germany Marken der solute GmbH | brands of solute GmbH billiger.de | Shopping.de Gesch?ftsf?hrer | Managing Director: Dr. Thilo Gans, Bernd Vermaaten Webseite | www.solute.de Sitz | Registered Office: Karlsruhe Registergericht | Register Court: Amtsgericht Mannheim Registernummer | Register No.: HRB 110579 USt-ID | VAT ID: DE234663798 Informationen zum Datenschutz | Information about privacy policy http://solute.de/ger/datenschutz/grundsaetze-der-datenverarbeitung.php Am 28.06.22 um 09:57 schrieb ??? ????: > def add_route(self, route): > # """ Add a route object, but do not change the :data:`Route.app` > # attribute.""" > self.routes.append(route) > self.router.add(route.rule, route.method, route, name=route.name > ) > # if DEBUG: route.prepare() > -- > From wlfraed at ix.netcom.com Tue Jun 28 09:33:13 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 28 Jun 2022 09:33:13 -0400 Subject: why function throws an error? References: Message-ID: <3j0mbh9klilv8h1im82vrt603avpfglgdm@4ax.com> On Tue, 28 Jun 2022 10:57:59 +0300, ??? ???? declaimed the following: > def add_route(self, route): > # """ Add a route object, but do not change the :data:`Route.app` > # attribute.""" > self.routes.append(route) > self.router.add(route.rule, route.method, route, name=route.name >) > # if DEBUG: route.prepare() From your subject "why function throws an error?". How would we know? You never show us the error traceback, you never provide a minimal code listing that someone could attempt to run to perform debugging. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From nsh531 at gmail.com Tue Jun 28 09:35:22 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Tue, 28 Jun 2022 16:35:22 +0300 Subject: WHAT THE ERROR ON MY CODE??? Message-ID: import requests from requests.structures import CaseInsensitiveDict url = "https://api.crowdstrike.com/oauth2/token" headers = CaseInsensitiveDict() headers["Content-Type"] = "application/x-www-form-urlencoded" headers["Authorization"] = "Basic YjMwMzcwODY3NTUzNDMwNTg5NzA2MjkyNDFmMDE1YWY6VjNKYTk2Y1F4RTFzeTdYbzRnbkt0a2k1djhscXUyU01oSE5VWUwwRg==" data = "POST" resp = requests.post(url, headers=headers, data=data) print(resp.text) print(resp.status_code) import requests from requests.structures import CaseInsensitiveDict MYurl = " https://api.crowdstrike.com/intel/combined/indicators/v1?q=123.123.123.123" headersa = CaseInsensitiveDict() headersa["Authorization"] = "Bearer "+resp.text resp1 = requests.get(MYurl, headers=headersa) print(resp1.status_code) From rosuav at gmail.com Tue Jun 28 11:41:43 2022 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 29 Jun 2022 01:41:43 +1000 Subject: WHAT THE ERROR ON MY CODE??? In-Reply-To: References: Message-ID: ?On Wed, 29 Jun 2022 at 01:37, ???? ?????? wrote:? > headers["Authorization"] = "Basic > YjMwMzcwODY3NTUzNDMwNTg5NzA2MjkyNDFmMDE1YWY6VjNKYTk2Y1F4RTFzeTdYbzRnbkt0a2k1djhscXUyU01oSE5VWUwwRg==" > The error is that you just revealed your credentials to the whole world. This is a public mailing list. In fact, you just revealed your credentials to TWO mailing lists at once. Good job. ChrisA From david at lowryduda.com Tue Jun 28 11:42:01 2022 From: david at lowryduda.com (David Lowry-Duda) Date: Tue, 28 Jun 2022 11:42:01 -0400 Subject: WHAT THE ERROR ON MY CODE??? In-Reply-To: References: Message-ID: Please don't use all caps in the subject line. It comes across as if you're yelling at the list --- this doesn't make people want to be more helpful. Instead, use meaningful, specific subject headers. Also, please be precise and informative about what your problem is. It's not clear what you expect your code to do or what happens differently than you expect. On Tue, Jun 28, 2022 at 04:35:22PM +0300, ??? ???? wrote: >import requests >from requests.structures import CaseInsensitiveDict > >url = "https://api.crowdstrike.com/oauth2/token" Further, testing your code makes random api calls to some website, which I'm disinclined to do without proper context. For more advice, I suggest reading "How to Ask Questions" at http://www.catb.org/~esr/faqs/smart-questions.html - DLD From ongekruisigde at news.eternal-september.org Tue Jun 28 14:54:05 2022 From: ongekruisigde at news.eternal-september.org (De ongekruisigde) Date: Tue, 28 Jun 2022 18:54:05 -0000 (UTC) Subject: WHAT THE ERROR ON MY CODE??? References: Message-ID: On 2022-06-28, Chris Angelico wrote: > ?On Wed, 29 Jun 2022 at 01:37, ???? ?????? wrote:? >> headers["Authorization"] = "Basic >> YjMwMzcwODY3NTUzNDMwNTg5NzA2MjkyNDFmMDE1YWY6VjNKYTk2Y1F4RTFzeTdYbzRnbkt0a2k1djhscXUyU01oSE5VWUwwRg==" >> > > The error is that you just revealed your credentials to the whole > world. This is a public mailing list. > > In fact, you just revealed your credentials to TWO mailing lists at once. I think the term 'script kiddie' applies here. > Good job. > > ChrisA -- Without followers, evil cannot spread. [Spock, "And The Children Shall Lead", stardate 5029.5] From rob.cliffe at btinternet.com Tue Jun 28 17:31:34 2022 From: rob.cliffe at btinternet.com (Rob Cliffe) Date: Tue, 28 Jun 2022 22:31:34 +0100 Subject: REPL with multiple function definitions In-Reply-To: References: Message-ID: On 26/06/2022 23:22, Jon Ribbens via Python-list wrote: > On 2022-06-26, Rob Cliffe wrote: >> This 2-line program >> >> def f(): pass >> def g(): pass >> >> runs silently (no Exception).? But: >> >> 23:07:02 c:\>python >> 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. >>>>> def f(): pass >> ... def g(): pass >> ? File "", line 2 >> ??? def g(): pass >> ??? ^ >> SyntaxError: invalid syntax >> Is there a good reason for this? > For some reason, the REPL can't cope with one-line blocks like that. > If you put a blank line after each one-block line then it will work. It's actually not to do with 1-line blocks, just attempting to define 2 functions "at once": 22:27:23 C:\>python 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. >>> def f(): ...???? return 42 ... def g(): ? File "", line 3 ??? def g(): ??? ^ SyntaxError: invalid syntax >>> But you are right that adding a blank line after the first function definition solves the "problem". Rob Cliffe From rosuav at gmail.com Tue Jun 28 21:13:29 2022 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 29 Jun 2022 11:13:29 +1000 Subject: REPL with multiple function definitions In-Reply-To: References: Message-ID: On Wed, 29 Jun 2022 at 11:00, Rob Cliffe via Python-list wrote: > > On 26/06/2022 23:22, Jon Ribbens via Python-list wrote: > > On 2022-06-26, Rob Cliffe wrote: > >> This 2-line program > >> > >> def f(): pass > >> def g(): pass > >> > >> runs silently (no Exception). But: > >> > >> 23:07:02 c:\>python > >> 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. > >>>>> def f(): pass > >> ... def g(): pass > >> File "", line 2 > >> def g(): pass > >> ^ > >> SyntaxError: invalid syntax > >> Is there a good reason for this? > > For some reason, the REPL can't cope with one-line blocks like that. > > If you put a blank line after each one-block line then it will work. > It's actually not to do with 1-line blocks, just attempting to define 2 > functions "at once": > > > 22:27:23 C:\>python > 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. > >>> def f(): > ... return 42 > ... def g(): > File "", line 3 > def g(): > ^ > SyntaxError: invalid syntax > >>> > > But you are right that adding a blank line after the first function > definition solves the "problem". And if you have something where you want to copy and paste multiple statements, there are a few ways to do it: 1) Put "if 1:" at the top. That makes it a single block, so you can paste in as much as you like, as long as the only blank line is at the end. 2) Put the code into a file and then use "python3 -i setup.py". That runs all the code, then drops you into the REPL in that context. 3) Put the code into a file, and inside the REPL, "from setup import *". Unlike option 2, this can be done after the beginning of the session. Downside: editing setup.py and reimporting won't apply your changes. ChrisA From nsh531 at gmail.com Wed Jun 29 01:32:51 2022 From: nsh531 at gmail.com (=?UTF-8?B?16DXqteZINep15jXqNef?=) Date: Wed, 29 Jun 2022 08:32:51 +0300 Subject: WHAT THE ERROR ON MY CODE??? In-Reply-To: References: Message-ID: Sorry but i forgor to delete this token data ?????? ??? ?????, 28 ????? 2022, ??? De ongekruisigde < ongekruisigde at news.eternal-september.org>: > On 2022-06-28, Chris Angelico wrote: > > ?On Wed, 29 Jun 2022 at 01:37, ???? ?????? wrote:? > >> headers["Authorization"] = "Basic > >> YjMwMzcwODY3NTUzNDMwNTg5NzA2MjkyNDFmMDE1YWY6VjNKYTk2Y1F4RTFz > eTdYbzRnbkt0a2k1djhscXUyU01oSE5VWUwwRg==" > >> > > > > The error is that you just revealed your credentials to the whole > > world. This is a public mailing list. > > > > In fact, you just revealed your credentials to TWO mailing lists at once. > > I think the term 'script kiddie' applies here. > > > > Good job. > > > > ChrisA > > > -- > Without followers, evil cannot spread. > > [Spock, "And The Children Shall Lead", stardate 5029.5] > -- > https://mail.python.org/mailman/listinfo/python-list > -- From dfnsonfsduifb at gmx.de Wed Jun 29 05:50:36 2022 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Wed, 29 Jun 2022 11:50:36 +0200 Subject: Creating lambdas inside generator expression Message-ID: Hi list, I've just encounted something that I found extremely unintuitive and would like your feedback. This bit me *hard*, causing me to question my sanity for a moment. Consider this minimal example code (Py 3.10.4 on Linux x64): class Msg(): def hascode(self, value): print("Check for", value) return False conds = [ lambda msg: msg.hascode("foo"), lambda msg: msg.hascode("bar"), ] msg = Msg() print(conds[0](msg)) print(conds[1](msg)) It works perfectly and does exactly what it looks like. The output is: Check for foo False Check for bar False But now consider what happens when we create the lambdas inside a list comprehension (in my original I used a generator expresison, but the result is the same). Can you guess what happens when we create conds like this? conds = [ lambda msg: msg.hascode(z) for z in ("foo", "bar") ] I certainly could not. Here's what it outputs: Check for bar False Check for bar False I.e., the iteration variable "z" somehow gets bound inside the lambda not by its value, but by its reference. All checks therefore refence only the last variable. This totally blew my mind. I can understand why it's happening, but is this the behavior we would expect? And how can I create lambdas inside a generator expression and tell the expression to use the *value* and not pass the "z" variable by reference? Cheers, Joe From dfnsonfsduifb at gmx.de Wed Jun 29 06:43:19 2022 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Wed, 29 Jun 2022 12:43:19 +0200 Subject: Creating lambdas inside generator expression References: Message-ID: Aha! conds = [ lambda msg, z = z: msg.hascode(z) for z in ("foo", "bar") ] Is what I was looking for to explicitly use the value of z. What a caveat, didn't see that coming. Learning something new every day. Cheers, Joe Am 29.06.22 um 11:50 schrieb Johannes Bauer: > Hi list, > > I've just encounted something that I found extremely unintuitive and > would like your feedback. This bit me *hard*, causing me to question my > sanity for a moment. Consider this minimal example code (Py 3.10.4 on > Linux x64): > > > class Msg(): > def hascode(self, value): > print("Check for", value) > return False > > conds = [ > lambda msg: msg.hascode("foo"), > lambda msg: msg.hascode("bar"), > ] > > msg = Msg() > print(conds[0](msg)) > print(conds[1](msg)) > > > > It works perfectly and does exactly what it looks like. The output is: > > Check for foo > False > Check for bar > False > > But now consider what happens when we create the lambdas inside a list > comprehension (in my original I used a generator expresison, but the > result is the same). Can you guess what happens when we create conds > like this? > > conds = [ lambda msg: msg.hascode(z) for z in ("foo", "bar") ] > > I certainly could not. Here's what it outputs: > > Check for bar > False > Check for bar > False > > I.e., the iteration variable "z" somehow gets bound inside the lambda > not by its value, but by its reference. All checks therefore refence > only the last variable. > > This totally blew my mind. I can understand why it's happening, but is > this the behavior we would expect? And how can I create lambdas inside a > generator expression and tell the expression to use the *value* and not > pass the "z" variable by reference? > > Cheers, > Joe From antoon.pardon at vub.be Wed Jun 29 14:47:29 2022 From: antoon.pardon at vub.be (Antoon Pardon) Date: Wed, 29 Jun 2022 20:47:29 +0200 Subject: Creating lambdas inside generator expression In-Reply-To: References: Message-ID: <0ba67336-6a64-95a0-2335-7196cca2518a@vub.be> Or you could try this as an alternative: conds = [ (lambda code: lambda msg: msg.hascode(code))(z) for z in ("foo", "bar") ] Op 29/06/2022 om 12:43 schreef Johannes Bauer: > Aha! > > conds = [ lambda msg, z = z: msg.hascode(z) for z in ("foo", "bar") ] > > Is what I was looking for to explicitly use the value of z. What a > caveat, didn't see that coming. > > Learning something new every day. > > Cheers, > Joe > > > Am 29.06.22 um 11:50 schrieb Johannes Bauer: >> Hi list, >> >> I've just encounted something that I found extremely unintuitive and >> would like your feedback. This bit me *hard*, causing me to question my >> sanity for a moment. Consider this minimal example code (Py 3.10.4 on >> Linux x64): >> >> >> class Msg(): >> def hascode(self, value): >> print("Check for", value) >> return False >> >> conds = [ >> lambda msg: msg.hascode("foo"), >> lambda msg: msg.hascode("bar"), >> ] >> >> msg = Msg() >> print(conds[0](msg)) >> print(conds[1](msg)) >> >> >> >> It works perfectly and does exactly what it looks like. The output is: >> >> Check for foo >> False >> Check for bar >> False >> >> But now consider what happens when we create the lambdas inside a list >> comprehension (in my original I used a generator expresison, but the >> result is the same). Can you guess what happens when we create conds >> like this? >> >> conds = [ lambda msg: msg.hascode(z) for z in ("foo", "bar") ] >> >> I certainly could not. Here's what it outputs: >> >> Check for bar >> False >> Check for bar >> False >> >> I.e., the iteration variable "z" somehow gets bound inside the lambda >> not by its value, but by its reference. All checks therefore refence >> only the last variable. >> >> This totally blew my mind. I can understand why it's happening, but is >> this the behavior we would expect? And how can I create lambdas inside a >> generator expression and tell the expression to use the *value* and not >> pass the "z" variable by reference? >> >> Cheers, >> Joe From cspealma at redhat.com Wed Jun 29 15:34:21 2022 From: cspealma at redhat.com (Calvin Spealman) Date: Wed, 29 Jun 2022 15:34:21 -0400 Subject: WHAT THE ERROR ON MY CODE??? In-Reply-To: References: Message-ID: You also forgot to include any information about an error or problem you got in using this code. We can't help you if you don't have an actual question to ask. ?On Wed, Jun 29, 2022 at 1:36 AM ???? ?????? wrote:? > Sorry but i forgor to delete this token data > > ?????? ??? ?????, 28 ????? 2022, ??? De ongekruisigde < > ongekruisigde at news.eternal-september.org>: > > > On 2022-06-28, Chris Angelico wrote: > > > ?On Wed, 29 Jun 2022 at 01:37, ???? ?????? wrote:? > > >> headers["Authorization"] = "Basic > > >> YjMwMzcwODY3NTUzNDMwNTg5NzA2MjkyNDFmMDE1YWY6VjNKYTk2Y1F4RTFz > > eTdYbzRnbkt0a2k1djhscXUyU01oSE5VWUwwRg==" > > >> > > > > > > The error is that you just revealed your credentials to the whole > > > world. This is a public mailing list. > > > > > > In fact, you just revealed your credentials to TWO mailing lists at > once. > > > > I think the term 'script kiddie' applies here. > > > > > > > Good job. > > > > > > ChrisA > > > > > > -- > > Without followers, evil cannot spread. > > > > [Spock, "And The Children Shall Lead", stardate 5029.5] > > -- > > https://mail.python.org/mailman/listinfo/python-list > > > > > -- > > -- > https://mail.python.org/mailman/listinfo/python-list > -- CALVIN SPEALMAN SENIOR QUALITY ENGINEER calvin.spealman at redhat.com M: +1.336.210.5107 [image: https://red.ht/sig] TRIED. TESTED. TRUSTED. From rosuav at gmail.com Wed Jun 29 17:17:43 2022 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 30 Jun 2022 07:17:43 +1000 Subject: Creating lambdas inside generator expression In-Reply-To: References: Message-ID: On Thu, 30 Jun 2022 at 02:49, Johannes Bauer wrote: > But now consider what happens when we create the lambdas inside a list > comprehension (in my original I used a generator expresison, but the > result is the same). Can you guess what happens when we create conds > like this? > > conds = [ lambda msg: msg.hascode(z) for z in ("foo", "bar") ] > > I certainly could not. Here's what it outputs: > > Check for bar > False > Check for bar > False > > I.e., the iteration variable "z" somehow gets bound inside the lambda > not by its value, but by its reference. All checks therefore refence > only the last variable. > Yep, that is the nature of closures. (Side point: This isn't actually a generator expression, it's a list comprehension; current versions of Python treat them broadly the same way, but there was previously a difference in the way scoping worked.) What you're seeing is a consequence of the way that closures work, and it is a very good thing most of the time :) The usual way to "snapshot" a variable is what you showed in your followup: a default argument value. def f(..., z=z): ... z has been snapshot (As others have pointed out, this isn't unique to lambdas; any function will behave that way.) Antoon offered another variant, but written as a pair of lambda functions, it's a little hard to see what's going on. Here's the same technique written as a factory function: def does_it_have(z): return lambda msg: msg.hascode(z) conds = [does_it_have(z) for z in ("foo", "bar")] Written like this, it's clear that the variable z in the comprehension is completely different from the one inside does_it_have(), and they could have different names if you wanted to. This is a fairly clean way to snapshot too, and has the advantage that it doesn't pretend that the function takes an extra parameter. ChrisA From __peter__ at web.de Thu Jun 30 06:04:13 2022 From: __peter__ at web.de (Peter Otten) Date: Thu, 30 Jun 2022 12:04:13 +0200 Subject: Creating lambdas inside generator expression In-Reply-To: References: Message-ID: <5605b923-c562-397a-1f1b-58c3ee29c0f9@web.de> On 29/06/2022 23:17, Chris Angelico wrote: > On Thu, 30 Jun 2022 at 02:49, Johannes Bauer wrote: >> But now consider what happens when we create the lambdas inside a list >> comprehension (in my original I used a generator expresison, but the >> result is the same). Can you guess what happens when we create conds >> like this? >> >> conds = [ lambda msg: msg.hascode(z) for z in ("foo", "bar") ] >> >> I certainly could not. Here's what it outputs: >> >> Check for bar >> False >> Check for bar >> False >> >> I.e., the iteration variable "z" somehow gets bound inside the lambda >> not by its value, but by its reference. All checks therefore refence >> only the last variable. >> > > Yep, that is the nature of closures. (Side point: This isn't actually > a generator expression, it's a list comprehension; current versions of > Python treat them broadly the same way, but there was previously a > difference in the way scoping worked.) What you're seeing is a > consequence of the way that closures work, and it is a very good thing > most of the time :) > > The usual way to "snapshot" a variable is what you showed in your > followup: a default argument value. > > def f(..., z=z): > ... z has been snapshot > > (As others have pointed out, this isn't unique to lambdas; any > function will behave that way.) > > Antoon offered another variant, but written as a pair of lambda > functions, it's a little hard to see what's going on. Here's the same > technique written as a factory function: > > def does_it_have(z): > return lambda msg: msg.hascode(z) > > conds = [does_it_have(z) for z in ("foo", "bar")] > > Written like this, it's clear that the variable z in the comprehension > is completely different from the one inside does_it_have(), and they > could have different names if you wanted to. This is a fairly clean > way to snapshot too, and has the advantage that it doesn't pretend > that the function takes an extra parameter. While I'd go with Chris' suggestion there are two other options: functools.partial() and operator.methodcaller(). Example: >>> class Msg: def __init__(self, msg): self.msg = msg def hascode(self, code): return code in self.msg >>> conds = [partial(lambda z, msg: msg.hascode(z), z) for z in ("foo", "bar")] >>> [cond(Msg("barbaz")) for cond in conds] [False, True] >>> conds = [methodcaller("hascode", z) for z in ("foo", "bar")] >>> [cond(Msg("barbaz")) for cond in conds] [False, True] From rob.cliffe at btinternet.com Thu Jun 30 17:36:09 2022 From: rob.cliffe at btinternet.com (Rob Cliffe) Date: Thu, 30 Jun 2022 22:36:09 +0100 Subject: Byte arrays and DLLs Message-ID: <19eed94d-4f36-3171-7ce7-761850d5581a@btinternet.com> I have an application in which I wanted a fixed-length "array of bytes" (that's intended as an informal term) where I could read and write individual bytes and slices, and also pass the array to a DLL (one I wrote in C) which expects an "unsigned char *" parameter. I am using ctypes to talk to the DLL but am open to alternatives. Speed is important.? My OS is Windows 10. I started off using a bytearray object (bytes does not support item assignment), but I couldn't find any way of passing it to the DLL directly.? Instead I had to convert it to a different type before passing it, e.g. ??? bytes(MyArray) or ??? (ctypes.c_char * LEN).from_buffer(MyArray)) # LEN is the length of MyArray, knownin advance but this was slow, I think because the array data is being copied to a separate object. Eventually after consulting Googol I came up with using a memoryview: ??? MyArray = memoryview(bytearray(?? )) # can read and write to this and passing it to the DLL as ??? MyArray.tobytes() and was gratified to see a modest speed improvement.? (I don't know for sure if it is still copying the array data, though I would guess not.) Is this a sensible approach, or am I still missing something? AKAIK it is not possible to give ctypes a bytearray object and persuade it to give you a pointer to the actual array data, suitable for passing to a DLL.? Is this (a) false (b) for historical reasons (c) for some other good reason? TIA Rob Cliffe From eryksun at gmail.com Thu Jun 30 18:45:49 2022 From: eryksun at gmail.com (Eryk Sun) Date: Thu, 30 Jun 2022 17:45:49 -0500 Subject: Byte arrays and DLLs In-Reply-To: <19eed94d-4f36-3171-7ce7-761850d5581a@btinternet.com> References: <19eed94d-4f36-3171-7ce7-761850d5581a@btinternet.com> Message-ID: On 6/30/22, Rob Cliffe via Python-list wrote: > > AKAIK it is not possible to give ctypes a bytearray object and persuade > it to give you a pointer to the actual array data, suitable for passing > to a DLL. You're overlooking the from_buffer() method. For example: >>> ba = bytearray(10) >>> ca = (ctypes.c_char * len(ba)).from_buffer(ba) >>> ca.value = b'spam&eggs' >>> ba bytearray(b'spam&eggs\x00') Note that the bytearray can't be resized while a view of the data is exported. For example: >>> ba.append(97) Traceback (most recent call last): File "", line 1, in BufferError: Existing exports of data: object cannot be re-sized >>> del ba[-1] Traceback (most recent call last): File "", line 1, in BufferError: Existing exports of data: object cannot be re-sized