unable to run the basic Embedded Python example
I cannot get the simple program https://docs.python.org/3/extending/embedding.html#very-high-level-embedding to work. My environment: * Windows 10 * Microsoft Visual Studio 2019 * Qt Creator 10.0.1 (only as an IDE) * Python not installed This is what I did: 1. I downloaded https://www.python.org/ftp/python/3.11.4/Python-3.11.4.tgz 2. I extracted Python-3.11.4.tgz into C:\temp\Python-3.11.4 3. I opened the "x64 Native Tools Command Prompt for VS 2019" which comes with Microsoft Visual Studio 2019 4. In "x64 Native Tools Command Prompt for VS 2019": ** ** Visual Studio 2019 Developer Command Prompt v16.11.26 ** Copyright (c) 2021 Microsoft Corporation ** [vcvarsall.bat] Environment initialized for: 'x64' C:\Program Files (x86)\Microsoft Visual Studio\2019\Community>cd C:\temp\Python-3.11.4\PCbuild C:\temp\Python-3.11.4\PCbuild>build.bat -d // <= option '-d' means "debug" Downloading nuget... [many lines omitted] Build succeeded. C:\temp\Python-3.11.4\PCbuild\pythoncore.vcxproj(578,5): warning MSB3073: The command ""C:\Program Files\Git\cmd\git.exe" name-rev --name-only HEAD > "C:\temp\Python-3.11.4\PCbuild\obj\311amd64_Debug\pythoncore\gitbranch.txt"" exited with code 128. C:\temp\Python-3.11.4\PCbuild\pythoncore.vcxproj(578,5): warning MSB4181: The "Exec" task returned false but did not log an error. C:\temp\Python-3.11.4\PCbuild\pythoncore.vcxproj(579,5): warning MSB3073: The command ""C:\Program Files\Git\cmd\git.exe" rev-parse --short HEAD > "C:\temp\Python-3.11.4\PCbuild\obj\311amd64_Debug\pythoncore\gitversion.txt"" exited with code 128. C:\temp\Python-3.11.4\PCbuild\pythoncore.vcxproj(579,5): warning MSB4181: The "Exec" task returned false but did not log an error. C:\temp\Python-3.11.4\PCbuild\pythoncore.vcxproj(580,5): warning MSB3073: The command ""C:\Program Files\Git\cmd\git.exe" describe --all --always --dirty > "C:\temp\Python-3.11.4\PCbuild\obj\311amd64_Debug\pythoncore\gittag.txt"" exited with code 128. C:\temp\Python-3.11.4\PCbuild\pythoncore.vcxproj(580,5): warning MSB4181: The "Exec" task returned false but did not log an error. 6 Warning(s) 0 Error(s) Time Elapsed 00:00:34.87 C:\temp\Python-3.11.4\PCbuild> 5. I copied the example https://docs.python.org/3/extending/embedding.html#very-high-level-embedding, unchanged, to 'C:\temp\embedded_python\main.c'. 6. I created Qt Creator project file 'C:\temp\embedded_python\ embedded_python.pro': TEMPLATE = app TARGET = embedded_python SOURCES += main.c PYTHON_DIR = C:/temp/Python-3.11.4 INCLUDEPATH += $${PYTHON_DIR}/Include INCLUDEPATH += $${PYTHON_DIR}/PC LIBS += $${PYTHON_DIR}/PCbuild/amd64/python311_d.lib 7. I built the project: 20:02:38: Running steps for project embedded_python... 20:02:38: Starting: "C:\Qt\6.1.3\msvc2019_64\bin\qmake.exe" C:\temp\embedded_python\embedded_python.pro -spec win32-msvc "CONFIG+=debug" "CONFIG-=qml_debug" "CONFIG-=qtquickcompiler" Info: creating stash file C:\temp\build-embedded_python-Desktop_Qt_6_1_3_MSVC2019_64bit-Debug\.qmake.stash 20:02:38: The process "C:\Qt\6.1.3\msvc2019_64\bin\qmake.exe" exited normally. 20:02:38: Starting: "C:\Qt\Tools\QtCreator\bin\jom\jom.exe" -f C:/temp/build-embedded_python-Desktop_Qt_6_1_3_MSVC2019_64bit-Debug/Makefile qmake_all jom 1.1.3 - empower your cores 20:02:38: The process "C:\Qt\Tools\QtCreator\bin\jom\jom.exe" exited normally. 20:02:38: Starting: "C:\Qt\Tools\QtCreator\bin\jom\jom.exe" C:\Qt\Tools\QtCreator\bin\jom\jom.exe -f Makefile.Debug cl -c -nologo -Zc:wchar_t -FS -Zc:strictStrings -Zi -MDd -utf-8 -W3 -w44456 -w44457 -w44458 /Fddebug\embedded_python.vc.pdb -DUNICODE -D_UNICODE -DWIN32 -D_ENABLE_EXTENDED_ALIGNED_STORAGE -DWIN64 -DQT_GUI_LIB -DQT_CORE_LIB -I..\embedded_python -I. -I..\Python-3.11.4\Include -I..\Python-3.11.4\PC -I..\..\Qt\6.1.3\msvc2019_64\include -I..\..\Qt\6.1.3\msvc2019_64\include\QtGui -I..\..\Qt\6.1.3\msvc2019_64\include\QtCore -Idebug -IC:/VulkanSDK/ 1.0.51.0/Include -I..\..\Qt\6.1.3\msvc2019_64\mkspecs\win32-msvc -Fodebug\ @C:\Users\dave\AppData\Local\Temp\main.obj.21168.0.jom main.c ..\embedded_python\main.c(12): warning C4996: 'Py_SetProgramName': deprecated in 3.11 link /NOLOGO /DYNAMICBASE /NXCOMPAT /DEBUG /SUBSYSTEM:WINDOWS "/MANIFESTDEPENDENCY:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' publicKeyToken='6595b64144ccf1df' language='*' processorArchitecture='*'" /MANIFEST:embed /OUT:debug\embedded_python.exe @C:\Users\dave\AppData\Local\Temp\embedded_python.exe.21168.484.jom 20:02:39: The process "C:\Qt\Tools\QtCreator\bin\jom\jom.exe" exited normally. 20:02:39: Elapsed time: 00:01.
Re: Creating logs with Python
Thank you Gerard! I am working on a project and needed that... :) 73, and thanks, Dave (NK7Z) https://www.nk7z.net ARRL Volunteer Examiner ARRL Technical Specialist, RFI ARRL Asst. Director, NW Division, Technical Resources On 2/22/23 07:03, Weatherby,Gerard wrote: https://docs.python.org/3/howto/logging.html From: Python-list on behalf of Bibi Date: Wednesday, February 22, 2023 at 9:44 AM To: python-list@python.org Subject: Creating logs with Python *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** Hello I want to store and make available as part of my project, logs, for access to data. Do you have any proposals? Kind regards -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!ntBEz59Ey9Aq3lepQ3xSKwSYtD_mYgoMO3OPqxMUrzbHNliAV76yHKsVIbEDpznq3hXNHvGxG3RNUPVxj5k$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!ntBEz59Ey9Aq3lepQ3xSKwSYtD_mYgoMO3OPqxMUrzbHNliAV76yHKsVIbEDpznq3hXNHvGxG3RNUPVxj5k$> -- https://mail.python.org/mailman/listinfo/python-list
Re: Function to Print a nicely formatted Dictionary or List?
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" > } > -- https://mail.python.org/mailman/listinfo/python-list
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
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 + (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 > wlfr...@ix.netcom.comhttp://wlfraed.microdiversity.freeddns.org/ > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: How to replace characters in a string?
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@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
Re: How to replace characters in a string?
> 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 -- https://mail.python.org/mailman/listinfo/python-list
Re: How to replace characters in a string?
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 -- https://mail.python.org/mailman/listinfo/python-list
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
Re: How to replace characters in a string?
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 -- https://mail.python.org/mailman/listinfo/python-list
How to replace characters in a string?
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
Re: How to test characters of a string
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 -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
rotfl! Nice one! > On 8 Jun 2022, at 00:24, 2qdxy4rzwzuui...@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 -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
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 -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
A, 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 -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
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 >> > <mailto:ongekruisi...@news.eternal-september.org>> wrote: >> >> On 2022-06-07, Dave > <mailto:d...@looktowindward.com> <mailto:d...@looktowindward.com >> <mailto:d...@looktowindward.com>>> 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> >> <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> -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
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 <mailto:d...@looktowindward.com>> 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> -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
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, 2qdxy4rzwzuui...@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
Re: How to test characters of a string
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 -- https://mail.python.org/mailman/listinfo/python-list
How to test characters of a string
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 -- https://mail.python.org/mailman/listinfo/python-list
Re: Help with Python/Eyed3 MusicCDIdFrame method
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 > <https://mail.python.org/mailman/listinfo/python-list> -- https://mail.python.org/mailman/listinfo/python-list
Help with Python/Eyed3 MusicCDIdFrame method
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 -- https://mail.python.org/mailman/listinfo/python-list
python 3.9.12 and python 3.10
Date: Tue, 3 May 2022 19:59:08 +0100 Subject: python 3.9.12 and python 3.10 I installed 3.9 and am able to enter simple code which runs. If I type an error I can highlight it but cannot copy or delete it. I looked for help & found 3.10 and installed it but when I selected the python icon 3.9 appeared with my old errors. I uninstalled 3.10 as 3.9 did not appear in control panel. Dell Inspiron 3793 Win 10 Thanks Dave Francis -- https://mail.python.org/mailman/listinfo/python-list
[issue43112] SOABI on Linux does not distinguish between GNU libc and musl libc
Change by Dave Shawley : -- nosy: +dave-shawley ___ Python tracker <https://bugs.python.org/issue43112> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue46014] functools.singledispatch does not support Union types
New submission from Dave Evans : It's not currently possible to use `singledispatch` with a function annotated with a Union type, although the desired behaviour is clear. Example: ``` from functools import singledispatch from typing import Union @singledispatch def test(arg): raise ValueError(arg) @test.register def _(arg: Union[int, float]): print(f"{arg} is a number") test(1) ``` This dies with: TypeError: Invalid annotation for 'arg'. typing.Union[int, float] is not a class. I've implemented a workaround which digs the types out of the union and registers them one-by-one: ``` from functools import singledispatch from typing import Union, get_type_hints def register_for_union_type(target_fn): def decorator(fn): arg_type = list(get_type_hints(fn).values())[0] assert arg_type.__origin__ is Union for type_ in arg_type.__args__: fn = target_fn.register(type_)(fn) return fn return decorator @singledispatch def test(arg): raise ValueError(arg) @register_for_union_type(test) def _(arg: Union[int, float]): print(f"{arg} is a number") test(1) ``` Looking at the source for `singledispatch` is doesn't look like it would *too* difficult to add support for something like this, though of course there may be subtleties I've missed. Would you be open to a patch? The only other mentions I've found of this online are: https://mail.python.org/archives/list/python-id...@python.org/thread/HF5HDXQ2SXZHO3TWODIRQATTE4TCAWPL/ https://stackoverflow.com/questions/61721761/type-hints-and-singledispatch-how-do-i-include-union-in-an-extensible-w -- components: Library (Lib) messages: 408018 nosy: evansd priority: normal severity: normal status: open title: functools.singledispatch does not support Union types type: enhancement versions: Python 3.10, Python 3.11, Python 3.7, Python 3.8, Python 3.9 ___ Python tracker <https://bugs.python.org/issue46014> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue45305] Incorrect record of call_args_list when using multiple side_effect in mock.patch
Dave McNulla added the comment: I understand. It's a thing I often forget in python that some parameters are passed by value while others are passed by reference (language for parameters I remember from C class about 30 years ago). I do not think I would have caught that with docs, unless you start putting them in Stack Overflow! I'm only sort of kidding. I think you can close this bug. Thanks for the clarification, Dave -- resolution: -> not a bug ___ Python tracker <https://bugs.python.org/issue45305> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue45305] Incorrect record of call_args_list when using multiple side_effect in mock.patch
New submission from Dave McNulla : https://gist.github.com/dmcnulla/ecec8fc96a2fd07082f240eeff6888d9 I'm trying to reproduce an error in a call to a method, forcing a second call to the method. In my test, the call_args_list is showing incorrectly (both in debugging or running unittest normally). I am not certain what other circumstances this is happening or not happening. I was able to reduce the code to reproduce it quite a bit. I am certain that the first call to the method is not matching correctly in my criteria to what I expect based on my debugging. I am using python 3.7. I can reproduce in IntelliJ or by commandline `python3 -m pytest test_multiple_side_effect.py` -- components: Tests messages: 402743 nosy: dmcnulla priority: normal severity: normal status: open title: Incorrect record of call_args_list when using multiple side_effect in mock.patch versions: Python 3.7 ___ Python tracker <https://bugs.python.org/issue45305> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue39442] from __future__ import annotations makes dataclasses.Field.type a string, not type
Dave Tapley added the comment: I don't know if it helps, but I just ran in to this when I followed the advice at (1) because I wanted to type hint a method with the type of the enclosing class. This broke a package I'm working on in parallel (2) because it uses dataclasses.fields internally. I'm not sure what the advice would be here, should my package detect if the caller has `from __future__ import annotations` and do something? (1) https://stackoverflow.com/questions/33533148/how-do-i-type-hint-a-method-with-the-type-of-the-enclosing-class/33533514#33533514 (2) https://pypi.org/project/dataclasses-configobj/ -- nosy: +davetapley ___ Python tracker <https://bugs.python.org/issue39442> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Subprocess Connection Error
Hello, I bought a book called Coding for Beginners to learn how to code using Python. The first few exercises went fine. When I got to the page called Recognizing types and did the exercise and saved it and tried to run the module it comes up with a Subprocess Connection Error. It says, "IDLE's subprocess didn't make connection. See the Start up failure section of the IDLE doc, online at https://docs.python.org/3/library/idle.html#startup-failure.; I went there and it said to try uninstalling python and then reinstalling it. I did this and it did the same thing again. It also said something about it is because of the antivirus software. I tried installing python on a different computer and it happened at the exact same place in the exercises in the book. I am far from being a computer whiz, just thought it would be fun to learn some simple coding. Any help would be appreciated. One more thing, the book says to save it as "types.py". Thank you, Dave Dungan -- https://mail.python.org/mailman/listinfo/python-list
Visualize dataframes in 2 lines
import sho sho.w(dataframe) Install : pip install sho Medium Article: https://medium.com/@davewd/sho-w-dataframe-my-first-package-b7242088b78f Github: https://github.com/davewd/sho -- https://mail.python.org/mailman/listinfo/python-list
[issue40134] Inconsistent ANSI escape code handling on Windows 10
New submission from Dave Rove : The correct handling of ANSI escape codes by the print() function may or may not be enabled in the Windows 10 command prompt window, depending on previous system calls. The following is quite repeatable. Comment-out the apparently meaningless os.system("") line and ANSI codes do not work, but leave that line in and ANSI codes DO work: import os os.system("") # Comment this out to disable ANSI codes ansi_red = "\x1b[31m" ansi_normal = "\x1b[0m" print(ansi_red + "This is red!" + ansi_normal) To be consistent with Python on Linux and Mac, I believe that ANSI codes should be permanently enabled in Windows 10 rather than removed. ANSI code handling was present from the start of Windows 10, so it's reasonable to presume that it's now a permanent feature of the Windows command prompt window. Either way, the inconsistency of the handling should be fixed. To emphasize that ANSI codes ARE a feature of the command prompt, comment out that line to disable the ANSI codes in print(), but redirect the output to a text file. Then display that file at the command prompt. The ANSI codes then work correctly. python myansi.py > myansi.txt type myansi.txt -- components: Windows messages: 365458 nosy: daverove, paul.moore, steve.dower, tim.golden, zach.ware priority: normal severity: normal status: open title: Inconsistent ANSI escape code handling on Windows 10 type: behavior versions: Python 3.8 ___ Python tracker <https://bugs.python.org/issue40134> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue39852] IDLE: Goto should remove selection and update the status bar
Dave Liptack added the comment: Like goto, right-click also exhibits this behavior. Should selection_clear also be added to right-click code? -- ___ Python tracker <https://bugs.python.org/issue39852> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue39852] IDLE: Copy/Paste behaves like Cut/Paste
Dave Liptack added the comment: OS: Windows 10 Pro Version: 1909 OS Build: 18363.657 Python 2.7.17 and 3.8.1 were installed from https://www.python.org/downloads/ using the Windows x86-64 executable installer (3.8.1) and Windows x86-64 MSI installer (2.7.17) Both line numbers and code context are not present To reproduce: 1) Position cursor at the start of a line of text 2) Type Shift+down arrow (to select line of text) 3) Type Ctrl+c 4) Type Alt+g (IDLE) or Ctrl+g (Notepad, Notepad++) 5) Enter line number (for example below line number = 2) 6) Type Enter 7) Type Ctrl+v Example initial text: # This is line 1 # additional line # This is a line I wish to duplicate # another additional line Resulting text in IDLE: # This is line 1 # This is a line I wish to duplicate # additional line # another additional line Resulting text in Notepad and Notepad++: # This is line 1 # This is a line I wish to duplicate # additional line # This is a line I wish to duplicate # another additional line My workaround in IDLE is to add a step between #6 and #7 above, where I mouse click at the desired paste location -- ___ Python tracker <https://bugs.python.org/issue39852> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue39852] IDLE: Copy/Paste behaves like Cut/Paste
New submission from Dave Liptack : Python 3.8.1 IDLE 3.8.1 When COPYing text in IDLE, right-click and PASTE behaves like CUT/PASTE This also occurs with COPY -> Go to Line -> PASTE This does not occur with COPY -> left-click -> PASTE -- assignee: terry.reedy components: IDLE messages: 363370 nosy: Dave Liptack, terry.reedy priority: normal severity: normal status: open title: IDLE: Copy/Paste behaves like Cut/Paste type: behavior versions: Python 3.8 ___ Python tracker <https://bugs.python.org/issue39852> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue39001] possible problem with 64-bit mingw DECREF
Dave Lawrence added the comment: traced to be a duplicate of https://bugs.python.org/issue28267 -- resolution: -> not a bug stage: -> resolved status: open -> closed ___ Python tracker <https://bugs.python.org/issue39001> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue39001] possible problem with 64-bit mingw DECREF
Dave Lawrence added the comment: by redefinining the Py_DECREF macro in my application: #define Py_DECREF(op) do { if (--op->ob_refcnt == 0) fprintf(stderr, "DECREF %s %d %p %d %s %p\n", __FILE__, __LINE__, op, Py_SIZE(op), Py_TYPE(op)->tp_name,Py_TYPE(op)->tp_dealloc ); fflush(stderr); } while(0) this outputs lines like this: DECREF vardef_file.cc 1601 09F3C728 0 generator which appears to be showing the tp_dealloc is a null pointer. -- ___ Python tracker <https://bugs.python.org/issue39001> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue39001] possible problem with 64-bit mingw DECREF
Dave Lawrence added the comment: further investigation seems to point to this being something to do with mingw and the dll. I have tried compiling the same test example on 64-bit linux and in the Ubuntu WSL on windows and it works. Tests also show that the refcount of '1' is correct and not the problem. the PyObject pointers of 02750408 are suspicious though and on sight look like 32-bit addresses -- is there some odd 32/64 bit mismatch happening somewhere even though the lib clearly links and loads the dll? -- ___ Python tracker <https://bugs.python.org/issue39001> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue39001] possible problem with 64-bit mingw DECREF
New submission from Dave Lawrence : I am calling a python method from C using the attached code. The Site.py file is: import os def find_site(): path = os.path.abspath(".") return path Cross compiled to Windows from Linux using mxe.cc and python 2.7.17 On 32-bit this runs as expected: module = 028BC710 result = 0283D6B0 Found Site at \\wsl$\Ubuntu\home\dl result = 0283D6B0 decref module = 028BC710 decref Site = \\wsl$\Ubuntu\home\dl but crashes on 64-bit, failing to DECREF result: module = 02750408 result = 00E62EF0 Found Site at \\wsl$\Ubuntu\home\dl result = 00E62EF0 decref In both cases the libpython was made using the .dll copied from the target Windows machine and pexports and dlltool to create the .a if the return value of the python is return "C:/Test/Path" it works. if you add test2 = test and return test2 it fails. if you say test2 = "".join(c for c in path) and return test2 it fails. if you set path2 = "C:/Test/Path and return test2 it works using Py_REFCNT [in the C code] shows a value of 2 for a return "c:/test" but a value of 1 a return test -- components: Library (Lib), Windows files: py.cc messages: 358033 nosy: Dave Lawrence, paul.moore, steve.dower, tim.golden, zach.ware priority: normal severity: normal status: open title: possible problem with 64-bit mingw DECREF type: crash versions: Python 2.7 Added file: https://bugs.python.org/file48767/py.cc ___ Python tracker <https://bugs.python.org/issue39001> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue38837] struct.pack: Unable to pack more than 256 bytes at a time
Dave Lotton added the comment: Mark, you are absolutely correct. I'm an idiot. Focused on wrong thing. Thank you. -- resolution: -> not a bug stage: -> resolved status: open -> closed ___ Python tracker <https://bugs.python.org/issue38837> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue38837] struct.pack: Unable to pack more than 256 bytes at a time
New submission from Dave Lotton : Using struct.pack it is not possible (Python 3.6.8 and 2.7.15) to pack more than 256 bytes at a time. This seems like an arbitrarily small number, and seems to be inconsistent with the capabilities of the unpack function, which is able to unpack a larger number of bytes. Below demonstrates the issue... >>> # Create large data set to be packed >>> data = range(0,512) >>> # Demonstrate format string for packing >>> '<%dB' % len(data) '<512B' >>> # Try to pack large data set >>> packed = pack('<%dB' % len(data), *data) Traceback (most recent call last): File "", line 1, in struct.error: ubyte format requires 0 <= number <= 255 >>> # Make data set <= 256 bytes >>> data = range(0,256) >>> packed = pack('<%dB' % len(data), *data) >>> # Data successfully packed >>> # Append another 256 bytes to packed data >>> packed += pack('<%dB' % len(data), *data) >>> # Unpack all 512 bytes >>> unpacked = unpack('<%dB' % len(packed), packed) >>> >>> unpacked (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 22 1, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 19 7, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255) The 256 byte limit on packing seems arbitrarily small and is inconsistent with the unpack function. I'm wondering if there is a rationale for this limit, or it has simply been an oversight in the implementation. I am using Mint Linux 19.2 64-bit (Ubuntu Bionic - based distro). The problem is manifested on both Python 3.6.8 and 2.7.15 included in the distro. -- components: Library (Lib) messages: 356886 nosy: Dave Lotton priority: normal severity: normal status: open title: struct.pack: Unable to pack more than 256 bytes at a time type: behavior versions: Python 2.7, Python 3.6 ___ Python tracker <https://bugs.python.org/issue38837> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: low-level csv
The few times I looked at CSV module it never looked useful to me. I seem to use shlex for everything. For example: def csv_split (s): lex = shlex.shlex(s, posix=True) lex.whitespace_split = True lex.whitespace = ',' return list(lex) will split on commas while honoring quoted values (and stripping out the quotes) Dave On 2019/11/17 08:18, Antoon Pardon wrote: This is python 2.6->2.7 and 3.5->3.7 I need to convert a string that is a csv line to a list and vice versa. I thought to find functions doing this in the csv module but that doesn't seem to be the case. I can of course write special classes that would allow for this using a csv.reader and csv.writer but that would be some convoluted code. Anyone some suggestions? -- https://mail.python.org/mailman/listinfo/python-list
Re: How to delay until a next increment of time occurs ?
Rudy, OK I'm old enough cancer to know what X10 is. :-) I wouldn't think this is too difficult to do as you're only sending. For this application IMO there is too much going on inside python that can interrupt the cycle of modulation. (Intra and Extra python; garbage collection, other processes, etc) I would drop back to a simple program in C that you execute from python to do the actual sending putting your 'message' on the command line to that program (or use a tmpfile). I think your solution will be to execute this program from python. Let me stress, my advise is doing this *reliably*. In that regard you might need look at locking your C process to 1 CPU and giving it highest priority. (man nice) Once you have this working reliably, you could then look to convert it to a python c-module to more tightly integrate it. Dave On 2019/11/14 15:00, R.Wieser wrote: Dave, Can you expand on what you are trying to accomplish with this? There is a small 433 MHz rf transmitter connected to the pin, and when I send the right pattern a wireless wall-wart will respond and switch a lamp on or off. Its just ment as an example of a real-world application of Python, nothing serious. Ofcourse, by doing so I'm learning about how to use python (and the Pi) myself too. :-) It seems a small C program or library you interface python too is a better solution. :-) I already wrote that program in C{something} (I'm not sure what my Pi offers by default) a while ago, but "ported" it to python. For the above mentioned "example" reason. ... Which is also why I didn't even try to just shell to that program, or try to interface with a C{something} library. Though doing such interfacing is in the pipeline (I've already found-and-stored some documentation about it). Regards, Rudy Wieser -- https://mail.python.org/mailman/listinfo/python-list
Re: How to delay until a next increment of time occurs ?
Can you expand on what you are trying to accomplish with this? It seems a small C program or library you interface python too is a better solution. With that said, as others mentioned you might need a real time OS or micro controller if this needs to be dead on timing. Dave On 2019/11/13 09:02, R.Wieser wrote: Hello all, I'm writing some code to toggle a pin on a Raspberry Pi, and would like to have that happen at (multiples of) 300 uSec increments. I tried time.sleep(), but that one disregards the time after the last one ends and the new one is started. In other words, all the time spend in code (or being interrupted by another thread!) between the end of the previous and the start of the current sleep throws the whole repetitive timing off. So, I'm looking for a method that will allow me to wait for a "last time plus increment". Is there one with the properties of sleep() (not just burning processor cycles way, blocking all threads), but referencing a previous time. Regards, Rudy Wieser -- https://mail.python.org/mailman/listinfo/python-list
ANNOUNCE: Thesaurus and ThesaurusCfg - recursive mapping and cfg file data types
This announcement is for a pre-release that I would like people to comment on structure, naming, etc. (Code review maybe not yet. :-) Before you say "It's all been done before." I suggest you take a closer look and I think you may conclude that what I've revised over 7 years is now interesting. --- Thesaurus is a mapping data type with key recursion and attribute aliasing. It is a subclass of dict() and compatible as a dictionary replacement baring where key path recursion may take place. ThesaurusExtended is a subclass of Thesaurus providing additional usability methods. ThesaurusCfg is a subclass of ThesaurusExtended providing a configuration file parser and per key data coercion methods. The Thesaurus family works with Python 2.6+ to 3.8+. A simple example of ThesaurusCfg -- cfgs = ''' prog.version(static_int)= 123 opt.verbose (str_to_bool) = yes hi = Hello ''' from thesauruscfg import thescfg cfg = thescfg() >>> cfg.parse(cfgs) {'prog': {'version': 123}, 'opt': {'verbose': True}, 'hi': 'Hello'} >>> cfg.opt.verbose True import json >>> print(json.dumps(cfg, indent=4, separators=(',', ': '))) { "prog": { "version": 123 }, "opt": { "verbose": true }, "hi": "Hello" } browse: https://git.cinege.com/thesaurus/ or git clone https://git.cinege.com/thesaurus/ --- Dave -- https://mail.python.org/mailman/listinfo/python-list
[issue38665] Crash when running SQLAlchemy with pyodbc
Dave Johansen added the comment: I can't. I just know that I'm running this process and this crash happens. Any recommendations on how to diagnose that? -- ___ Python tracker <https://bugs.python.org/issue38665> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue38665] Crash when running SQLAlchemy with pyodbc
New submission from Dave Johansen : We're using SQLAlchemy 1.3.10 with pyodbc 4.0.27 in the python:3.7.5-alpine docker image to connect to a MySQL 13.0.5026.0 database and it's crashing with the following error: python: malloc.c:2406: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed. ------ messages: 355830 nosy: Dave Johansen priority: normal severity: normal status: open title: Crash when running SQLAlchemy with pyodbc type: crash versions: Python 3.7 ___ Python tracker <https://bugs.python.org/issue38665> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Python shows error on line 15 that i cant fix
On Saturday, September 21, 2019 at 2:46:15 PM UTC-4, boB Stepp wrote: > On Sat, Sep 21, 2019 at 1:01 PM Dave Martin wrote: > > > > On Saturday, September 21, 2019 at 1:33:12 PM UTC-4, Terry Reedy wrote: > > > On 9/21/2019 11:53 AM, Dave Martin wrote: > [...] > > > > #get the combined data and load the fits files > > > > > > > > fits_filename="Gaia_DR2/gaiadr2_100pc.fits" > > > > df=pd.DataFrame() > > > > with fits.open(fits_filename) as data: > > > > df=pd.DataFrame(data[1].data) > > > > > > A 'with' statement is a compound statement. It must be followed by a > > > 'suite', which usually consists of an indented block of statements. > > > This is line 17 from the first non-blank line you posted. > [...] > > > Can you provide an example of how to use the suite feature. Thank you. > > Dave, you seem to have some expectation that you should be given the > answer. That is not how help is given in this forum. You are > expected to be doing the needed to work before being helped further. > You have been referred to the tutorial multiple times. Please read > it! Indentation is so fundamental to structuring Python code that it > is clear that you need grounding in Python fundamentals. Otherwise > you are essentially Easter-egging through a code sample that you have > no true understanding of. > > If you must continue to Easter-egg Python instead of reading the > tutorial (or something equivalent) then check the section of the > tutorial on files. You will find examples of the use of "with" there. > > > -- > boB Bob, You seem to have the expectation that you know more about coding than me and that you can insult me without me retaliating. If I were you, I would leave this forum and never respond to another person question again, if you think that you can rudely ransack your way through what is supposed to be a helpful tool. -Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: Python shows error on line 15 that i cant fix
On Saturday, September 21, 2019 at 1:33:12 PM UTC-4, Terry Reedy wrote: > On 9/21/2019 11:53 AM, Dave Martin wrote: > > > > # starAbsMags=df['radial_velocity'] > > > > #GaiaPandasEscapeVelocityCode > > > > import pandas as pd > > import numpy as np > > from astropy.io import fits > > import astropy > > import matplotlib.pyplot as plt > > > > > > #get the combined data and load the fits files > > > > fits_filename="Gaia_DR2/gaiadr2_100pc.fits" > > df=pd.DataFrame() > > with fits.open(fits_filename) as data: > > df=pd.DataFrame(data[1].data) > > A 'with' statement is a compound statement. It must be followed by a > 'suite', which usually consists of an indented block of statements. > This is line 17 from the first non-blank line you posted. > > Please stop spamming the list with multiple posts. Do spend a few hours > reading the tutorial until you understand my answer. > https://docs.python.org/3/tutorial/index.html Also read > https://stackoverflow.com/help/minimal-reproducible-example > so you can ask better questions. > > I presume you got "SyntaxError: expected an indented block". > A minimal example getting this error is, for instance, > > while True: > a = 1 > > -- > Terry Jan Reedy Can you provide an example of how to use the suite feature. Thank you. -- https://mail.python.org/mailman/listinfo/python-list
Re: python is bugging
On Saturday, September 21, 2019 at 12:44:27 PM UTC-4, Brian Oney wrote: > On Sat, 2019-09-21 at 08:57 -0700, Dave Martin wrote: > > On Saturday, September 21, 2019 at 11:55:29 AM UTC-4, Dave Martin > > wrote: > > > what does expected an indented block > > > > *what does an indented block mean? > > It means that the line of code belongs to a certain body as defined > above its position. > > Please follow the tutorial. > > https://docs.python.org/3/tutorial/index.html df.to_csv(r"faststars.csv", index=None,header=True) # starAbsMags=df['radial_velocity'] #GaiaPandasEscapeVelocityCode import pandas as pd import numpy as np from astropy.io import fits import astropy import matplotlib.pyplot as plt #get the combined data and load the fits files fits_filename="Gaia_DR2/gaiadr2_100pc.fits" df=pd.DataFrame() with fits.open(fits_filename) as data: df=pd.DataFrame(data[1].data) df.columns=[c.lower() for c in df.columns] print("Columns.") print(df.columns.values) print("n/n") #print out some data meta info to see what we're working with print("Number of stars:") nstars=len(df) print(nstars) distances = (df['parallax']/1000) starAbsMags =df['phot_g_mean_mag'] df = df[(df.parallax_over_error > 10 ) ] print("Left after filter: " +str(len(df)/float(nstars)*100)+" %") df.hist(column='radial_velocity') #fastdf=df[(df.radial_velocity > 200) | (df.radial_velocity < -200)] fastdf=df[(df.radial_velocity > 550)|(df.radial_velocity<-550)] print(len(fastdf)) #print(fastdf)# starTemps=df['astrometric_weight_al'] # df.plot.scatter("radial_velocity", "astrometric_weight_al", s=1, c="radial_velocity", colormap="plasma") # #df=df[(df.radial_velocity>=-550)] # #plt.axis([0,400,-800,-550]) # #plt.axis([0,400,550,800]) # plt.xlabel('weight(Au)') # plt.ylabel('Speed') # plt.title('Gaia Speed vs Weight') this is my code the error is on line 15 -- https://mail.python.org/mailman/listinfo/python-list
Re: python is bugging
On Saturday, September 21, 2019 at 11:55:29 AM UTC-4, Dave Martin wrote: > what does expected an indented block *what does an indented block mean? -- https://mail.python.org/mailman/listinfo/python-list
python is bugging
what does expected an indented block -- https://mail.python.org/mailman/listinfo/python-list
Python shows error on line 15 that i cant fix
# starAbsMags=df['radial_velocity'] #GaiaPandasEscapeVelocityCode import pandas as pd import numpy as np from astropy.io import fits import astropy import matplotlib.pyplot as plt #get the combined data and load the fits files fits_filename="Gaia_DR2/gaiadr2_100pc.fits" df=pd.DataFrame() with fits.open(fits_filename) as data: df=pd.DataFrame(data[1].data) df.columns=[c.lower() for c in df.columns] print("Columns.") print(df.columns.values) print("n/n") #print out some data meta info to see what we're working with print("Number of stars:") nstars=len(df) print(nstars) distances = (df['parallax']/1000) starAbsMags =df['phot_g_mean_mag'] df = df[(df.parallax_over_error > 10 ) ] print("Left after filter: " +str(len(df)/float(nstars)*100)+" %") df.hist(column='radial_velocity') #fastdf=df[(df.radial_velocity > 200) | (df.radial_velocity < -200)] fastdf=df[(df.radial_velocity > 550)|(df.radial_velocity<-550)] print(len(fastdf)) #print(fastdf)# starTemps=df['astrometric_weight_al'] # df.plot.scatter("radial_velocity", "astrometric_weight_al", s=1, c="radial_velocity", colormap="plasma") # #df=df[(df.radial_velocity>=-550)] # #plt.axis([0,400,-800,-550]) # #plt.axis([0,400,550,800]) # plt.xlabel('weight(Au)') # plt.ylabel('Speed') # plt.title('Gaia Speed vs Weight') -- https://mail.python.org/mailman/listinfo/python-list
Re: Formatting floating point
On 9/4/19 1:38 PM, Rhodri James wrote: On 04/09/2019 18:12, Dave via Python-list wrote: My question is why, and where do I find a reliable source of information on formatting numbers? Not interested in replacement values like '{} {}'.format(1, 2). Here: https://docs.python.org/3/library/string.html#format-specification-mini-language I suspect the thing you were overlooking was that format() expects to be given a format specification, and you gave it a format string. Instead of format(num, "{0:.1f}"), you wanted format(num, ".1f"). If you had tried "{0:.1f}".format(num) instead, you would have found that worked too. Thanks Rhodri Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: Formatting floating point
On 9/4/19 1:25 PM, Chris Angelico wrote: On Thu, Sep 5, 2019 at 3:16 AM Dave via Python-list wrote: All, I have been going in circles trying to format a floating point number so there is only 1 decimal place. In reading all of the gobble-gook that passes for Python advice, it looked like I should have done this: numStr = '3.14159' num = float(numstr) # OK so far numFmt = format(num, '{0:.1f}') # Errors on format string # --- Alternative that also does not work numFmt = float("{0:.1f}".format(numStr)) # --- numFmt = format(num, '0.1f')# Does work Let's start by eliminating a few possibilities here. Don't try formatting the original string, and don't call float() on the result afterwards; just start with a floating-point value, and then create a formatted string. If you think about starting with a value (which in this case is a number) and the need to make a displayable version (which implies that it's a string), your options basically look like this: num = 3.14159 num_fmt = format(num, ".1f") num_fmt = "{0:.1f}".format(num) num_fmt = f"{num:.1f}" All of these will give you back the string "3.1". All of them involve a format string of ".1f", and they differ only in how they're choosing which value to put there. Hopefully that will clear things up a bit. ChrisA That helps! Thanks Chris. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Formatting floating point
All, I have been going in circles trying to format a floating point number so there is only 1 decimal place. In reading all of the gobble-gook that passes for Python advice, it looked like I should have done this: numStr = '3.14159' num = float(numstr) # OK so far numFmt = format(num, '{0:.1f}') # Errors on format string # --- Alternative that also does not work numFmt = float("{0:.1f}".format(numStr)) # --- numFmt = format(num, '0.1f')# Does work My question is why, and where do I find a reliable source of information on formatting numbers? Not interested in replacement values like '{} {}'.format(1, 2). Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: Application Preferences
On 8/19/19 1:53 PM, Barry Scott wrote: On 19 Aug 2019, at 13:43, Dave via Python-list wrote: The plan for an app that I'm doing was to use SQLite for data and to hold the preference settings as some apps do. The plan was changed last week to allow the user to select the location of the data files (SQLite) rather than putting it where the OS would dictate. Ok with that, but it brings up some questions. First, I will need to have a file that points to the location of the data file since that can't be hard coded. Second, if I have to have a file that is likely part of the application group of files, would it make more sense to use a more traditional preferences file? How have other Python app developers done in this case? There are expected locations for config files and data files on each OS. On macOS you would use ~/Library/Preferences/ and put a file or a folder of files in there. The convention is use your website name as the base name of the file or folder. For example for scm-workbench I use: org.barrys-emacs.scm-workbench as the folder name for all the scm-workbench files. On Windows you can use a file or folder in %APPDATA% that is named after your app. You should find the folder by doing a win32 API call to get the value. See getPreferencesDir() in https://github.com/barry-scott/scm-workbench/blob/master/Source/Common/wb_platform_win32_specific.py <https://github.com/barry-scott/scm-workbench/blob/master/Source/Common/wb_platform_win32_specific.py> for how to get the value. On Linux the XDG spec says that you should put config files in ~/.config/ and data files in ~/.local/share/. Doing XDG to the spec is a little involved. I have some experimental code that implements the logic for config the XdgConfigPath class in: https://github.com/barry-scott/CLI-tools/blob/master/Source/smart_find/__init__.py <https://github.com/barry-scott/CLI-tools/blob/master/Source/smart_find/__init__.py> Putting a file directly in the $HOME folder is no longer recommended. The format of the config data you are free to choose. I have been using JSON files recently as it allow for structured data. Barry Barry, and all, I agree that various OS's have a favorite place to put things. Python has a library that will help. However, there are valid reasons to let the customer choose. Perhaps the drive/folder is a journaling one, or one that is backed up multiple times per day. My take is to start with the OS solution, but let the customer decide. How did this thread show up in the SQLite mailing list anyway? Really has nothing to do with SQLite that I can see. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: Application Preferences
On 8/19/19 9:22 AM, Malcolm Greene wrote: Hi Dave, The plan for an app that I'm doing was to use SQLite for data and to hold the preference settings as some apps do. The plan was changed last week to allow the user to select the location of the data files (SQLite) rather than putting it where the OS would dictate. Ok with that, but it brings up some questions. First, I will need to have a file that points to the location of the data file since that can't be hard coded. Second, if I have to have a file that is likely part of the application group of files, would it make more sense to use a more traditional preferences file? How have other Python app developers done in this case? We handle the "where is my config file" question by defaulting to script's current directory, then a script-specific folder within their home directory. Users can override that behavior by setting a script specific environment variable or by using a command line switch to point to a different location or config file. We store our preferences in an INI style config file which we've found easier to support when there's problems. Malcolm Malcolm, Thanks for the reply. I agree that a traditional INI file is the easiest way, especially since Python supports them. So if I understand you, your apps look like this: -App Dir | +-App Code Folder | +-(File to direct to home folder) -Home Folder (the default location, but user can select other locations) | +-App INI Folder | +-App INI file -- https://mail.python.org/mailman/listinfo/python-list
Application Preferences
The plan for an app that I'm doing was to use SQLite for data and to hold the preference settings as some apps do. The plan was changed last week to allow the user to select the location of the data files (SQLite) rather than putting it where the OS would dictate. Ok with that, but it brings up some questions. First, I will need to have a file that points to the location of the data file since that can't be hard coded. Second, if I have to have a file that is likely part of the application group of files, would it make more sense to use a more traditional preferences file? How have other Python app developers done in this case? Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: Create multiple sqlite tables, many-to-many design
On 8/13/19 5:46 PM, Rich Shepard wrote: On Tue, 13 Aug 2019, Rich Shepard wrote: Read Joe Celko's books, starting with his SQL Programming Guide, then SQL That should be SQL Programming Style Rich Rich, On my next trip to BN I'll see if they have them. That is long term though. Right now I just need to know how to populate the join table and anything else that has escaped me. SQL is cool. SQL + Python (or C or C++ or Java) is more cool. Lot easier to understand than pointer math in C. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: Create multiple sqlite tables, many-to-many design
On 8/13/19 2:59 PM, Chris Angelico wrote: On Wed, Aug 14, 2019 at 4:50 AM Dave via Python-list wrote: Some of the tables are related. For example: Hiking_Table Trails_TableJoining_Table -- hike_id PK trail_id PKhike_id FK hike_date TEXT trail_name TEXTtrail_id FK hike_destination TEXTtrail_rating REAL hike_rating REALtrail_comments TEXT hike_comments TEXT So far, so good. I know how to create the tables. What I am struggling with is how do I insert data into the joining table or don"t I? If so, do I need to query the other two tables to get the auto-number ID's? Some things I have read suggest that the joining table just contains references, so there is no actual insert. A pointer to information how to do this would be appreciated. As for queries, I think I use joins, but a pointer on how to do this would also be appreciated. The joining table is a real thing, and will have real inserts. It might be easier to think of this as two separate one-to-many relationships; for the sake of demonstration, I'm going to add another column to your joining table. hike_sections ==> hike_id references hikes, trail_id references trails, companion_name You've decided to have someone with you for some sections of your hike. As such, what we have is a number of "mini-hikes" that make up a single hike (that's a one-to-many relationship between hikes and sections), and also a single trail can be a section of any number of hikes (so, another one-to-many relationship between trails and sections). For any given section, there is exactly one companion. Does this make the many-to-many relationship a bit easier to understand? It'll work exactly the same way even if you have no ancillary information in that joining table. ChrisA Chris, Thanks for the note. I get the theory of MTM and the join table. It is the implementation I don't get. Let me see if I can demonstrate my confusion using pseudo code. def dbTables_create (dbpath): sql_HikeTable = """ CREATE TABLE IF NOT EXISTS hike ( hike_id INTEGER AUTO_INCREMENT PRIMARY KEY, hike_date TEXT, hike_destination TEXT, hike_rating REAL, hike_comments TEXT ) """ sql_TrailTable = """ CREATE TABLE IF NOT EXISTS trail ( trail_id INTEGER AUTO_INCREMENT PRIMARY KEY, trail_name TEXT, trail_rating REAL, trail_comment TEXT ) """ sql_JoiningTable = """ CREATE TABLE IF NOT EXISTS hike_trail ( hike_id INTEGER trail_id INTEGER ) """ # Some more code to open connection, create cursor, execute SQL. def getUserInput (): # Code to get the user input. # The user input is: hdate = "2019-05-28" hdestination = "Top of White Face Mountain, NY." hrating = 5.0 # Rating scale 1.0 (bad) to 5.0 (perfect). hcomments "Got to do again. Better shoes needed." tname1 = "Brookside" trating1 = 4.5 tcomments1 = "Easy" tname2 = "Wilmington Trail" trating2 = 4.9 tcomments2 = "Awesome!!" def dbDataInsert(): sql_HikeInsert = """ INSERT INTO hike ( hike_date, hike_destination, hike_rating, hike_comments ) VALUES ( hdate, hdestination, hrating, hcomments ) """ sql_TrailInsert = """ NSERT INTO trail ( trail_name, trail_rating, trail_comment ) VALUES ( tname1, trating1, tcomments1 ) """ sql_TrailInsert = """ NSERT INTO trail ( trail_name, trail_rating, trail_comment ) VALUES ( tname2, trating2, tcomments2 ) """ """ ---> Now what? I need to populate the join (hike_trail) table. Do I query the tables to get the id's? Is there another way? This is the part I really don't get. """ Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: Create multiple sqlite tables, many-to-many design
On 8/13/19 4:45 PM, MRAB wrote: On 2019-08-13 19:59, Chris Angelico wrote: On Wed, Aug 14, 2019 at 4:50 AM Dave via Python-list wrote: Some of the tables are related. For example: Hiking_Table Trails_Table Joining_Table - - hike_id PK trail_id PK hike_id FK hike_date TEXT trail_name TEXT trail_id FK hike_destination TEXT trail_rating REAL hike_rating REAL trail_comments TEXT hike_comments TEXT So far, so good. I know how to create the tables. What I am struggling with is how do I insert data into the joining table or don"t I? If so, do I need to query the other two tables to get the auto-number ID's? Some things I have read suggest that the joining table just contains references, so there is no actual insert. A pointer to information how to do this would be appreciated. As for queries, I think I use joins, but a pointer on how to do this would also be appreciated. The joining table is a real thing, and will have real inserts. It might be easier to think of this as two separate one-to-many relationships; for the sake of demonstration, I'm going to add another column to your joining table. hike_sections ==> hike_id references hikes, trail_id references trails, companion_name You've decided to have someone with you for some sections of your hike. As such, what we have is a number of "mini-hikes" that make up a single hike (that's a one-to-many relationship between hikes and sections), and also a single trail can be a section of any number of hikes (so, another one-to-many relationship between trails and sections). For any given section, there is exactly one companion. Does this make the many-to-many relationship a bit easier to understand? It'll work exactly the same way even if you have no ancillary information in that joining table. Might I also suggest dropping unnecessary prefixes from the field names. For example, "hike_comments" in "Hiking_Table" can be called just "comments" because it's clear from the context that a field called "comments" in the hiking table will contain comments about hiking, if you see what I mean. I do indeed. I did that so it was easy for everyone to follow. Having started with assm. and C, I have to remind myself to be more explanatory in naming. Guess I over-did it. The actual code is different. htbl, ttbl, jtbl, etc. Too short? Dave, -- https://mail.python.org/mailman/listinfo/python-list
Create multiple sqlite tables, many-to-many design
Oops! Just posted this to the wrong newsgroup. Sorry!!! I'm doing a Python app that uses SQLite, and am stumbling on a few questions. I've read a lot of books and documentation, but two questions still allude me. Hope someone that been there done this can help. Below is a note I sent to the SQLite mailing list yesterday. So far, nothing. Need to get going, so many thanks! I'm doing an app. that uses sqlite, and has a many-to-many relationship. The areas I need some guidance are: * Best way to create multiple tables the first time the app. is started. * How to create a MTM relationship and add/modify data. I can create tables (Python) by putting the code in discrete functions for each table and passing just the path to the database. I can also create a calling function that gets a connection and passes that. What is the pro-con of each since each seems to work? Better ideas? Some of the tables are related. For example: Hiking_Table Trails_TableJoining_Table -- hike_id PK trail_id PKhike_id FK hike_date TEXT trail_name TEXTtrail_id FK hike_destination TEXTtrail_rating REAL hike_rating REALtrail_comments TEXT hike_comments TEXT So far, so good. I know how to create the tables. What I am struggling with is how do I insert data into the joining table or don"t I? If so, do I need to query the other two tables to get the auto-number ID's? Some things I have read suggest that the joining table just contains references, so there is no actual insert. A pointer to information how to do this would be appreciated. As for queries, I think I use joins, but a pointer on how to do this would also be appreciated. Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
Python/SQLite best practices
I'm looking for some tips from experienced hands on on this subject. Some of the areas of interest are (feel free to add more): * Passing connections and cursors - good, bad indifferent? I try to avoid passing file handles unless necessary, so I view connections and cursors the same. Though that said, I'm not aware of any specific problems in doing so. For designs with multiple tables: * Better to pass an sql string to functions that create/add data/update/delete data and pass them to create, insert, update, delete functions; or have those functions for each table? Taking table creation for example, if there are five tables, and the sql string is passed, there would need to be six functions to do it, though the complexity of each function may be reduced a little. [table1create with sql and establishing a cursor, to table5create and then a function that executes the sql]. Best way to establish the connection and cursor, as well as close them? I have seen many ways to do this, and know that the with block can be used to create a connection and close it automatically, but the same is not true of the cursor. Also, using only a with block does not handle any errors as well as a try/with. For example: | try: | # Use with block to create connection – it will close self. | with sqlite3.connect(path) as conn: | cur = conn.cursor() | cur.execute(sql_ProjectsTable) | cur.close() | except Error as e: | print(e) What else? Dave, -- https://mail.python.org/mailman/listinfo/python-list
[issue37546] colors in ttk treeview tags are ignored
New submission from dave : The following example code fails in Python 3.7.3 64 bit (both lines are displayed in black). It works correctly in 3.7.2 and earlier. import tkinter as tk import tkinter.ttk as ttk root = tk.Tk() ttk.Label(root, text='This is a RED label', foreground='red').pack() tree = ttk.Treeview(root) tree.tag_configure('RED_TAG', foreground='red', font=('arial', 12)) tree.insert('', tk.END, text='Black line') tree.insert('', tk.END, text='Red line', tag='RED_TAG') tree.pack() root.mainloop() -- components: Tkinter messages: 347618 nosy: dave9000 priority: normal severity: normal status: open title: colors in ttk treeview tags are ignored type: behavior versions: Python 3.7 ___ Python tracker <https://bugs.python.org/issue37546> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue37362] test_gdb must not fail on "unexpected" messages written into stderr
Dave Malcolm added the comment: I think when I wrote this I was over-optimistically thinking that we could just add more patterns, but if it's becoming a pain, then your approach looks good to me. -- nosy: +dmalcolm ___ Python tracker <https://bugs.python.org/issue37362> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue37092] LoggerAdapter doesn't have fatal() like Logger
New submission from Dave Johansen : Using LoggerAdapter is a convenient way to add extra info to all logs, but it doesn't have the fatal() method like Logger, so it isn't a drop in replacement like it should be. -- components: Library (Lib) messages: 343941 nosy: Dave Johansen priority: normal severity: normal status: open title: LoggerAdapter doesn't have fatal() like Logger type: behavior versions: Python 3.7 ___ Python tracker <https://bugs.python.org/issue37092> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue35070] test_posix fails on macOS 10.14 Mojave
Dave Page added the comment: The submitted patch from websurfer5 resolves the issue for me. -- ___ Python tracker <https://bugs.python.org/issue35070> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Python best practice instantiating classes in app
On 4/29/19 3:26 PM, Terry Reedy wrote: On 4/29/2019 1:38 PM, Dave wrote: As apps get more complex we add modules, or Python files, to organize things. One problem I have is a couple of data classes (list of dictionary objects) in a few modules that are used in a number of the other modules. For example a list of meter reading dictionaries in one module is used by the user interface module to get the data from the user, a report module to display the data, and a file module to save and retrieve the data to/from file. All the modules need to use the same instance of the list classes. There are a number of ways to do this. One is a module that creates the objects, then import that module into all of the others. Works well, You can have one *or more* such modules. Perhaps you already do. but may not be the best way to do the job. In what way do you consider it unsatisfactory. It is not that I consider it unsatisfactory as much as I'm looking for the best way. I am constantly amazed at the thought that has been given to this language (with the exception of access modifiers - perhaps, and lack of a case statement), and often find that there is a better way of doing everything. A slight variation is to do this in the main module, but the main module has to be imported into the others. Avoid import loops unless really necessary. They often work, but when they don't ... its a pain. Since I use the main module as a calling module to load data, start the user interface, and to close things down, it may not be the best place to also create the classes. Another way to do this is have a line in each module to check the name. If it is the module name, then create the class and then import these modules in all the others. A tad messy and maybe a little confusing. Right. -- https://mail.python.org/mailman/listinfo/python-list
Python best practice instantiating classes in app
As apps get more complex we add modules, or Python files, to organize things. One problem I have is a couple of data classes (list of dictionary objects) in a few modules that are used in a number of the other modules. For example a list of meter reading dictionaries in one module is used by the user interface module to get the data from the user, a report module to display the data, and a file module to save and retrieve the data to/from file. All the modules need to use the same instance of the list classes. There are a number of ways to do this. One is a module that creates the objects, then import that module into all of the others. Works well, but may not be the best way to do the job. A slight variation is to do this in the main module, but the main module has to be imported into the others. Since I use the main module as a calling module to load data, start the user interface, and to close things down, it may not be the best place to also create the classes. Another way to do this is have a line in each module to check the name. If it is the module name, then create the class and then import these modules in all the others. A tad messy and maybe a little confusing. So what are the suggestions from people that have been down this road before? Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
[issue36277] pdb's recursive debug command is not listed in the docs
Change by Dave Nguyen : -- keywords: +patch pull_requests: +12796 stage: needs patch -> patch review ___ Python tracker <https://bugs.python.org/issue36277> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue35070] test_posix fails on macOS 10.14 Mojave
Dave Page added the comment: I'm seeing what appears to my uneducated eyes to be the same failure on Mojave, on a brand new machine which is entirely standalone: 12:16:00 0:00:07 load avg: 4.24 [133/416/1] test_posix failed 12:16:00 test test_posix failed -- Traceback (most recent call last): 12:16:00 File "/Users/jenkins/workspace/python-macos-build/Python-3.7.2/Lib/test/test_posix.py", line 1026, in test_getgrouplist 12:16:00 self.assertIn(group, posix.getgrouplist(user, group)) 12:16:00 OSError: [Errno 25] Inappropriate ioctl for device 12:16:00 0:00:07 load avg: 4.24 [134/416/1] test_ast passed System info: pgabf-macos2:Python-3.7.2 jenkins$ gcc --version Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/c++/4.2.1 Apple LLVM version 10.0.1 (clang-1001.0.46.3) Target: x86_64-apple-darwin18.2.0 Thread model: posix InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin pgabf-macos2:Python-3.7.2 jenkins$ system_profiler SPSoftwareDataType Software: System Software Overview: System Version: macOS 10.14.3 (18D42) Kernel Version: Darwin 18.2.0 Boot Volume: Macintosh HD Boot Mode: Normal Computer Name: pgabf-macos2 User Name: Jenkins (jenkins) Secure Virtual Memory: Enabled System Integrity Protection: Enabled Time since boot: 10 days 1:30 Happy to provide any additional info or try out patches if anyone wants. -- nosy: +Dave Page ___ Python tracker <https://bugs.python.org/issue35070> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: How call method from a method in same class?
On 4/1/19 10:29 PM, Cameron Simpson wrote: On 01Apr2019 22:02, Dave wrote: As classes get more complex, it is good to call a function to do some of the processing, and make the code easier to follow. My question is how to do that? I've attached some silly code to illustrate the point. The error is: name 'validScale' is not defined. Well, yes it is, but maybe not the correct way. Suggestions? It is and it isn't. See below: class TempConverter(): """ Temperature Converter converts a tempeature from one scale to another scale. For example: 32, F, C will return 0 degrees C """ [...] def validScale(self, scaleName): if scaleName.upper == 'F' or 'C' or 'K': return True else: return False def convertTemp(self): """ Converts temperature scale if scales valid.""" if validScale(self.scale): scaleValid = True [...] It is an instance method, so: if self.validScale(self.scale) would resolve the name. However, there are several things worth discussing here. First up, validScale itself returns a Boolean, so just return the test result. Change: if scaleName.upper == 'F' or 'C' or 'K': return True else: return False into: return scaleName.upper == 'F' or 'C' or 'K' Second, the condition is buggy. You want this: return scaleName.upper() in ('F', 'C', 'K') i.e. you need to call (the "()") the .upper method, and you need to check if the result is in your collection of valid results. This expression: value == A or B or C means: True if value == A, otherwise B if B is true, otherwise C. The next thing to observe is that you're testing whether self.scale is valid. Normal practice would be to make that test in __init__, and raise a ValueError if it is not so: def __init__(self, .scale...): if scale.upper() not in ('F', 'C', 'K'): raise ValueError("invalid scale %r: expected one of F, C or K" % (scale,)) why recite the scale in the message? Because it makes the offending value obvious. In particular, if for example you called this incorrectly and had the temperature in there instead of the scale that will be trivial to debug from the message. Of course, you actually want to be able to test any scal evalue for validity, not just the one stuffed into your instance (.scale). So lets revisit the validScale method: def validScale(self, scale): return scaleName.upper() in ('F', 'C', 'K') You'll notice that it doesn't depend in "self". Or, for that matter, the class. So this is a "static" method: a function defined in the class for conceptual clarity, but not with any dependence on the class itself or a particular class instance. So: @staticmethod def validScale(scale): return scaleName.upper() in ('F', 'C', 'K') In __init__, and elsewhere, you can still call this from the instance: def __init__(self, .scale...): if not self.validScale(scale): raise ValueError("invalid scale %r: expected one of F, C or K" % (scale,)) You can also call this from _outside_ the class, for example for other validation: scale = input("Enter a temperate scale name (F, C or K): ") if not TempConverter.validScale(scale): print("Bad! Bad user!") newScaleValid = True Again, validScale returns a Boolean. So you could have just gone: newScaleValid = self.validScale(newScale) if scaleValid and newScaleValid: print('Scale converted') else: msg = "There was and error with the scales entered.\n" msg = msg + "You entered: " + self.scale msg = msg + ' ' 'and' + self.newScale print(msg) if __name__ == "__main__": myclass = TempConverter(32, 'f', 'c') myclass.convertTemp() My personal inclination would be do define a Temperature class with a convert function to be used like this: temp = Temperature(32, 'f') tempC = temp.convert('c') This reduces the complexity of the class and IMO makes it easier to use elsewhere. BTW, you get an instance back from tempConverter(...), not a class. So don't call it "myclass". Cheers, Cameron Simpson Cameron, I'm going to need a while to work through this. As I mentioned, this was quick and dirty code just to illustrate a point - not intended to be good code. So I'll take a close read tomorrow. Thanks again!! Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: How call method from a method in same class?
On 4/1/19 10:02 PM, Dave wrote: As classes get more complex, it is good to call a function to do some of the processing, and make the code easier to follow. My question is how to do that? I've attached some silly code to illustrate the point. The error is: name 'validScale' is not defined. Well, yes it is, but maybe not the correct way. Suggestions? Dave, class TempConverter(): """ Temperature Converter converts a tempeature from one scale to another scale. For example: 32, F, C will return 0 degrees C """ def __init__(self, temperature, scale, newScale): self.temperature = temperature self.scale = scale self.newScale = newScale def validScale(self, scaleName): if scaleName.upper == 'F' or 'C' or 'K': return True else: return False def convertTemp(self): """ Converts temperature scale if scales valid.""" if validScale(self.scale): scaleValid = True if validScale(self.newScale): newScaleValid = True if scaleValid and newScaleValid: print('Scale converted') else: msg = "There was and error with the scales entered.\n" msg = msg + "You entered: " + self.scale msg = msg + ' ' 'and' + self.newScale print(msg) if __name__ == "__main__": myclass = TempConverter(32, 'f', 'c') myclass.convertTemp() Thanks all for your (ready, wait for it) self-lessness help (get it?) Dave (laughing) -- https://mail.python.org/mailman/listinfo/python-list
Re: How call method from a method in same class?
On 4/1/19 10:12 PM, Irv Kalb wrote: On Apr 1, 2019, at 7:02 PM, Dave wrote: As classes get more complex, it is good to call a function to do some of the processing, and make the code easier to follow. My question is how to do that? I've attached some silly code to illustrate the point. The error is: name 'validScale' is not defined. Well, yes it is, but maybe not the correct way. Suggestions? Dave, class TempConverter(): """ Temperature Converter converts a tempeature from one scale to another scale. For example: 32, F, C will return 0 degrees C """ def __init__(self, temperature, scale, newScale): self.temperature = temperature self.scale = scale self.newScale = newScale def validScale(self, scaleName): if scaleName.upper == 'F' or 'C' or 'K': return True else: return False def convertTemp(self): """ Converts temperature scale if scales valid.""" if validScale(self.scale): scaleValid = True if validScale(self.newScale): newScaleValid = True if scaleValid and newScaleValid: print('Scale converted') else: msg = "There was and error with the scales entered.\n" msg = msg + "You entered: " + self.scale msg = msg + ' ' 'and' + self.newScale print(msg) if __name__ == "__main__": myclass = TempConverter(32, 'f', 'c') myclass.convertTemp() -- https://mail.python.org/mailman/listinfo/python-list To answer your specific question, you call a method in the same class by calling: self.methodName For example: self.validScale However, once you fix that, you wind find that the if statement in that method is not built correctly. Also, since the variable self.scale is already set in your __init__ method, there is no need to pass it into your function. You could just use self.scale inside that method. Irv Irv, Thanks for the response! I realize the code is junk - just done to illustrate the problem. Dave, -- https://mail.python.org/mailman/listinfo/python-list
How call method from a method in same class?
As classes get more complex, it is good to call a function to do some of the processing, and make the code easier to follow. My question is how to do that? I've attached some silly code to illustrate the point. The error is: name 'validScale' is not defined. Well, yes it is, but maybe not the correct way. Suggestions? Dave, class TempConverter(): """ Temperature Converter converts a tempeature from one scale to another scale. For example: 32, F, C will return 0 degrees C """ def __init__(self, temperature, scale, newScale): self.temperature = temperature self.scale = scale self.newScale = newScale def validScale(self, scaleName): if scaleName.upper == 'F' or 'C' or 'K': return True else: return False def convertTemp(self): """ Converts temperature scale if scales valid.""" if validScale(self.scale): scaleValid = True if validScale(self.newScale): newScaleValid = True if scaleValid and newScaleValid: print('Scale converted') else: msg = "There was and error with the scales entered.\n" msg = msg + "You entered: " + self.scale msg = msg + ' ' 'and' + self.newScale print(msg) if __name__ == "__main__": myclass = TempConverter(32, 'f', 'c') myclass.convertTemp() -- https://mail.python.org/mailman/listinfo/python-list
Re: configparser - which one?
On 3/26/19 4:29 AM, Terry Reedy wrote: On 3/25/2019 8:10 PM, Dave wrote: I use Python3 3, and expected learning how to use configparser would be no big deal. Well! Seems there is configparser, stdconfigparser, and configparser is what IDLE uses. I would read the extra or deleted features of the others and see if they apply to your client's project. safeconfigparser, and multiple ways to set the section and entries to the section. A little confusing. I want to future-proof may code, so what should I be using? As for setting the sections and entries, the following both work. from configparser import ConfigParser # Python 3 syntax parser = ConfigParser() parser['DEFAULT'] = {'Language': 'English', 'Units': 'English', 'UseDefaults': 'True', 'NumberRidesDisplay': '30', 'Pi': '3.14'} The dict interface is newer but I doubt that the older one will go away. (IDLE uses it because it predates the dict interface. Since this code is pretty static, I do not currently see a payoff for conversion.) parser.add_section('Default') parser.set('default', 'language', 'english') parser.set('default', 'units_measure', 'english') parser.set('default', 'background_color', 'white') parser.set('default', 'useDefaults', 'true') parser.set('default', 'numToDisp', '12') parser.set('default', 'pi', '3.14') The advantage of the former is that it will handle 'DEFAULT', while the last one won't. I like the former, but not sure if it is the future. We do not remove things and break backwards compatibility lightly. Thanks everyone. So, I'll use configparser, but I do like the dictionary API as it makes the code a little easier as I can pass as arguments a section name and a dictionary with the contents to a function to write the complete section. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: configparser - which one?
On 3/25/19 10:58 PM, DL Neil wrote: Dave, On 26/03/19 1:10 PM, Dave wrote: I use Python3 3, and expected learning how to use configparser would be no big deal. Well! Seems there is configparser, stdconfigparser, and safeconfigparser, and multiple ways to set the section and entries to the section. A little confusing. I want to future-proof may code, so what should I be using? (with apologies for not answering the question directly) After striking this problem, I was encouraged to take a look at JSON, and thence YAML. Once there, as they say, didn't look back! - multi-dimensional possibilities, cf .ini - similarity/correspondence with Python data structures - convenient PSL - easily adopted by (power-)users, cf Python code WebRefs: - similar Q: https://stackoverflow.com/questions/5055042/whats-the-best-practice-using-a-settings-file-in-python - article: https://martin-thoma.com/configuration-files-in-python/ - similar discussion: https://stackoverflow.com/questions/3085029/pros-and-cons-for-different-configuration-formats Wish I could do that. Customer wants .ini. I would need to sell them on an alternative. The issue is human readable - .ini is easier for people to understand. Dave, -- https://mail.python.org/mailman/listinfo/python-list
configparser - which one?
I use Python3 3, and expected learning how to use configparser would be no big deal. Well! Seems there is configparser, stdconfigparser, and safeconfigparser, and multiple ways to set the section and entries to the section. A little confusing. I want to future-proof may code, so what should I be using? As for setting the sections and entries, the following both work. from configparser import ConfigParser # Python 3 syntax parser = ConfigParser() parser['DEFAULT'] = {'Language': 'English', 'Units': 'English', 'UseDefaults': 'True', 'NumberRidesDisplay': '30', 'Pi': '3.14'} parser.add_section('Default') parser.set('default', 'language', 'english') parser.set('default', 'units_measure', 'english') parser.set('default', 'background_color', 'white') parser.set('default', 'useDefaults', 'true') parser.set('default', 'numToDisp', '12') parser.set('default', 'pi', '3.14') The advantage of the former is that it will handle 'DEFAULT', while the last one won't. I like the former, but not sure if it is the future. Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Creating GUI Applications with wxPython
On 2/27/19 11:38 AM, Rhodri James wrote: On 27/02/2019 15:37, Dave wrote: * GUI must support all desktops with a native look and feel. Kivy fails this one. Will have mobile apps later in the year, so it would be nice if one GUI fits all, but am ok with 2 gui's if needed. This requirement will cause you endless pain, particularly when mobiles enter the picture. I'm not convinced it's a completely good idea; a sensible UI for a desktop probably won't be sensible for a phone and vice versa Agreed - that is why I'm open to two GUI kits. Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Creating GUI Applications with wxPython
Sorry about the duplicate messages - bad hair day! Dave, On 2/27/19 10:38 AM, Dave wrote: On 1/14/19 2:08 PM, Mike Driscoll wrote: Hi, I just thought I would let you all know that I am working on my 2nd wxPython book, "Creating GUI Applications with wxPython". This one will be about actually creating small runnable applications instead of just recipes like my Cookbook did. I hope to have 8-10 working applications included with the book. You can read more about it here if you are interested: https://www.blog.pythonlibrary.org/2019/01/14/creating-gui-applications-with-wxpython-kickstarter/ Feel free to ask me questions about it too. Thanks, Mike Mike, I have two Python 3 (3.6) apps that will get the full GUI treatment very soon. I'm in the process of choosing a GUI, and that may be where you/your book can help. Seems this is not a trivial effort (wishing that Python was like VB6 from the 90's). Anyway, here is what I am looking for - hopefully it helps guide you. * GUI relatively easy to understand and implement. easyGUI is truly easy in all areas, but fails some of my other requirements. The QT/PyQT/PySide2 situation is a mess - which one to use, why, any implementation differences, etc. * Performance is very good. Users hate to wait - for anything! * Lots of widgets! I'll need a spreadsheet-like widget, a form widget to enter information on parts, activities, etc., splash screen that the code can talk to while the app is loading, and the big one - a cross-platform printer widget that works with Windows and Mac/Unix/CUPS. A network widget may also be good. * A GUI designer may be good. Currently there is Glade for GTK, and QT-Designer for QT. * GUI must support all desktops with a native look and feel. Kivy fails this one. Will have mobile apps later in the year, so it would be nice if one GUI fits all, but am ok with 2 gui's if needed. * A great book taking me from beginner to expert. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Creating GUI Applications with wxPython
On 1/14/19 2:08 PM, Mike Driscoll wrote: Hi, I just thought I would let you all know that I am working on my 2nd wxPython book, "Creating GUI Applications with wxPython". This one will be about actually creating small runnable applications instead of just recipes like my Cookbook did. I hope to have 8-10 working applications included with the book. You can read more about it here if you are interested: https://www.blog.pythonlibrary.org/2019/01/14/creating-gui-applications-with-wxpython-kickstarter/ Feel free to ask me questions about it too. Thanks, Mike Mike, I have two Python 3 (3.6) apps that will get the full GUI treatment very soon. I'm in the process of choosing a GUI, and that may be where you/your book can help. Seems this is not a trivial effort (wishing that Python was like VB6 from the 90's). Anyway, here is what I am looking for - hopefully it helps guide you. * GUI relatively easy to understand and implement. easyGUI is truly easy in all areas, but fails some of my other requirements. The QT/PyQT/PySide2 situation is a mess - which one to use, why, any implementation differences, etc. * Performance is very good. Users hate to wait - for anything! * Lots of widgets! I'll need a spreadsheet-like widget, a form widget to enter information on parts, activities, etc., splash screen that the code can talk to while the app is loading, and the big one - a cross-platform printer widget that works with Windows and Mac/Unix/CUPS. A network widget may also be good. * A GUI designer may be good. Currently there is Glade for GTK, and QT-Designer for QT. * GUI must support all desktops with a native look and feel. Kivy fails this one. Will have mobile apps later in the year, so it would be nice if one GUI fits all, but am ok with 2 gui's if needed. * A great book taking me from beginner to expert. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Creating GUI Applications with wxPython
On 1/14/19 2:08 PM, Mike Driscoll wrote: Hi, I just thought I would let you all know that I am working on my 2nd wxPython book, "Creating GUI Applications with wxPython". This one will be about actually creating small runnable applications instead of just recipes like my Cookbook did. I hope to have 8-10 working applications included with the book. You can read more about it here if you are interested: https://www.blog.pythonlibrary.org/2019/01/14/creating-gui-applications-with-wxpython-kickstarter/ Feel free to ask me questions about it too. Thanks, Mike Mike, I have two Python 3 (3.6) apps that will get the full GUI treatment very soon. I'm in the process of choosing a GUI, and that may be where you/your book can help. Seems this is not a trivial effort (wishing that Python was like VB6 from the 90's). Anyway, here is what I am looking for - hopefully it helps guide you. * GUI relatively easy to understand and implement. easyGUI is truly easy in all areas, but fails some of my other requirements. The QT/PyQT/PySide2 situation is a mess - which one to use, why, any implementation differences, etc. * Performance is very good. Users hate to wait - for anything! * Lots of widgets! I'll need a spreadsheet-like widget, a form widget to enter information on parts, activities, etc., splash screen that the code can talk to while the app is loading, and the big one - a cross-platform printer widget that works with Windows and Mac/Unix/CUPS. A network widget may also be good. * A GUI designer may be good. Currently there is Glade for GTK, and QT-Designer for QT. * GUI must support all desktops with a native look and feel. Kivy fails this one. Will have mobile apps later in the year, so it would be nice if one GUI fits all, but am ok with 2 gui's if needed. * A great book taking me from beginner to expert. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Creating GUI Applications with wxPython
On 1/14/19 2:08 PM, Mike Driscoll wrote: Hi, I just thought I would let you all know that I am working on my 2nd wxPython book, "Creating GUI Applications with wxPython". This one will be about actually creating small runnable applications instead of just recipes like my Cookbook did. I hope to have 8-10 working applications included with the book. You can read more about it here if you are interested: https://www.blog.pythonlibrary.org/2019/01/14/creating-gui-applications-with-wxpython-kickstarter/ Feel free to ask me questions about it too. Thanks, Mike Mike, I have two Python 3 (3.6) apps that will get the full GUI treatment very soon. I'm in the process of choosing a GUI, and that may be where you/your book can help. Seems this is not a trivial effort (wishing that Python was like VB6 from the 90's). Anyway, here is what I am looking for - hopefully it helps guide you. * GUI relatively easy to understand and implement. easyGUI is truly easy in all areas, but fails some of my other requirements. The QT/PyQT/PySide2 situation is a mess - which one to use, why, any implementation differences, etc. * Performance is very good. Users hate to wait - for anything! * Lots of widgets! I'll need a spreadsheet-like widget, a form widget to enter information on parts, activities, etc., splash screen that the code can talk to while the app is loading, and the big one - a cross-platform printer widget that works with Windows and Mac/Unix/CUPS. * GUI must support all desktops with a native look and feel. Kivy fails this one. Will have mobile apps later in the year, so it would be nice if one GUI fits all, but am ok with 2 gui's if needed. * A great book taking me from beginner to expert. Dave, -- https://mail.python.org/mailman/listinfo/python-list
[issue32972] unittest.TestCase coroutine support
Dave Shawley added the comment: PR 10296 is my implementation of a unittest.TestCase subclass solution to this issue. This comment explains the approach and rationale in detail. Let's discuss this and see if the implementation meets expectations or should be abandoned. I refactored unittest.TestCase to isolate the running of test methods into a new helper method named _runTest and add a new hook named _terminateTest. The _runTest method is used to customize test method execution in sub-classes. The _terminateTest method is called from within the finally block in unittest.TestCase.run. It is an empty method in unittest.TestCase. This was the only change to unittest.TestCase. A new class unittest.AsyncioTestCase was added that implements async-based testing. It is a direct sub-class of unittest.TestCase that: * uses a @property named loop to lazily create an event loop instance * destroys the event loop instance in _terminateTest * re-implements _runTest to call new asynchronous hook methods * adds asyncSetUp and asyncTearDown methods that simply call the synchronous methods * re-implements doCleanups to call co-routines asynchronously Rationale - I used asyncio.iscoroutinefunction to detect if test methods or callbacks are co-routines. You explicitly opt-in to async behavior using the async marker on things that you want to run on the loop. This will cause problems with using the patch decorator on test methods since they will no not be detected as co-routines. I took this approach primarily to simplify the code and enforce explicitness. Since the implementation is a new sub-class, it cannot break existing code and new code can place the patch inside of the test method instead of decorating the method. I believe that creating an destroying the loop with each test method execution is the safest approach for managing the lifecycle. I view having the loop exist at the class level is an unnecessary optimization. I also ensure that code under test that calls asyncio.get_event_loop or asyncio.get_running_loop will receive the loop by calling asyncio.set_event_loop with the new loop. This came up in PR review with Petter S. The management of the loop is isolated into a property which makes it possible to create custom sub-classes that instantiate 3rd party loops that are asyncio compatible. This is the only concession that my implementation makes to supporting other loop classes. If it is not clear, I believe that a new sub-class of unittest.TestCase is necessary for a clean implementation. It preserves unittest.TestCase so the risk of breaking existing code is minimized and the async functionality is isolated in a new class that is explicitly meant to test async code. This is also necessary if the implementation should exist in the asyncio module. -- ___ Python tracker <https://bugs.python.org/issue32972> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue32972] unittest.TestCase coroutine support
Dave Shawley added the comment: Hi everyone, I'm trying to reboot conversation on this issue since I would love for this to land in Python 3.8. At the recommendation of Terry Jan Reedy, here is my summary of where I think that the discussion is currently. If anything is misrepresented, incorrectly linked, or if I misspelled anyones name, I apologize. Feel free to correct any mistakes that you notice. New subclass of TestCase versus enhancing unittest.TestCase --- This was one of the primary discussion points since the start of this BPO. I believe that Petter S (msg313454), Yury Selivanov (msg313695), and Andrew Svetlov (msg313481) were +1 on having a new sub-class of unittest.TestCase whereas Zachary Ware (msg313696) and R. David Murray (msg313413) would prefer that unittest.TestCase be enhanced to support async methods directly. This is (in my opinion) the most contentious of the issues. It also is the one with the largest impact on the implementation. I feel that it is still largely up in the air amongst the core developers. Lifecycle of the loop - Whether the loop should live for the entire execution of a TestCase or for the execution of an individual test method came up a few times. Nathaniel Smith (msg313455) was concerned about callbacks leaking between tests. Yury Selivanov and Zachary Ware agreed that having a single event loop per class was acceptable (msg313696 and msg313700). Support for other loops --- Supporting 3rd party loop implementations (e.g., Tornado, Twisted, curio/trio) was discussed briefly. The conclusion that I drew from the discussion is that the built-in testing class was not required to offer direct support to non-asyncio compatible loops. Most notably msg313481 from Andrew Svetlov influenced my implementation. Where should support live? -- This is only relevant if we are not enhancing unittest.TestCase. Petter S favored that the separate test case implementation live in asyncio instead of unittest. I don't believe that anyone else had a strong opinion on this issue. Should we have explicit methods for async behavior? --- Yury Selivanov was most outspoken on explicitly named "async" methods like "asyncSetup", "asyncAddCallback", and the like. Particularly in msg313695 and msg313700. Zachary Ware seemed to agree that the separation was necessary but the functionality could be implemented by calling the async methods from the existing setUp and setUpClass methods (msg313699). Did I miss anything? -- ___ Python tracker <https://bugs.python.org/issue32972> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
preferences file
I'm doing a small application and want to add user preferences. Did some googling to see if there are standard Python ways/tools, but it seems not so much. My specific questions are: 1. Best practices for a user preference file/system? 2. File format favored and why - ini, JSON, etc? 3. File location? I'm using Ubuntu and I believe that the correct location would be home/.config/ . What about Mac and Windows? Would like to find a Python library that handles all of this, but so far... Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
System printer object
I need to print to one or both of my system printers. I have not found a printer object in Python or in Tkinter. This needs to work with Linux, Window, and Mac. Can someone point me in the right direction? Ultimately, I want to have a File/Print in the menu that lets me select the printer and properties. Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: Kivy native GUI examples
On 1/7/19 11:14 AM, Thomas Jollans wrote: On 07/01/2019 15.51, Dave wrote: I need to select a Python GUI. It needs to cover all of the desktops (Linux, Windows, Apple) and hopefully mobile (Android and Ios). I'm looking at Kivy, but have yet to find an example app. that has a native looking GUI (Windows, Mac, Linux/Gnome/KDE). Is that possible and anyone know of some examples? AFAIK looking like a native app is quite simply not something Kivy helps you with. If that's important, you should look into other options such as Qt (PyQt5 or PySide2). -- Thomas Thanks Thomas. -- https://mail.python.org/mailman/listinfo/python-list
Kivy native GUI examples
I need to select a Python GUI. It needs to cover all of the desktops (Linux, Windows, Apple) and hopefully mobile (Android and Ios). I'm looking at Kivy, but have yet to find an example app. that has a native looking GUI (Windows, Mac, Linux/Gnome/KDE). Is that possible and anyone know of some examples? Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
[issue32972] unittest.TestCase coroutine support
Dave Shawley added the comment: I added a different implementation for consideration (https://github.com/python/cpython/pull/10296). -- pull_requests: +9606 ___ Python tracker <https://bugs.python.org/issue32972> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue32971] Docs on unittest.TestCase.assertRaises() should clarify context manager details
Change by Dave Shawley : -- keywords: +patch pull_requests: +9605 stage: -> patch review ___ Python tracker <https://bugs.python.org/issue32971> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue32972] unittest.TestCase coroutine support
Dave Shawley added the comment: Hi all, I took a slightly different direction for adding async/await support to the unittest library. I summarized the approach that I took in a message to python-ideas (https://mail.python.org/pipermail/python-ideas/2018-October/054331.html) and a branch is available for preview in my fork of cpython (https://github.com/dave-shawley/cpython/pull/1). My question is whether I should reboot this bpo with my PR or create a new one since the implementation is different than what was already discussed? -- nosy: +dave-shawley ___ Python tracker <https://bugs.python.org/issue32972> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9263] Try to print repr() when an C-level assert fails (in the garbage collector, beyond?)
Dave Malcolm added the comment: Thanks! -- ___ Python tracker <https://bugs.python.org/issue9263> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue34208] Change in 3.7 expression evaluation?
New submission from Dave Opstad : In 3.6 I get this: >>> x = (100 * 20) >>> x is 2000 False >>> (100 * 20) is 2000 False But in 3.7, I get this: >>> x = (100 * 20) >>> x is 2000 False >>> (100 * 20) is 2000 True This isn't necessarily a problem, but I'm curious why this behavior changed from 3.6 to 3.7. -- components: Interpreter Core messages: 322304 nosy: opstad priority: normal severity: normal status: open title: Change in 3.7 expression evaluation? type: behavior versions: Python 3.7 ___ Python tracker <https://bugs.python.org/issue34208> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9635] Add Py_BREAKPOINT and sys._breakpoint hooks
Dave Malcolm <dmalc...@redhat.com> added the comment: On Fri, 2018-02-23 at 00:16 +, Cheryl Sabella wrote: > Cheryl Sabella <chek...@gmail.com> added the comment: > > Did PEP553 make this issue obsolete? I *think* they have slightly different scope: if I'm reading it right, PEP553 is about injecting a breakpoint into the Python debugger. This proposal was about injecting a lower-level breakpoint for debugging CPython itself (for e.g. gdb to handle). The idea was to make it easier to, say, step through a particular CPython construct at the C level by injecting a breakpoint right before it: def test_something(): # lots of setup sys.c_level_breakpoint() # whatever comes next so that sys.c_level_breakpoint drops you into, say, gdb, and from there you can step through the following Python code at the C level, without having to express stepping through all the setup at the C/gdb level. Hope that makes sense. That said, I'm full-time on gcc these days, and unlikely to pursue this from the CPython side. -- ___ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue9635> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue32488] Fatal error using pydoc
Dave Opstad <dave.ops...@monotypeimaging.com> added the comment: I think this was my mistake; when I used pydoc3 instead of pydoc it ran to completion. Please feel free to close this; sorry for the noise. -- ___ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue32488> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue32488] Fatal error using pydoc
New submission from Dave Opstad <dave.ops...@monotypeimaging.com>: I'm running 3.6.4 on Mac OS X 10.13.2, bash shell. Doing: $ pydoc modules causes: Please wait a moment while I gather a list of all available modules... Fatal Python error: PyThreadState_Get: no current thread Abort trap: 6 Reproduced this several times with the same result. -- components: Demos and Tools messages: 309422 nosy: opstad priority: normal severity: normal status: open title: Fatal error using pydoc type: crash versions: Python 3.6 ___ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue32488> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue32195] datetime.strftime with %Y no longer outputs leading zeros
Dave Challis <sui...@gmail.com> added the comment: My mistake, it appears to be related to the OS it's running on rather than the version (I just happened to test with different versions on different OSes). On Mac OS X (with 3.6.2): >>> import datetime >>> datetime.datetime.min.strftime('%Y') '0001' On Linux (with 3.6.2 again): >>> import datetime >>> datetime.datetime.min.strftime('%Y') '1 -- ___ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue32195> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue32195] datetime.strftime with %Y no longer outputs leading zeros
New submission from Dave Challis <sui...@gmail.com>: Tested in python 3.6.2: >>> import datetime >>> datetime.datetime.min.strftime('%Y') '1' Expected output: '0001' This means that strftime and strptime aren't necessarily symmetric, e.g.: >>> datetime.datetime.strptime(datetime.datetime.min.strftime('%Y'), '%Y') ValueError: time data '1' does not match format '%Y' -- components: Library (Lib) messages: 307389 nosy: davechallis priority: normal severity: normal status: open title: datetime.strftime with %Y no longer outputs leading zeros type: behavior versions: Python 3.6 ___ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue32195> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue31237] test_gdb disables 25% of tests in optimized builds
Dave Malcolm added the comment: The problem is that there are so many variables: * which version of which compiler * optimization flags * which version of gdb * which CPU architecture etc (and the compiler and/or gdb could be carrying patches from downstream distributors...) All of these can affect the debugging experience; as soon as optimizations are turned on it's very hard to predict exactly how well we can capture the frame information in the debugger. Hence it makes sense to skip these tests for optimized builds, to avoid creating noise in the buildbots. Downstream distributions might want to re-enable the tests, if they have sufficient control over the compiler and debugger versions that are in use, I guess. Or maybe there's a way to express some of the above sanely? Not sure. Hope this is constructive. -- ___ Python tracker <rep...@bugs.python.org> <http://bugs.python.org/issue31237> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com