Re: bring back nntp library to python3
On 14/08/2024 23:32, Left Right via Python-list wrote: >> it became simple and straightforward to >> download and install packages. > > I think the right word for this is "delusional". I agree. But even if it worked it doesn't alter the fact that by not having batteries included it puts the onus on developers to build complex installs since their clients can't be expected to use pip etc. And a vanilla python no longer comes with the batteries. It greatly adds to the Python users workload even as it lightens the library maintainers load. It was certainly one of the main reasons I adopted python rather than perl. But thankfully I'm retired now so it's somebody else's problem. > But hey, this is just letting off steam. Nobody cares. Lots of people care but the ability to influence these decisions seems to have been removed far from the general python user community. Python has moved from the BDFL/Bazaar to the Committee/Cathedral. Probably an inevitable consequence of its current "popularity". -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Best use of "open" context manager
On 06/07/2024 11:49, Rob Cliffe via Python-list wrote: > If the file does not exist I want to take appropriate action, e.g. > print an error message and abort the program. > I might write it like this: > > try: > with open(FileName) as f: > for ln in f: > print("I do a lot of processing here") > # Many lines of code here . > except FileNotFoundError: > print(f"File {FileName} not found") > sys.exit() > > but this violates the principle that a "try" suite should be kept small, The try is small, it only has a single statement inside. The compound block inside that statement should have its own try/ecxepts but the outer one really only applies to the with statement. I certainly prefer this option to any of the others presented. > not to mention that having "try" and "except" far apart decreases > readability. This is a valid concern although that's part of the reason we use indentation. Compared to early BASIC and FORTRAN with massive GOSUB type leaps (and often no indentation) it's very readable! But its still preferable to having the multi-level indents below or having to remember to close the file when finished (and ensure that all possible paths do so. > try: > f = open(FileName) as f: > FileLines = f.readlines() > except FileNotFoundError: > print(f"File {FileName} not found") > sys.exit() > # I forgot to put "f.close()" here -:) Exactly! That's why using with is safer even if the except is detached from the try. You are also reading the entire file into memory which could be an issue. And you are not catching any errors in the read operations because the except only covers a missing file. > Really I would like to write something like > > try: > with open(FileName) as f: > except FileNotFoundError: > print(f"File {FileName} not found") > sys.exit() > else: # or "finally:" > for ln in f: > print("I do a lot of processing here") > # Many lines of code here . I find that much less readable because the file handling block is a long way from the open file line and has extra control statements to mentally negotiate. The advantage of the original version is that you can ignore errors and read the code easily. You only need to find the except clause if you need to know how errors will be dealt with. But if comprehending the core functionality of the code you can just ignore all the error handling blocks. > Is there a better / more Pythonic solution? All IMHO of course, but I think the current implementation is the best of the options presented. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: IDLE: clearing the screen
On 08/06/2024 20:18, Rob Cliffe via Python-list wrote: > OK, here is the advanced version: > import os > class _cls(object): > def __repr__(self): > os.system('cls') > return '' > cls = _cls() > > Now when you type > cls > it clears the screen. For me on a Mac it clears the terminal screen that I used to launch IDLE and prints a single blank line on the IDLE shell. (And I have to use "clear" instead of "cls" of course. A quick Google suggests that printing Ctrl-L (formfeed?) might be a platform agnostic solution. But that didn't work for me in IDLE either. I think this is one where the best bet is to go into the IDLE code and add a Shell submenu to clear screen! Apparently it's been on the workstack at idle-dev for a long time but is considered low priority... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Terminal Emulator (Posting On Python-List Prohibited)
On 18/05/2024 19:12, Piergiorgio Sartor via Python-list wrote: >> So venvs make managing all that pretty convenient. Dunno why everybody's >> so down on venvs... Not so much down on them, they are just one extra step that's mostly not needed(in my use case) > Only people which are *not* using python... :-) > > In my experience, venvs is the only possible > way to use python properly. Well, I've been using Python since 1998 on Linux, Windows and MacOS and have yet to find a use for a venv. I've played with them when they first came out but haven't actually found a scenario where I've thought "I need a venv for that!" But then I'm a sole user, I have 3 or 4 projects going but only me working on them. I only have 2 Python versions at any time and the OS handles that just fine without any venvs. > The dependency nightmare created by python, pip > and all the rest cannot be resolved otherwise. I've honestly never experienced this "nightmare". I install stuff and it just works. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Terminal Emulator
On 14/05/2024 18:44, Gordinator via Python-list wrote: > I wish to write a terminal emulator in Python. I am a fairly competent > Python user, and I wish to try a new project idea. What references can I > use when writing my terminal emulator? I wish for it to be a true > terminal emulator as well, not just a Tk text widget or something like that. The first thing is to decide which terminal. A VT100 is very different from a 3270. And even a VT330 is quite different from a VT100 although sharing a common subset of control codes. And if you start looking at graphical terminals things get even more interesting! The other thing to consider is whether it will be a standalone app or a GUI component. If the latter do you want to expose your own API or clone the manufacturers? Or both?! Or you could make it an object that can be used both in GUIs and in "robotic" or "batch" mode. So many options. Most of the specs are available online and there must be dozens of terminal emulators around written in C so you should have plenty of sample code to study. Good luck! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: How to Add ANSI Color to User Response
On 10/04/2024 19:50, WordWeaver Evangelist via Python-list wrote: > I have a simple question. I use the following textPrompt in some of my Jython > modules: > '\n[1;33mYour choice is? (A B C D E): ', maxChars=1, autoAccept=False, > forceUppercase=True) > Is there a way to add an ANSI color code to the end Normally, for any kind of fancy terminal work, I'd say use curses. But I suspect Jython may not support curses? On the offchance it does do curses it would look like: import curses def main(scr): if curses.has_colors(): # check the terminal supports color curses.start_color(). # init the color system curses.init_pair(1,curses.COLOR_YELLOW,curses.COLOR_BLUE) # Now start adding text coloring as desired... scr.addstr(0,0,"This string is yellow and blue", curses.color_pair(1)) scr.refresh(). # make it visible else: scr.addstr("Sorry, no colors available") curses.wrapper(main) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: xkcd.com/353 ( Flying with Python )
On 30/03/2024 07:04, Greg Ewing via Python-list wrote: > On 30/03/24 7:21 pm, HenHanna wrote: >> https://xkcd.com/1306/ >> what does SIGIL mean? > > I think its' a Perl term, referring to the $/@/# symbols in front of > identifiers. There seem to be several derivation sources including a fantasy world city suspended above a very thin, tall steeple Personally, I know SIGIL as an opensource EPUB editor! None of them seem to have any direct connection to the xkcd cartoon. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Error in Module
On 10/03/2024 18:08, Sanskar Mukeshbhai Joshi via Python-list wrote: > I had made my project in BCA in Python. When I had complete my > project and run the program, at that time I got the error in > runnig my project. The error was ModuleNotFoundError: No module named 'flask'. Flask is a third party package that you need to install separately from Python. It does not come as standard. Have you installed Flask on the computer where you are running your project? If so, how did you download/install it? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Variable scope inside and outside functions - global statement being overridden by assignation unless preceded by reference
On 05/03/2024 22:46, Grant Edwards via Python-list wrote: > Unfortunately (presumably thanks to SEO) the enshittification of > Google has reached the point where searching for info on things like > Python name scope, the first page of links are to worthless sites like > geeksforgeeks. And not just Google, I just tried bing, yahoo and duckduckgo and they are all the same. Not a one listed anything from python.org on the first page... In fact it didn't even appear in the first 100 listings, although wikipedia did manage an entry, eventually. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: RE: Problem resizing a window and button placement
On 27/02/2024 07:13, Steve GS via Python-list wrote: > Aside from using it to resized > the window, is there no way to > know the last value of the > change for use in the program? The last value would be the current width. And you know how to get that as shown in your configure function: Ww = root.winfo_width() > I could write the value to a > label and read it back later That's no different to writing it to global Ww and accessing that as demonstrated in my last code post (with button). >>> It's better just to ask tk > for the values whenever you > need them, as you do inside > your handler. > > How would that be done? Ww = root.winfo_width() Provided you can access the root widget (which is (nearly?) always true) you can get the width of the main window. But can I ask if you have a particular use-case in mind for this? We started out talking about relocating some widgets when the window was resized. We established that the best place to do that was inside the configure event handler, with no need to store the width. (assuming you aren't using a dynamic layout manager(grid/pack/form) which would be better still!) We've now moved on to the more general issue of communicating values between event handlers (although still using the width as our exemplar). Is this just academic interest or do you have a specific need for this? If we know the need we might be able to suggest a specific (and possibly better?)solution. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: RE: RE: Problem resizing a window and button placement
On 26/02/2024 11:02, Steve GS via Python-list wrote: > Although your code produces the value of Ww outside the function, > I do not see how I can use the value of Ww unless I close the program. You have to use a function that operates inside the mainloop. Thats the nature of event driven programs, all activity happens inside the mainloop except initialisation and cleanup. So you need to create an event handler as I described below. Here is the complete program including the button: ### import tkinter as tk Ww=None def on_configure(*args): global Ww Ww = root.winfo_width() print("Ww Inside = <" + str(Ww) + ">") def printW(): print("Button Ww = ", Ww) root = tk.Tk() bw = tk.Button(root, text="Print Width", command=printW) bw.pack() root.bind('', on_configure) root.mainloop() print("Ww Outside = <" + str(Ww) + ">") Notice that the button callback picks up the latest value of Ww. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: RE: Problem resizing a window and button placement
On 26/02/2024 07:56, Steve GS via Python-list wrote: > Then there is that discovery > element: Why is my original > idea not working? I still > cannot pass the value back > from the function. What is > different about this function > that others would have given > me the value? There is nothing different, see the code below. print() is a function like any other. In this case it is called after you close the window, ie after mainloop() exits. But any other function called inside mainloop - eg any other event handler can also access it. For example, if you added a button: def printW(): print("Button Ww = ", Ww) bw = tk.Button(root, text="Print Width", command=printW) bw.pack() You would be able to print the value on demand. >> import tkinter as tk >> >> Ww = None >> >> def on_configure(*args): >> global Ww >> Ww = root.winfo_width() >> print("Ww Inside =<"+str(Ww)+">") >> >> root = tk.Tk() >> root.bind('',on_configure) >> root.mainloop() >> >> print("Ww Outside = <"+str(Ww)+">") -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: RE: Problem resizing a window and button placement
On 25/02/2024 03:58, Steve GS via Python-list wrote: import tkinter as tk Ww = None def on_configure(*args): global Ww Ww = root.winfo_width() print("Ww Inside = <" + str(Ww) + ">") root = tk.Tk() root.bind('', on_configure) root.mainloop() print("Ww Outside = <" + str(Ww) > + ">") Produces: Ww Inside = <200> Ww Inside = <200> Ww Inside = <205> Ww Inside = <205> Ww Inside = <206> Ww Inside = <206> Ww Outside = <206> HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Using my routines as functions AND methods
On 04/01/2024 04:17, Thomas Passin via Python-list wrote: >> I'm probably missing something obvious here but can't you >> just assign your function to a class member? >> >> def myFunction(obj, ...): ... >> >> class MyClass: >> myMethod = myFunction > > That works if you assign the function to a class instance, but not if > you assign it to a class. > > def f1(x): > print(x) > f1('The plain function') > > class Class1: > pass > > class Class2: > pass > > c1 = Class1() > c1.newfunc = f1 > c1.newfunc('f1 assigned to instance') # Works as intended > > Class2.newfunc = f1 > c2 = Class2() > c2.newfunc('f1 assigned to class') # Complains about extra argument Yes but I did the assignment inside the class definition and that seemed to work just fine: >>> def g(obj, st): print(st, obj.v) ... >>> class D: ...def __init__(self,v): self.v = v ...m = g ... >>> d = D(66) >>> g(d,'val = ') val = 66 >>> d.m('v = ') v = 66 -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Using my routines as functions AND methods
On 03/01/2024 22:47, Guenther Sohler via Python-list wrote: > Hi, > > In my cpython i have written quite some functions to modify "objects". > and their python syntax is e.g.\ > > translate(obj, vec). e.g whereas obj is ALWAYS first argument. > However, I also want to use these functions as class methods without having > to > write the function , twice. When using the SAME function as a methos, the > args tuple must insert/contain "self" in the first location, so i have > written a function to do that: I'm probably missing something obvious here but can't you just assign your function to a class member? def myFunction(obj, ...): ... class MyClass: myMethod = myFunction Then you can call it as myObject = MyClass() myObject.myMethod() A naive example seems to work but I haven't tried anything complex so there is probably a catch. But sometimes the simple things just work? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Are there any easy-to-use Visual Studio C# WinForms-like GUI designers in the Python world for Tk?
On 29/12/2023 01:05, Félix An via Python-list wrote: > I'm used to C# WinForms, which has an easy-to-use drag-and-drop GUI > designer in Visual Studio. Is there anything similar for Tk? How about > Qt? There are any number of them but few that work well. The best I found was Dabo but it uses its own Framework (based, ISTR, on wxPython?) so not much good for integrating with third party widgets etc. I also used a Python fork of SpecTcl but it died a death I think. The Qt Designer tool works with Python but I never took to Qt as a toolkit although once mastered it is very powerful. Probably the best choice for professional class GUI applications using a GUI builder. And on a Mac the standard Apple XCode GUI builder works fine with Python too, but is Mac specific. > What do you recommend as the easiest way to create GUI programs in > Python, similar to the ease of use of C# WinForms? Provided you aren't getting fancy the basic Tkinter toolset and programming by hand works best for me. Once you get used to it its quick, flexible and fairly easy to debug. I also use wxPython if I need something more sophisticated, but again I just type the code I don't use a GUI builder. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: >>> %matplotlib inline results in SyntaxError: invalid syntax
On 25/12/2023 05:34, geetanajali homes via Python-list wrote: >> import numpy as np >> import pandas as pd >> import random >> import matplotlib.pyplot as plt >> %matplotlib inline >> >> I get an error on the last line. I am running this code in Idle Python >> 3.4.4 Shell... Python names can't start with a % (its the modulo or string formatting operator). I know nothing of the innards of matplotlib so I can only suggest a closer examination of their tutorial information. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Amy known issues with tkinter /ttk on latest MacOS?
On 17/11/2023 03:38, Terry Reedy wrote: > There have been other reports on the cpython issue tracker than Sonoma > broke bits of tk behavior. > https://github.com/python/cpython/issues?q=is%3Aissue+label%3AOS-mac+is%3Aclosed > > shows a couple Thanks Terry, I had a browse and it seems I'm not alone. That's a relief. I'll upgrade to 3.13 when it comes out and hopefully it will go away. (Another suggestion was to use the homebrew python but I don't like having any more homebrew stuff than is absolutely necessary!) Meantime I'll just have to continue nudging the mouse as I click! Alan G. -- https://mail.python.org/mailman/listinfo/python-list
Amy known issues with tkinter /ttk on latest MacOS?
I have a little app that I wrote ages ago (2015) using tkinter/ttk and it just works. Or it did, up until the latest MacOS version upgrade and now it has become very sporadic in response to mouse clicks. For example I have a drop-down list and I can drop the list but then it won't let me select an item. Or sometimes, the selected item is highlighted but the corresponding action doesn't get fired. It is intermittent which makes debugging it difficult. And it's not just lists it also affects regular buttons as well. Right clicks seem to work ok, it's only the left mouse button. Also, I've just noticed that if I move the mouse slightly while clicking that seems to work. There are no error/warning messages in the Console. I'm just wondered if this is a known issue, or just my setup? Any suggestions welcomed. Python version - 3.10.4 OS version - Sonoma 14.1 M1 Mac Mini, 16GB Ram I could upgrade my Python version but I was planning on waiting for the 3.13 release to finalize first. And I doubt if that's the cause anyway. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Newline (NuBe Question)
On 15/11/2023 07:25, Grizzy Adams via Python-list wrote: > for s in students: > grades.append(s.school) > grades.append(s.name) > grades.append(s.finalGrade()) > if s.finalGrade()>82: > grades.append("Pass") > else: > grades.append("Fail") > print(grades) > > --- End Code Snippit --- > Do I need to replace "append" with "print", or is there a way to get the > newline in as I append to list? Firstly, it is usually a bad idea to mix formatting features(like newline) with the data. You will need to remove them again if you want to work with the data itself. So, better to print the raw data and add the formatting during printing. There are a couple of options here (well more than a couple actually!) The simplest is to create another for loop and print each field with a newline automatically added by print() Another is to simply join everything in grades together separated by newlines. Python has a method to do that called join(): print('\n'.join(grades)) Unfortunately it seems your data has a mix of strings and numbers so that won't work without some tweaks: print('\n'.join(str(f) for f in grades)) However, I wonder if this really what you want? You have created grades as a long list containing all of the attributes of all of the students plus their Pass/Fail status. But you have no (easy)way to access the Pass/Fail value for each student. Do you really want to store the Pass/Fail in the student? And then print the students? Like so: for s in students if s.finalGrade() > 82: s.result = "Pass" else: s.result = "Fail" print(s.school) print(s.name) ... print(s.result) Just a thought... PS. There are neater ways to do this but you may not have covered those yet so I'll stick to basics. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: xor operator
On 14/11/2023 00:33, Mats Wichmann via Python-list wrote: > Hardware and software people may have somewhat different views of xor I've come at it from both sides. I started life as a telecomms technician and we learned about xor in the context of switching and relays and xor was a wiring configuration for scenarios where you wanted any single change of switch state to toggle the entire system (think a stairwell with switches on every landing). Later, I got into software engineering and we studied Boolean algebra and xor was an odd number of Truth values, used in parity tests (and in encryption). But from both perspectives xor is pretty clearly defined in how it operates and not, I suspect, what the OP really wants in this case. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Question(s)
On 25/10/2023 12:44, o1bigtenor via Python-list wrote: > Haven't heard of a python IDE - - - doesn't mean that there isn't such - - There are literally dozens with varying degrees of smartness. The big 4 all have Python plugins/environments: Eclipse, Netbeans, VisualStudio, IntelliJ And of course the Apple XCode toolset has a python environment. There are also several Python specific IDEs around too. Most of them are multi-platform: https://www.simplilearn.com/tutorials/python-tutorial/python-ide gives a small sample And of course the old favourites vi/vim and emacs both have comprehensive Python support. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Question(s)
On 25/10/2023 00:08, o1bigtenor via Python-list wrote: > So how does one test software then? Testing is very different to proving! As an industry we do a lot of testing at many different levels. On bigger projects you'll find: - Unit tests - testing small fragments of a bigger program - Integration tests - testing that sub modules of code work together (and code with hardware, if applicable) - System testing - checking that the code(and hardware) as a whole does what it should based on the specs (often done by an independent team) - Performance testing - checking the system runs as fast as it should, using only the memory it should, for as long as it should. - User testing - Can a real user drive it? - security testing - Does it stop the bad guys from messing it up or using it as a gateway? And there are more levels if you are really keen. Testing often(usually!) takes up more time than programming. And there are many, many books written about how to do it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Question(s)
On 24/10/2023 22:51, Grant Edwards via Python-list wrote: >>> Is there a way to verify that a program is going to do what it is >>> supposed to do even before all the hardware has been assembled and >>> installed and tested? > And the specified customer requirements are usually wrong too. Sure, > the customer said it is supposed to do X, but what they actually > needed was Y. And this is the hardest bit, specifying exactly what you want at a level that can be formally verified. I worked on some safety critical systems a while back(1990s) and we had to formally verify the core (non UI) code. We did this, but it still failed in some scenarios because we verified it against faulty specs which, in turn, were based on the customer's incorrectly stated requirements. Garbage-In-Garbage-Out still applies. Was the 3 months of formal analysis a waste of time? No, we still caught lots of subtle stuff that might have been missed, but it wasn't 100%. The bugs we did have were caught and identified during system tests. So far as I know, nobody has died as a result of any bugs in that system. But, to the OP, the effort in a) Learning the math and gaining experience for formal analysis and b) actually performing such an analysis of real design/code is simply not worth the effort for 99% of the programs you will write. It is much simpler and faster to just test. And test again. And again. Especially if you use automated testing tools which is the norm nowadays. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Why doc call `__init__` as a method rather than function?
On 15/09/2023 11:49, scruel tao via Python-list wrote: > ```python class A: > ... def __init__(self): > ... pass > On many books and even the official documents, it seems that > many authors prefer to call `__init__` as a "method" rather > than a "function". That' because in OOP terminology methods are traditionally implemented as functions defined inside a class (There are other ways to define methods in other languages, but the class/function duology is by far the most common.) What is a method? It is the way that an object handles a message. OOP is all about objects sending messages to each other. Many different objects can receive the same message but they each have their own method of handling that message. (This is called polymorphism.) Over time the most common way to implememt OOP in a language is to invent a "class" structure and to allow functions to either be defined within it or added to it later. In either case these functions are what define how a class (and its object instances) handle a given message. So the function describes the method for that message. And over time that has become shortened to the function inside a class *is* its method. In practice, the message looks like a function call. And the method consists of the function body (and/or any inherited function body). Thus every method is a function (or set of functions) but not every function is a method (or part of one). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Why do I always get an exception raised in this __init__()?
On 31/08/2023 22:15, Chris Green via Python-list wrote: > class Gpiopin: > > def __init__(self, pin): > # > # > # scan through the GPIO chips to find the line/pin we want > # > for c in ['gpiochip0', 'gpiochip1', 'gpiochip2', 'gpiochip3']: > > chip = gpiod.Chip(c) > for l in range(32): > line = chip.get_line(l) > if pin in line.name(): > print("Found: ", line.name()) > return > else: > raise ValueError("Can't find pin '" + pin + "'") You don't store the line anywhere. You need to use self.line self.line = chip.get_line(l) if pin... > def print_name(self): > print (self.line.name()) > > def set(self): > self.line.set_value(1) > > def clear(self): > self.line.set_value(0) As you do here. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Multiple inheritance and a broken super() chain
On 05/07/2023 01:27, Chris Angelico via Python-list wrote: >> So I'm curious about how big this "big problem with MI" is in > > Who said it's a big problem with MI? I think it's a very common perception, particularly with newer programmers who have never used it in anger. Any time anyone discusses MI it seems somebody will jump in and warn about diamonds etc. As a result many steer clear of MI, which is a shame. My personal experience of MI is that used appropriately it is a powerful and useful tool. But it must be used in a true is-a type relationship and not just as a kind of cheap reuse mechanism - that's when problems start. Also, mixin style MI is particularly powerful but the protocol between mixin and "subclass" needs to be carefully designed and documented. Like any powerful tool you need to understand the costs of use as well as the potential benefits. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Multiple inheritance and a broken super() chain
On 03/07/2023 19:39, Chris Angelico via Python-list wrote: > On Tue, 4 Jul 2023 at 03:39, Peter Slížik via Python-list >> The legacy code I'm working with uses a classic diamond inheritance. > What happens when Top is initialized twice? This seems like a problem > waiting to happen, and when you moved to using super(), you more than > likely simplified things and fixed things. Slightly off topic but I wonder how many real world problems people have experienced having the top of a diamond initialized twice? The reason I ask is that I ran a maintenance team for about 5 years (early 1990s) working on various OOP projects using MI; in Lisp Flavors, C++(*) and a homebrew variant of C that supported MI. In that time I don't recall ever having problems with top objects being initialized twice (apart from redundant execution of code of course). In most cases the top object was so abstract that its init()/constructor was only doing generic type stuff or opening database sessions/networks etc which got lost and tidied up by garbage collectors. So I'm curious about how big this "big problem with MI" is in practice. I'm sure there are scenarios where it has bitten folks but it never (or very rarely) occurred in our projects. (Of course, being maintenance programmers, the problems may have been ironed out before the code ever reached us! But that wasn't usually the case...) (*) C++ is the odd one out because it doesn't have GC, but then neither does it have an Object superclass so very often MI in C++ does not involve creating diamonds! And especially if the MI style is mixin based. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Fwd: AUTO EDITOR DIDN'T WORK
On 15/06/2023 08:58, Real Live FootBall Tv via Python-list wrote: > I have followed the instructions given on how to install the app. What I > needed was an application to cut of silence from my video and I saw auto > editor demonstrated as one of the applications that could do that. It does > cut the silent areas of an MP4 format video for instance but would save it > as a XML file which in turn would be exported to the video editor that > supports the output from the auto editor app. The one who demonstrated it > in a video used Davinci Resolve to import the XML file, I followed same > process but I couldn't get same result. It looks like you have three parts to this puzzle: - auto-editor - resolve - Python It's not clear which part isn't working but you can at least test Python is working after you install it by running the interpreter in a console/terminal window by typing python at the command prompt. If you get the Python prompt: >>> Then Python is installed OK. After that it's back into auto-editor and resolve and this is not the best place to get answers for those. Resolve at least has an active support forum, so I'd start there(assuming python works!) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Fwd: AUTO EDITOR DIDN'T WORK
Forwarding to list Okay thanks. Meanwhile, I am not tech savvy so I may not say much here. I followed all the commands as given on the website to install auto editor standing it on python but after rendering the XML file, I couldn't open it with my Davinci Resolve 18. I uninstalled and reinstalled about twice and still no success hence I uninstalled it. On Mon, 12 Jun 2023, 23:33 Alan Gauld via Python-list, mailto:python-list@python.org>> wrote: On 12/06/2023 10:26, Real Live FootBall Tv via Python-list wrote: > I did it because I was going to use it with another application, A VIDEO > EDITING APP, Auto EDITOR but it didn't work for some reasons unknown to me. You need to define "didn't work" Did it work as a python interpreter? ie. Did you get a >>> prompt in a terminal? and without involvement from your video editor? If so, what did you do to link it to the video editor? And what was the result? Or did Python not even start? How did you try to use it? What OS are you on? Did the installer run OK? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ <http://www.alan-g.me.uk/> http://www.amazon.com/author/alan_gauld <http://www.amazon.com/author/alan_gauld> Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos <http://www.flickr.com/photos/alangauldphotos> -- https://mail.python.org/mailman/listinfo/python-list <https://mail.python.org/mailman/listinfo/python-list> -- https://mail.python.org/mailman/listinfo/python-list
Fwd: Re: AUTO EDITOR DIDN'T WORK
On 12/06/2023 10:26, Real Live FootBall Tv via Python-list wrote: > I did it because I was going to use it with another application, A VIDEO > EDITING APP, Auto EDITOR but it didn't work for some reasons unknown to me. You need to define "didn't work" Did it work as a python interpreter? ie. Did you get a >>> prompt in a terminal? and without involvement from your video editor? If so, what did you do to link it to the video editor? And what was the result? Or did Python not even start? How did you try to use it? What OS are you on? Did the installer run OK? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Silly (maybe) question re imported module(s)
On 19/05/2023 19:46, Grizzy Adams wrote: > Tried that > RESTART: D:\Shades\Tools\Python\Temp\cube.py cubes() > Traceback (most recent call last): > File "", line 1, in > cubes() > TypeError: 'list' object is not callable Ah, now I understand. cubes is a literal list defined in the module. > But that was spot on, thanks > import cube cube.cubes > [0, 1, 8, 27, 64, 125, 216, 343, 512, 729] Glad to help. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Silly (maybe) question re imported module(s)
On 19/05/2023 13:36, Grizzy Adams wrote: >> Looks like you are using IDLE? > > Yes > > > From consol > import cube cubes > Traceback (most recent call last): > File "", line 1, in > cubes > NameError: name 'cubes' is not defined You imported cube but tried to use cubes. I'm guessing cubes is defined inside cube so you would need cube.cubes > File->Open mymodule.module into the editor, then F5 to run all is well > > RESTART: D:\Shades\Tools\Python\Temp\cube.py cubes > [0, 1, 8, 27, 64, 125, 216, 343, 512, 729] cubes looks like it should be a function but in that case there should be parens after it. So I'm not sure how that is working! I'd expect that you need to do: import cube cube.cubes() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Silly (maybe) question re imported module(s)
On 19/05/2023 07:44, Grizzy Adams via Python-list wrote: > when typed in console or editor and run with F5 (which saves before it can > run) > > But sometimes saved work (albeit small) when imported does not work any longer Looks like you are using IDLE? If so, it's possible that in the original case you had some values set from a previous run that were picked up but when you reimport later those values are missing. It would help if you can post any error messages since they should give clues(like name errors for example). Also describe how you are "importing" the modules. are you typing >>> import mymodule at the interactive prompt or are you using the File->Open menu to load them into the editor? (It sounds like the latter) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: What to use instead of nntplib?
On 16/05/2023 10:06, Cameron Simpson wrote: >> I'm curious as to why nntplib is deprecated? Surely there are still a >> lot of nntp servers around, both inside and outside corporate firewalls? >> Is there a problem with the module or is it just perceived as no longer >> required? > > See PEP 594: https://peps.python.org/pep-0594/ Thanks Cameron. A scary list; I must have a dozen projects from the late 90s still live that are using many of these! I'm glad I'm retired and won't be the one who has to fix 'em :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: What to use instead of nntplib?
On 15/05/2023 22:11, Grant Edwards wrote: > I got a nice warning today from the inews utility I use daily: > > DeprecationWarning: 'nntplib' is deprecated and slated for removal in > Python 3.13 > > What should I use in place of nntplib? I'm curious as to why nntplib is deprecated? Surely there are still a lot of nntp servers around, both inside and outside corporate firewalls? Is there a problem with the module or is it just perceived as no longer required? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: [pygettext] --package-name and --package-version unknown
On 04/05/2023 22:38, c.bu...@posteo.jp wrote: > Hello, > > am I right to assume that "pygettext" is part of the official Python3 > "package"? So it is OK to aks here? > No it doesn't appear to be. It is not listed in the standard library. It is mentioned in the documentation for gettext which is part of the standard library. It does seem to be part of the Python i18n toolkit however. There are extensive comments in the .py file. https://github.com/python/cpython/tree/main/Tools/i18n/pygettext.py > I would like to modify the header that pygettext does create in each > po-file. Sorry, I've never used pygettext so can't help there. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Python curses missing form library?
On 24/04/2023 17:26, Grant Edwards wrote: > Does the Python curses support in the standard library not include > support for the curses form library? It seems to include support for > the panel library, but I can't find any mention of the form library. I don't believe so. If you are building terminal based form-type apps the best bet seems to be urwid. I haven't used it in anger but the beginner docs I saw looked promising. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: PyCharm's strict PEP and not so strict?
On 19/04/2023 10:51, Kevin M. Wilson via Python-list wrote: > I'm in a bit of a quandary, I want some strict syntax errors to be flagged, OK, You might want to use a "linter" in that case because most tools use the interpreter itself to flag syntax errors. > but the use of single quotes vs double quotes! > NOT what I need from the 'checker', you dig? Not really. What is the problem. Use of single versus double quotes is straightforward - use one or the other and make sure they match(opening and closing) You can nest one type inside the other if you need literal quotes. And of course the same applies to triple quotes except you can include newlines inside those. What kind of problems are you experiencing with quotes? If we have some specific examples we can give specific answers. > "stones" for bull, how do I set up the kind of "checking" I want? That's not a phrase with which I'm familiar but my guess is you need to install a linter tool and then, possibly configure it to flag or hide particular error/warning types to your personal taste. Each tool is different so you will need to read the docs on how to configure it (and how to plumb it into your IDE). Personally I've never felt the need for any stricter error checking than the interpreter provides so I can't offer anything beyond the generic suggestion to use a linter. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: tksheet - Copy and Paste with headers
> 在 2023/4/15 2:33, angela vales 写道: >> I have recently created a tkinter app and need the ability to copy and > paste data from tksheet table into an Excel file. First thanks for drawing my attention to tksheet. I've long been desiring a decent table widget in tkinter and was on the verge of trying to create one of my own. tksheet looks like it will do all I need. As to copy/paste I couldn't see any explicit mention but it does say the underlying data is in a Tk Canvas so it may be that copy/paste will just work, did you try it? What happened if you paste into a text editor in the first instance? And Excel in the second? If all else fails you can probably write handlers and bind to Ctrl-C and Ctrl-V to do something yourself that mimics cut/paste. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: RE: Weak Type Ability for Python
On 14/04/2023 00:25, avi.e.gr...@gmail.com wrote: > Is there any concept in Python of storing information in some way, such as > text, and implementing various ideas or interfaces so that you can query if > the contents are willing and able to be viewed in one of many other ways? Are you talking about something like a C union type (or a Pascal variant record)? I'm not aware of any such feature in Python but have often thought it would be a nice to have for the rare cases where its useful. > Or it may be storing text in some format but the object is willing to > transform the text into one of several other formats when needed. The text > may also have attributes such as whether it is in English or Hungarian or is > mixed-language. Or are you meaning something like an extension to the struct module that can interpret a bytestring in any way defined by a format string? > basis. But do some languages have some support within the language itself? The closest to what you seem to mean is, I think, the C union type, at least in my experience. But you have to define all the ways you can interpret the type up front in the type definition. > My reason for asking, is based on the discussion. If I want to use plus with > an integer and a string, it may be reasonable for the interpreter to ask one > or the other operand if they are able to be seen another way. You can achieve that in a slightly different way in Tcl which allows you to redefine all the operators (commands in Tcl-speak) in the language so redefining plus is easy. Doing it based on type is more tricky but doable. > Unfortunately, if they BOTH are flexible, how do you decide whether to add > them as numbers or concatenate them as strings? Yes, that's where it becomes a designer's arbitrary choice. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Weak Type Ability for Python
On 13/04/2023 20:35, Chris Angelico wrote: > REXX - where everything is a string, > It was quite the experience back in the day (as OS/2's native > scripting language), I briefly met REXX on a mainframe, but I did play with OS/2 for a year or two. Back when it looked like it might be a rival to M$ OS/2 running NeXTstep now that would have been a platform for the 90s... both so near yet so far. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Windows Gui Frontend
On 01/04/2023 18:21, Jim Schwartz wrote: > Are there any ide’s that will let me design the screen and convert it to > python? There is nothing remotely like the VB or Delphi GUI builders. There are some tools somewhat similar to the Java Swing and FX GUI builders with varying degrees of bugginess. And there are a few bespoke GUI type tools such as Dabo for building specific types of applications. But most Python GUI developers seem to prefer to just hard code the Python, once you get used to it there's not much time saving with the GUI tools. The real time consuming stuff in building GUIs is getting the basic design right and keeping all the controls, keyboard bindings and menus in sync. State management in other words. I did a deep dive examination of GUI builders back around v2.6 and came away less than enthused. Things may have improved since then but I've seen no real evidence of that. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Windows installer from python source code without access to source code
On 31/03/2023 13:00, Jim Schwartz wrote: > I want a windows installer to install my application that's written in > python, but I don't want the end user to have access to my source code. Others have commented that at some level it will always be thre but on a more pragmatic level tools like py2exe bundle up a Python app as an exe file which might be all you need? I'm sure if a user dug deep enough they could still find the source (or something close) but to deter casual browsing it might be what you want. Caveat: I've never used py2exe in anger and my experiements were before Python3 so ive no idea what it does today! But a quick check suggests it still exists and works with python3 code - last major release was in Nov 2022. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Fwd: Friday finking: IDE 'macro expansions'
On 18/03/2023 12:15, Peter J. Holzer wrote: >> I think you might be meaning TurboPascal, Delphi's forerunner. It just >> had a compiler and text editor. > > I'd still classify Turbo Pascal as an IDE. It wasn't a standalone > compiler you would invoke on source files you wrote with some other It had both (although I'm not sure when that was introduced, the original didn't). Mostly you used the IDE/editor but there was a command line compiler that you could run (and a make-like project tool too in the later versions). I started with TurboPascal on DOS at Uni generating COM files then later used TP versions 4, 5.5(with added OOP!) and 6 professionally, creating EXE file DOS programs. Up until I switched to a Mac, a year ago, I still had TP6 and used it to maintain some old TurboVision DOS programs. But I used Delphi from version 1 through to 7(?) for all my Windows programming and still have version 3 installed (via VirtualBox on Linux) to keep some old shareware apps of mine running. I often think there are a lot of similarities between Delphi/Object Pascal and Python in the OOP area. > it, see the errors directly in the source code. I think it even had a > debugger which would also use the same editor window (Turbo C did). I think the debugger came in v3, but i could be wrong. I don't recall there being one at uni... > Turbo Pascal predated GUIs, so it wouldn't have a GUI builder. No, it did have a windowing toolkit(TurboVision) but no visual UI builder. That was the big new feature of Delphi. > application (i.e. not a learning project) with a traditional desktop GUI > for 20 years) so the presence or absence of a GUI builder isn't an > essential criterion on whether something is or is not an IDE. Indeed, but it was intrinsic to Delphi (even though you could write non GUI apps too, but they required extra effort.) Eclipse et al have GUI builders available as extras, in Delphi (and Lazurus) it is hard to avoid. BTW Delphi (v11) and the other Borland tools are still going strong, albeit at extortionately high prices: $1000~3000 for the pro versions! (But there is still a free community version with just the basics.) See http://www.embarcadero.com And it's targeted at multi-platforms now: Windows, MacOS, Android, iOS although it only runs on Windows. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Fwd: Friday finking: IDE 'macro expansions'
On 17/03/2023 17:55, Thomas Passin wrote: >> I used Delphi and Smalltalk/V which both pretty much only exist within >> their own IDEs and I used their features extensively. > > Back when Delphi first came out, when I first used it, I don't remember > any IDE; one just used a text editor. I think you might be meaning TurboPascal, Delphi's forerunner. It just had a compiler and text editor. But Delphi from day 1 was an IDE designed to compete with Visual Basic. Everything was geared around the GUI builder. You could write code outside the IDE but it was orders of magnitude more difficult. The Lazarus open source project is based on Delphi's IDE. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Fwd: Friday finking: IDE 'macro expansions'
Oops! I meant to send this to the group not just Dave. Forwarded Message On 16/03/2023 22:55, dn via Python-list wrote: > Do you make use of your IDE's expansionist tendencies, and if-so, which > ones? When I'm writing Java/C++/C# yes, I need all the IDE help I can get. Netbeans or Eclipse being my tools of choice. And in my Windows days I used Delphi and Smalltalk/V which both pretty much only exist within their own IDEs and I used their features extensively. When writing Python I use IDLE, or vim for bigger jobs. IDLE does have some suggestions and auto tricks but I don't always use them. In vim I use auto-indent and that's about it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Lambda returning tuple question, multi-expression
On 08/03/2023 21:56, aapost wrote: > When making a UI there are a lot of binding/trace operations that need > to occur that lead to a lot of annoying 1 use function definitions. I > don't really see lambda use like below. Lambdas are very common in GUI callbacks but I admit I've never seen tuples used to create multiple expressions. That's a neat trick I hadn't thought of and will probably use. > Giving 2 working lambda examples using a returned tuple to accomplish > multiple expressions - what sort of gotchas, if any, might make the > following bad practice if I am missing something? Not bad practice per-se but you are still limited to expressions, no loops for example (although you could fake it with a list comp, but that gets ugly fast!) Also layout is all important here. It could get very messy to read if indentation isn't clear. You only have to look at some Javascript code with function definitions as arguments to functions to see how clunky that can be. Similarly debugging so much code passed as arguments might be an issue - no easy way to step into the lambda. But as an alternative to writing many typical event handlers it's definitely a valid approach that I'll be trying. > b = tk.Button(master=main, text="Enable") > b.config( > command=lambda: ( > e1.config(state="normal"), > e2.config(state="normal"), > e3.config(state="normal") > ) > ) You could of course single line that with: b = tk.Button(master=main, text="Enable", command=lambda: ( e1.config(state="normal"), e2.config(state="normal"), e3.config(state="normal") ) ) It's not a radical change from using a lamba as a callback but it does extend the use case to cover a common GUI scenario. I like it. I wish I'd thought of it years ago. Thanks for sharing. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: RE: Which more Pythonic - self.__class__ or type(self)?
On 04/03/2023 17:38, avi.e.gr...@gmail.com wrote: > > Of course each language has commonly used idioms > That's the point, the correct term is probably "idiomatic" rather than "pythonic" but it is a defacto standard that idiomatic Python has become known as Pythonic. I don't think that's a problem. And at least we aren't in the C++ situation where almost everything that was idiomatic up until 1999 is now deemed an anti-pattern and they have standard library modules to try and guide you to use the "correct" idioms! But being Pythonic is still a much more loose term and the community less stressed about it than their C++ cousins where it has almost reached a religious fervour! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Which more Pythonic - self.__class__ or type(self)?
On 02/03/2023 20:54, Ian Pilcher wrote: > Seems like an FAQ, and I've found a few things on StackOverflow that > discuss the technical differences in edge cases, but I haven't found > anything that talks about which form is considered to be more Pythonic > in those situations where there's no functional difference. I think avoiding dunder methods is generally considered more Pythonic. But in this specific case using isinstance() is almost always the better option. Testing for a specific class is likely to break down in the face of subclasses. And in Python testing for static types should rarely be necessary since Python uses duck typing and limiting things to a hard type seriously restricts your code. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: TypeError: can only concatenate str (not "int") to str
On 26/02/2023 00:54, Greg Ewing via Python-list wrote: > On 26/02/23 10:53 am, Paul Rubin wrote: >> I'm not on either list but the purpose of the tutor list is to shunt >> beginner questions away from the main list. I'm not sure that's why we set it up but it is certainly a large part of our remit. But protecting newbies from overly complex responses and covering wider topics (beyond pure Pyhon) is also a large part of our purpose. > There's a fundamental problem with tutor lists. They rely on > experienced people, the ones capable of answering the questions, > to go out of their way to read the tutor list -- something that > is not of personal benefit to them. In practice, the "tutors" tend to be split between folks who inhabit both lists and those who only interact on the tutor list. eg. I lurk here and only occasionally partake. But the problem with this particular thread is that, if directed to the tutor list, the OP would simply be told that "that's the way Python works". The tutor list is not for discussing language enhancements etc. It is purely about answering questions on how to use the language (and standard library) as it exists. (We also cover beginner questions about programming in general.) So this thread is most definitely in the right place IMHO. -- Alan G Tutor list moderator -- https://mail.python.org/mailman/listinfo/python-list
Re: Usenet vs. Mailing-list (was: evaluation question)
On 28/01/2023 21:36, Dennis Lee Bieber wrote: > Now -- last time I checked the gmane server says posting is prohibited. > I used to use gmane as it retrieved directly from the mailing list I still use gmane but its no posting thing is a pain because responding (or posting new stuff) is a now more complicated than before. So I have to be very highly motivated to jump through the hoops. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: RE: NoneType List
On 02/01/2023 02:14, avi.e.gr...@gmail.com wrote: > I used PASCAL before C and I felt like I was wearing a straitjacket at times > in PASCAL when I was trying to write encryption/decryption functions and had > to find ways to fiddle with bits. Similar things were easy in C, and are > even easier in many more recent languages such as Python. That's true of pure Pascal. But Thomas was talking about Turbo Pascal which had extra functions and features for all those "real world" type things. (And you could insert some inline assembler if all else failed) It also relaxed the ludicrously strict typing slightly. Turbo Pascal made Pascal a joy and I still use Delphi for Windows programming today. TP also introduced classes to Pascal (although Apple had already done so for the Mac and Borland basically ported the syntax to the PC). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: NoneType List
On 31/12/2022 05:45, Goran Ikac wrote: > b = a.append(3) > I mean: why b = a.append(something) is the None type, and how to make a new > list that contains all the items from a and some new items? append() like many other collection methods in Python works in place and returns None. But the action has succeeded and 3 will have been appended to list 'a'. So, to create a new list that contains all the old items you could do: newlist = [] # an empty list for item in oldlist: newlist.append(item) This is so common Python has a shorthand form to do this: newlist = [item for item in oldlist] called a list comprehension. And there is an even shorter way using something called slicing: newlist = oldlist[:]# copy oldlist to new. However, as an ex-Smalltalk programmer, I do wish that Python returned self from these methods rather than None so that we could chain them. But sadly it doesn't. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: String to Float, without introducing errors
On 17/12/2022 11:51, Paul St George wrote: > I have a large/long array of numbers in an external file. The numbers look > like this: > > -64550.727 > -64511.489 > -64393.637 > -64196.763 > -63920.2 > When I bring the numbers into my code, they are Strings. To use the > numbers in my code, I want to change the Strings to Float type > because the code will not work with Strings but I do not want > to change the numbers in any other way. That may be impossible. Float type is not exact and the conversion will be the closest binary representation of your decimal number. It will be very close but it may be slightly different when you print it, for example. (You can usually deal with that by using string formatting features.) Another option is to use the decimal numeric type. That has other compromises associated with it but, if retaining absolute decimal accuracy is your primary goal, it might suit you better. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Does one have to use curses to read single characters from keyboard?
On 12/12/2022 17:45, Alan Gauld wrote: Absolutely nothing apparently! But in practce I did pen some esponses to Davids post. However this list seems to strip out what I've written, its happened a few times now. Not every time but enough that I rarely post here. But I'll try once more... > On 11/12/2022 21:07, dn wrote: >> On 11/12/2022 23.09, Chris Green wrote: >>> Is the only way to read single characters from the keyboard to use >>> curses.cbreak() or curses.raw()? >> You may like to re-ask this question over on the Python-Tutor list. The >> ListAdmin over there (literally) wrote the book on Python+curses... Thanks for the plug David, but... While my book is, I think, the only one specifically for curses with Python, it's hardly a definitive tome on the subject, rather a beginner's tutorial. An expanded HowTo if you like.. >> Did such research include the keyboard module? >> https://pypi.org/project/keyboard/ There are several such modules, including a good one by Fred Lundh. They are cross platform and probably the best solution for the OP if he doesn't mind using a third party module. I think Fred's was called terminal? But its been a while I normally just use curses for anything terminal related. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Does one have to use curses to read single characters from keyboard?
On 11/12/2022 21:07, dn wrote: > On 11/12/2022 23.09, Chris Green wrote: >> Is the only way to read single characters from the keyboard to use >> curses.cbreak() or curses.raw()? If so how do I then read characters, >> it's not at all obvious from the curses documentation as that seems to >> think I'm using a GUI in some shape or form. >> >> All I actually want to do is get 'Y' or 'N' answers to questions on >> the command line. >> >> Searching for ways to do this produces what seem to me rather clumsy >> ways of doing it. > > You may like to re-ask this question over on the Python-Tutor list. The > ListAdmin over there (literally) wrote the book on Python+curses... > > > Did such research include the keyboard module? > https://pypi.org/project/keyboard/ > > This project includes an (Enter-free) "hot-key" feature which firstly > detects the specific key or key-combination, and then calls an action > if/when True. > (amongst other functionality) > > Quick read tutorial: > https://www.thepythoncode.com/article/control-keyboard-python > > Disclaimer: have had it on my 'radar', but never actually employed. > (if you have considered, will be interested to hear conclusions...) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: an oop question
On 03/11/2022 18:29, Chris Angelico wrote: > On Fri, 4 Nov 2022 at 05:21, Julieta Shem wrote: >> >> Chris Angelico writes: >> >>> On Thu, 3 Nov 2022 at 21:44, Alan Gauld wrote: >>>> Also Python is not a purely OOP language, in that you can write >>>> functional and procedural code in Python if you wish. In >>>> Smalltalk thats notionally impossible because everything >>>> is an object. And all programming statements are messages >>>> to objects. >>> >>> In Python, everything is an object. Doesn't that equally mean that >>> Python is purely OOP? >> >> I think Alan Gauld pointed out that even syntax is an object in >> Smalltalk --- or was. An if-statement in Python is not an object. > > Okay, fair; although I would be highly surprised if syntax is actually > an object The syntax isn't, it is a specification, but the AST certainly is and you can instantiate it and examine it from code. But the context here was Why *Alan Kay* doesn't include Python with Smalltalk as being OOP. There are plenty others who would call it so. But as for everything being an object, that's true but it doesn't alter the fact that the default mode of python programming is not to structure the code as a set of communicating objects (even if at some level everything is an object) but as a set of hierarchical functions. And fundamentally that's what Kay means by OOP. The program (not the language!) is built around objects. One of the greatest barriers to the adoption of OOP is the confusion between OOP and OOPL. And sadly the majority of attention has been on OOPL rather than OOP... > the concept "pass this message to this object" an object? Is the > message itself an object? Is it objects all the way down? At some point you hit C/Assembler. But it is astonishing just how far down the objects go in Smalltalk. But the control flow etc are fully OOP as per my last message. It if quite possible to subclass Boolean and override the whileTrue method to do something completely different to the normal while loop behaviour. Is it wise? No. But it is definitely possible! > At some point, any language with objects in it is "object oriented" to > some extent, and after that, it's all a spectrum. And this is exactly the problem. In the 80s we had a fairly clean concensus of what OOP meant and several different language approaches to that. But when C++ became popular(the defacto standard) peple started focussing on the language features and totally missed that Object Oriented Programming means writing programs that consist of objects communicating by messages. The language features(even classes) are merely implementation details. (I suspect this was partly driven by the fact that many university lecturers at the time didn't really grok OOP and teaching language features was much easier than teaching a new way of thinking about problems!) This was compounded when someone (Booch maybe?) came up with a set of criteria to determine whether a language was a "true OOPL" or merely "Object Based" (Ada and VB they're looking at you!) But frankly that was an irrelevance to OOP. You can do OOP (and I have!) in assembler and in COBOL - you just need to follow some agreed ground rules. It's a lot easier with an OOPL but it's not required. > multidimensional thing that's so tangled up that it guarantees that > people can happily debate for years to come. Exactly so. During the 90's there came to be at least 3 different camps of OOP evangelists and the OOP world slowly coalesced on a kind of hybrid amalgam with multiple names for the same feature and disagrements about which features are required or not to really be OOP. And as a result the whole concept of OOP has been muddied to the point that almost nobody does it anymore apart from (possibly) the Smalltalk crowd who have always smugly sat above the general throng content in the knowledge that theirs is the one true OOP! :-) Which brings us back to Alan Kay... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: an oop question
On 03/11/2022 00:25, Julieta Shem wrote: >> |OOP to me means only messaging, local retention and protection and >> |hiding of state-process, and extreme late-binding of all things. > > I'm wondering how Python fails to satisfy his definition. Python doesn't do any form of data protection/hiding. All attributes are public by default. In Smalltalk all attributes are private, with no way to make them public... Actually in C++/Java terms I believe they are "protected" because subclasses can access them(I think?). Also Python is not a purely OOP language, in that you can write functional and procedural code in Python if you wish. In Smalltalk thats notionally impossible because everything is an object. And all programming statements are messages to objects. Even an if/else test is a message to the boolean object: (5>3) ifTrue: ifFalse: ifTrue is a message to the boolean result of the expression which has a parameter of a block of code. It executes the block if the boolean is true. ifFalse is likewise a message to the same boolean object but only executes its block if the boolean is false. (Apologies if the syntax is out, its been a while since I wrote any Smalltalk!) Similarly loops are implemented as messages: whileTrue: to: do: So in Smalltalk absolutely everything is a message to an object. Python by comparison is much more traditional in form. It is possible to write procedural, non OOP code in Smalltalk but you really have to fight the system to do so. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: [correction]an oop question
On 02/11/2022 20:21, Dennis Lee Bieber wrote: >> shows that in Python we do *not* need subclassing/inheritance >> for polymorphism! >> > To me, that is not really an example of polymorphism, but more an > example of Python's "duck typing". But duck typing is a perfectly good implementation of polymorphism. The term just means that different objects respond to the same message in different ways. Nothing more, nothing less. Inheritance just happens to be the most common way of building that, especially in statically typed languages. > > I'd implement the example hierarchy as > class Language: > ... def f(self): > ... print(self.greeting) And that would be perfectly valid too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: an oop question
On 01/11/2022 17:58, Julieta Shem wrote: > nowhere in trying to detect in high-precision what is OOP and what is > not. Stefan has given a good answer but essentially OOP is a program that is structured around objects communicating by sending messages to one another. Objects are, in most (but not all) languages implemented using classes. A class is just a record or structure that can contain data and functions. In most (but not all) implementations of OOP messages are implemented as calls to the functions within an objects class. > The same for classes. I always liked to think of C structures as > some class. Provided that we allow pointers to functions within the struct then yes. Indeed the difference between structs and classes in C++ is very thin. And with the recent introduction of data classes in Python the boundaries are blurred here too. In pure OOP a class with only data would be pointless(since the data should ideally be hidden or "private"!) > structure Whatever si the class itself. Is this use of C outside of > OOP? I say it is not because my notion of OOP is that --- a way to make > objects and have methods operate on them, changing them or not. It's how many early attempts at OOP in C worked, including C++. Others, such as Objective C and cFlavours took a different approach. But conceptually methods do not "operate on objects" methods are how objects respond to messages. Eah object has its own method of handling a particular message. (This is polymorphism) In most (but not all) practical implementations methods are usually implemented as functions and so it seems like a message is just a synonym for acalling a method, but is more than that, it implies some kind of dynamic lookup. (for example when the method is implemented in a paremt class rather than the directly referenced one. But the functions that represent methods do indeed operate on their own object - ie self. > To me what distinguishes functional from imperative is, Not that imperative programming is not the same as OOP. Or at least it encompasses much more than OOP. Most OOP programs are written in imperative languages but it is possible to have functional OOP programs too. (If we consider the state data to be a single compound value that can only be changed by the object internally, or a new object with different state values returned.) >> IS-A relationship, so Stack inheriting Pair would mean that a Stack >> was a Pair. That is not really true. > > That's another interesting observation. I do not have much > understanding of how to really think of these things Read up on the Liskoff substitution principle as one approach to determining what an IS-A relationship means. Its not the only approach but it is less vague than some others! >> to complications. If in doubt use delegation instead. > > What is delegation? A fancy OOP term to mean containment. Specifically a method delegates the work top some internal object. eg. You can build a stack by containg a list within it. The stack delegates much of the work to the list object. In fact, in Python a stack can be a very thin wrapper over a list! > Any book recomendations on getting this thing mathematics-clear? The best book is IMHO Bertrand Meyer's book "Object Oriented Software Construction". It uses his own language,. Eiffel, but gives an excellent description of applied OOP and all of its features (Eiffel is perhaps the most feature complete OOPL of all - but, being proprietary (and somewhat buggy!) it has never quite caught on) But for a mathematical basis you need to look outside programming at systems engineering and the work done on cellular automata. In a pure OOP program each object should act as an independant cell communicating by asynchronous messages. Exactly as in cellular automata theory. .. Unfortunately, there is a huge gap between pure OOP theory and practical OOP languages! And just as big a gap between OOP language potential and real-world OOP usage. Very few purely OOP programs exist (maybe excepting in Smalltalk - see Stefan's posts again). :-( -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: an oop question
On 30/10/2022 14:01, Julieta Shem wrote: > I wrote the classes > > class Empty: > ... > class Pair: > ... > > (*) How to build a stack? > > These Lisp-like sequences are clearly a stack. That is a very important observation. A Pair IS-A Stack(sort of). If you had a stack you could create a Pair from it certainly. > So far so good, but when it comes to building a better user interface > for it I have no idea how to do it. I think one of the purposes of OOP > is to organize code hierarchically so that we can reuse what we wrote. One of the purposes of classes certainly. I'm not so sure it's a purpose of OOP. They are not the same thing. A class is a programming construct OOP is a programming style. Classes facilitate OOP but can be used outside of OOP too. > So I tried to make a Stack by inheriting Pair. But you said above that a Pair was a Stack. Inheritance implies an IS-A relationship, so Stack inheriting Pair would mean that a Stack was a Pair. That is not really true. A Stack could use a Pair (or many of them) but it is not a Pair. Trying to use inheritance inappropriately is one of the biggest (and commonest) mistakes in OOP. It invariably leads to complications. If in doubt use delegation instead. > class Stack(Pair): > pass > Stack(1, Empty()) > Stack(1, Empty()) > > Then I wrote pop and push. > Stack(1, Empty()).pop() > 1 > Stack(1, Empty()).push(2) > Stack(2, Stack(1, Empty())) > > So far so good. Now let me show you what I can't do. > > (*) The difficulty of encapsulating a union > > The Lisp-like sequences we're building here are union-like data > structures. A /sequence/ is either Empty() or Pair(..., /sequence/). I > have not found a way to represent this either-or datastructure with a > class. For example, there is no way right now to build an empty Stack > by invoking the Stack constructor. > Stack() > Traceback (most recent call last): > File "", line 1, in > TypeError: Pair.__init__() missing 2 required positional arguments: 'first' > and 'rest' > The usual Python approach to such things is to put some default values(often None but could be an Empty instance in your case) in the init() method parameter list. Then test if the inputs are None and if so take the appropriate action. > class Pair: > def __init__(self, first=Empty(), rest=Empty()): Like this. > if not isinstance(rest, Pair) and not isinstance(rest, Empty): > raise ValueError("rest must be Empty or Pair") > self.first = first > self.rest = rest > def fromIterable(it): > if len(it) == 0: > return Empty() > else: > return Pair(it[0], Pair.fromIterable(it[1:])) > def __str__(self): > return "{}({!r}, {})".format(self.__class__.__name__, self.first, > str(self.rest)) > def __repr__(self): > return str(self) > def __len__(self): > return 1 + self.rest.__len__() > > class Empty: > def __len__(self): > return 0 > def __str__(self): > return "Empty()" > def __repr__(self): > return self.__str__() > def __new__(clss): > if not hasattr(clss, "saved"): > clss.saved = super().__new__(clss) > return clss.saved > > class Stack(Pair): > def pop(self): > return self.first > def push(self, x): > return Stack(x, self) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Python/New/Learn
On 05/05/2022 02:36, Patrick 0511 wrote: > Hello, I'm completely new here and don't know anything about python. Do you know any other programming languages? That makes a huge difference in what you should start with! > Can someone tell me how best to start? > So what things should I learn first? Others have already made recommendations. I'll add that there is a dedicated python ttutor list for those just learning to ask questions. It is slightly more tolerant of "silly" questions and rookie mistakes than the main list here. You'll also find most of the discussions there will be closer to your level than the more advanced topics that get addressed here. Finally, I have a tutorial aimed at complete beginners, see the link below... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Python app on a Mac
On 15/04/2022 19:53, MRAB wrote: >> When I start the program I get a Terminal window as well >> as the GUI. On Windows I'd run it with pythonw and in Linux >> ... >> Does anyone know how to launch a Python program from the >> desktop without a Terminal window (or at least with an >> iconified one!) Does it require Applescript or somesuch? >> > There's an answer here: > > https://stackoverflow.com/questions/50792048/running-a-python-script-without-opening-terminal Yes, I've already done all that. The script runs and the GUI displays but so does a Terminal in the background. The SO answer does mention you can get the Terminal to close when the script terminates whhich would be better than now. However, another answer mentions something called Automator, which I'll need to Google... Thanks for the pointer though. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Python app on a Mac
I've just migrated from a Linux PC to a Mac mini running Monterey. I have a Python GUI(Tkinter) app that I wrote on Linux and have managed to get working on MacOS except When I start the program I get a Terminal window as well as the GUI. On Windows I'd run it with pythonw and in Linux I just created a desktop launcher to avoid that. But there is no pythonw on MacOS nor a simple way I can find to launch apps from the desktop. Does anyone know how to launch a Python program from the desktop without a Terminal window (or at least with an iconified one!) Does it require Applescript or somesuch? Alan G. -- https://mail.python.org/mailman/listinfo/python-list
Fwd: Re: Long running process - how to speed up?
On 19/02/2022 11:28, Shaozhong SHI wrote: > I have a cvs file of 932956 row That's not a lot in modern computing terms. > and have to have time.sleep in a Python > script. Why? Is it a requirement by your customer? Your manager? time.sleep() is not usually helpful if you want to do things quickly. > It takes a long time to process. What is a "long time"? minutes? hours? days? weeks? It should take a million times as long as it takes to process one row. But you have given no clue what you are doing in each row. - reading a database? - reading from the network? or the internet? - writing to a database? or the internet? - performing highly complex math operations? Or perhaps the processing load is in analyzing the totality of the data after reading it all? A very different type of problem. But we just don't know. All of these factors will affect performance. > How can I speed up the processing? It all depends on the processing. You could try profiling your code to see where the time is spent. > Can I do multi-processing? Of course. But there is no guarantee that will speed things up if there is a bottleneck on a single resource somewhere. But it might be possible to divide and conquer and get better speed. It all depends on what you are doing. We can't tell. We cannot answer such a vague question with any specific solution. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Advanced ways to get object information from within python
On 23/12/2021 11:01, Julius Hamilton wrote: > Lastly, the "help" function. > > I find "help" to similarly be a situation of information overload. I assume you know that you can target help() to the specific attribute or function you need not just the top level classes? So combined with dir() you can call help on each of the names that dir() reveals. That usually produces a much more focused form of documentation. So in your example: > dir(scrapy) shows this: >['Field', 'FormRequest', 'Item', 'Request', 'Selector', 'Spider', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_txv', 'exceptions', 'http', 'item', 'link', 'linkextractors', 'selector', 'signals', 'spiders', 'twisted_version', 'utils', 'version_info'] > I wish there was a convenient way for me to know what > all of these are. help(scrapy.http) help(scrapy.spiders) etc... And if it turns out they are not functions or classes you can use [p]print to get the values. You can also use type() to clarify what kind of thing an attribute is. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Fwd: Re: sum() vs. loop
On 10/10/2021 09:49, Steve Keller wrote: > I have found the sum() function to be much slower than to loop over the > operands myself: > > def sum_products(seq1, seq2): > return sum([a * b for a, b in zip(seq1, seq2)]) > > def sum_products2(seq1, seq2): > sum = 0 > for a, b in zip(seq1, seq2): > sum += a * b > return sum > > In a program I generate about 14 million pairs of sequences of ints each > of length 15 which need to be summed. The first version with sum() needs > 44 seconds while the second version runs in 37 seconds. > > Can someone explain this difference? I'm no expert on Python innards but it looks to me like the first version loops over the length of the list twice, once to generate the list of products and the second time to add them together. The pure Python version only loops once because it does the addition in transit. Presumably, especially for large numbers, a single python loop is faster than 2 C loops? But that's purely my speculation. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Question again
On 16/09/2021 06:50, af kh wrote: > Hello, > I was doing some coding on a website called replit I have no idea what that is but... > after answering 'no' or 'yes' after the last sentence I wrote, > the Python window shut off, That's what you told it to do in the code. Regardless of which answer the user gives the program reaches the end and stops. > in replit I added one more sentence, but it isn't shown on Python, I dn;t know what this means. > #Gives greetings to the user > import random ... > #Ask to pick between numbers 1~10 to see if you will get lucky today: Third > question > number = input("Please pick between numbers 1~10 to see your luck for today: > ") > > #From number 1~3 and an answer > if number == "1" or number == "2" or number == "3" : > print("You're in grat luck today!") > > #From number 4~7 and an answer > elif number == "4" or number == "5" or number == "6" : > print("damn, bad luck is coming your way") The cde and comment are not consistent. > #From number 8~10 and an answer > elif number == "7" or number == "8" or number == "9" or number == "10" : > print("I cannot sense any luck today, try again next time") Same here. > #Add a statement and question: Fourth question > print("That will be all for today's chitchat, woohooo! would you like to exit > the chat?") > #User says 'yes' > reply = input() > > #If user says 'yes' reply 'wait hold on! are you really leaving??': Fifth > question > if reply == "yes" : > print("Wait hold on! are you really leaving??") > > #User answers > answer = input() > #If user says 'yes' again, reply 'fine! bye then!' > if answer == "yes" : > print("Fine! bye then!") Shouldn't those lines be indented as part of the if statement above? > #Other than that if user says 'no', reply 'just kidding we're done here haha' > elif answer == "no" : > print("just kidding we're done here haha") But the code always gets to the end, there is nothing to stop it exiting. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Friday Finking: Contorted loops
On 12/09/2021 09:11, jak wrote: > if the only way to terminate a 'while True' loop is by using the 'break' > statement, why is it allowed to add the 'else' statement which will only > contain dead code? > > while True: > break > else: > print('dead code') > Because to the interpreter the condition is not part of the language. It is syntactically correct. An optimiser OTOH might welkl determine that the condition will never fail and therefore the else clause never be reached, in which case it would remove the dead code (possibly emitting a warning in the process?). A linter likewise might identify the redundant code. I don't use any python linters, does anyone know if they do detect such dead spots? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Friday Finking: Contorted loops
On 11/09/2021 15:41, Peter J. Holzer wrote: > How is C's do/while loop more horrible than Pascal's repeat/until? Because it is very hard to spot or distinguish from a normal while loop. while condition ; Is a valid (and fairly common) loop in C so code that has do{ code } while condition; Looks, for non-trivial cases, like a lot of code followed by an empty while loop. The do is easy to miss and the while loop disguised as a repeat termination is confusing. repeat code until condition Is far clearer to comprehend since there is no ambiguity. > In an old collection of small C programs of mine I find: > > 35 regular for loops > 28 while loops > 2 infinite for loops > 1 "infinite" for loop (i.e. it exits somewhere in the middle) > 0 do/while loops. That wouldn't surprise me, I've only used do/while in C a handful of times. But in Pascal I use it regularly. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Friday Finking: Contorted loops
On 10/09/2021 19:49, Stefan Ram wrote: > Alan Gauld writes: >> OK, That's a useful perspective that is at least consistent. >> Unfortunately it's not how beginners perceive it > ... > > Beginners perceive it the way it is explained to them by > their teacher. I'm not sure that's true. Most beginners, in my experience, learn the syntax from their teachers and then go off and play. What they observe happening is what sticks. And python loop 'else' constructs appear inconsistent to them. As teachers we like to think we are passing on our wisdom to our students but in reality everyone learns from their own experience. The teachers advice is just the starting point. Hopefully, that starting point sends them in the right direction but that's the best we can hope for. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Friday Finking: Contorted loops
On 10/09/2021 16:36, MRAB wrote: >> while...else... >> >> executes the else if the body of the loop does NOT get executed. >> >> for...else... >> >> executes the else iff ALL iterations of the for loop DO complete. >> > [snip] > > In both cases, it executes the 'else' part if it didn't break out of the > loop. That's it. OK, That's a useful perspective that is at least consistent. Unfortunately it's not how beginners perceive it and it causes regular confusion about how/when they should use else with a loop. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Friday Finking: Contorted loops
On 10/09/2021 00:47, Terry Reedy wrote: > even one loop is guaranteed.) "do-while" or "repeat-until is even rarer > since fractional-loop include this as a special case. Is there any empirical evidence to support this? Or is it just a case of using the tools that are available? In my experience of using Pascal (and much later with Delphi) that I used repeat loops at least as often as while loops, possibly more. But using Python and to a lesser extent C (which has a rather horrible do/while) construct I use while loops (often with an if-break) simply because that's what the language offers. So is it the case that the "need" for repeat loops is rare, simply a result of there being no native repeat loop available? After all we could have done without a for loop too and just used a while loop for everything (as was done in Oberon(?) ) Would we then state that the use of for loops was rare? But I would hope that any empirical research would look at the wider function of the loop and its purpose rather than merely analyzing the syntax and keywords. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Friday Finking: Contorted loops
On 09/09/2021 22:36, dn via Python-list wrote: > Even in fairly modest Python constructs, we quickly repeal the one-in, > one-out philosophy because try...except operates by providing another > exit-path. Exceptions are exceptional by their nature (or should be!) As such they can arguably be excused from the SP strictures. But python complicates this tenet still further by adding an else clause to its loops. And complicating this still more is that these else clauses have almost exactly opposite effects. while...else... executes the else if the body of the loop does NOT get executed. for...else... executes the else iff ALL iterations of the for loop DO complete. This confuses beginners immensely - and quite a few non beginners too; which is probably why they are not often seen "in the wild". This adds to the question of where exactly does a Python loop end? Is it after the code-suite following the loop construct? Or is it after the else code-suite, where such exists? Returning to the specific case of a repeat structure. In the case of a while loop the else offers another option: while condition loop-body else loop-body Now loop-body always gets executed at least once. But at the cost of duplicating the loop-body code, thus violating DRY. Just another thought... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: on writing a while loop for rolling two dice
On 07/09/2021 15:53, Grant Edwards wrote: > I remember engineering manager I worked with about 35 years ago who > used a set of C macros to try to make his code look as much like BASIC > as possible: > > #define IF if ( > #define THEN ) { > #define ELSE } else { > #define ENDIF } > ... > > IIRC he copied them out of a magazine article. That was quite common in C before it became popular(early/mid 80s). I've seen Pascal, Algol and Coral macro sets in use. You could even download pre-written ones from various bulletin boards (remember them?!) for a while. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: The sqlite3 timestamp conversion between unixepoch and localtime can't be done according to the timezone setting on the machine automatically.
On 03/09/2021 18:37, Chris Angelico wrote: Without DST the schools opened in the dark so all the kids had to travel to school in the dark and the number of traffic accidents while crossing roads jumped. > > Are you saying that you had DST in winter, or that, when summer *and* > DST came into effect, there was more light at dawn? Because a *lot* of > people confuse summer and DST, and credit DST with the natural effects > of the season change. OK, I see the confusion. What I should point out was that the experiment involved us staying on DST and not reverting to UTC in the winter - that unified us with most of the EU apparently... So although I'm saying DST it was really the non-reversion from DST to UTC that caused problems. Arguably, if we just stayed on UTC and didn't have DST at all there would be no issue - except we'd be an hour out of sync with the EU. (Post Brexit that may not be seen as a problem!! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: The sqlite3 timestamp conversion between unixepoch and localtime can't be done according to the timezone setting on the machine automatically.
On 02/09/2021 19:30, Chris Angelico wrote: >> Without DST the schools opened in the dark so all the kids >> had to travel to school in the dark and the number of >> traffic accidents while crossing roads jumped. > > How do they manage in winter? That was the winter. Sunrise wasn't till 10:00 or so and the schools open at 9. With DST sunrise became 9:00 and with pre-dawn light it is enough to see by. Its a recurring theme. Every now and then some smart young politician from the south of the UK suggests doing away with DST and a large crowd of northerners jump up and say no way! > Can that be solved with better street> lighting? They had street lighting but it casts dark shadows etc. In fact modern LED based street lighting is worse in that respect that the old yellow sodium lights were. But where it doesn't exist the cost of installing street lighting in small villages is too high compared to just changing the clocks. And of course street lighting has a real running cost that would be reflected in the local council taxes, and nobody wants to pay more of them! After all street lighting has been available for over 150 years, if they haven't installed it by now (I mean, nearly everywhere has some lighting, at least on the main roads, it's just the smaller back streets that tend to be dark.) > That was fifty years ago now, and the negative consequences > of DST are far stronger now. But not apparent to most people. Most still see it as a benefit because they get longer working daylight. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: The sqlite3 timestamp conversion between unixepoch and localtime can't be done according to the timezone setting on the machine automatically.
On 02/09/2021 20:11, MRAB wrote: >> In one of them (I can't recall which is which) they change on the 4th >> weekend of October/March in the other they change on the last weekend. >> >> > In the EU (and UK) it's the last Sunday in March/October. > > In the US it's second Sunday in March and the first Sunday in November. > > I know which one I find easier to remember! Interesting. I remember it as closer than that. The bugs we found were due to differences in the DST settings of the BIOS in the PCs. (They were deliberately all sourced from DELL but the EU PCs had a slightly different BIOS). The differences you cite should have thrown up issues every year. I must see if I can find my old log books... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: The sqlite3 timestamp conversion between unixepoch and localtime can't be done according to the timezone setting on the machine automatically.
On 02/09/2021 19:28, Chris Angelico wrote: >> Except for the places that don't follow the IANA scheme and/or >> dynamically change their time settings on a whim. To be complete >> you need the ability to manually override too. >> > > What places are those? Mainly small non-tech oriented places such as small pacific islands or principalities with local governance - such as by a group of tribal elders. I mentioned earlier the example of Andorra announcing on the Friday night before a DST change that they were deferring it for a week to preserve the skiing conditions. But we came across several similar situations in dealing with multi-national service centres. > IANA maintains the database by noticing changes > and announcements, and updating the database. But don;t those have to be electronic in nature? How, for example would it pick up the radio news announcement mentioned above? > governments need to "opt in" or anything. Stuff happens because people > do stuff, and people do stuff because they want to be able to depend > on timezone conversions. Umm, they do DST because it makes their lives easier - more daylight, extra work time. etc. The needs of, or impact on, computers in these kinds of small localities and communities are way down the pecking order. > There ARE times when a government makes a change too quickly to get > updates out to everyone, especially those who depend on an OS-provided > copy of tzdata, so I agree with the "on a whim" part. Though, > fortunately, that's rare. I agree it is very rare and if you only operate in mainstream localities you probably never see it as an issue, it's only when you need to support "off grid" locations that manual control becomes important. Also the problems we had were about 15 years ago, things may be better ordered nowadays. (I've been retired for 7 years so can't speak of more recent events) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: The sqlite3 timestamp conversion between unixepoch and localtime can't be done according to the timezone setting on the machine automatically.
On 31/08/2021 23:31, Chris Angelico wrote: > Ah, good to know. I think that actually makes a lot of sense; in the > US, they try to let everyone pretend that the rest of the world > doesn't exist ("we always change at 2AM"), but in Europe, they try to > synchronize for the convenience of commerce ("everyone changes at 1AM > UTC"). There's another gotcha with DST changes. The EU and USA have different dates on which they change to DST. In one of them (I can't recall which is which) they change on the 4th weekend of October/March in the other they change on the last weekend. That means on some years (when there are 5 weekends) there is a week when one has changed and the other hasn't. That caused us a lot of head scratching the first time we encountered it because our service centres in the US and EU were getting inconsistent time reporting and some updates showing as having happened in the future! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: The sqlite3 timestamp conversion between unixepoch and localtime can't be done according to the timezone setting on the machine automatically.
On 31/08/2021 22:32, Chris Angelico wrote: > If we could abolish DST world-wide, life would be far easier. All the > rest of it would be easy enough to handle. We tried that in the UK for 2 years back in the '70s and very quickly reverted to DST when they realized that the number of fatalities among young children going to school doubled during those two years. Without DST the schools opened in the dark so all the kids had to travel to school in the dark and the number of traffic accidents while crossing roads jumped. In fact during WW2 they increased DST to 2 hours (that was for the farmers!) because it meant that farm labourers would start work at first light, effectively extending the working day. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: The sqlite3 timestamp conversion between unixepoch and localtime can't be done according to the timezone setting on the machine automatically.
On 31/08/2021 22:13, Chris Angelico wrote: > But ultimately, it all just means that timezones are too hard for > humans to handle, and we MUST handle them using IANA's database. It is > the only way. Except for the places that don't follow the IANA scheme and/or dynamically change their time settings on a whim. To be complete you need the ability to manually override too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: The sqlite3 timestamp conversion between unixepoch and localtime can't be done according to the timezone setting on the machine automatically.
On 31/08/2021 13:45, Chris Angelico wrote: > (I find the Ireland situation particularly amusing. Time zones and daylight saving arrangements in particular are a nightmare at the micro level. I once worked on a large customer support application which required all dates/times to be viewable in UTC plus any of: - The local support centre's time (eg. Tokyo, Japan) - The customer organization's local time(eg. Seoul, Korea) - The local site time (some remote island in the pacific...) The big problem was the last one since some small countries have local arrangements for timezones that don't conform to the official ones. One pacific island had dual "patrons" and to avoid offending either they adopted a non-standard "timezone" half-way between the two patron's zones! In another case we had the principality of Andorra deciding to put off switching to DST for an extra week because it would make the snow melt faster and spoil the skiing! This was decided by the council on the Friday before it was due to happen and announced on the local radio... I got more grey hairs on that project than any other. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Python UI (was Re: urgent)
On 29/08/2021 11:28, Hari wrote: > i was download ur python software but it is like boring user interface I agree it is a boring user interface. Just 3 chevrons: >>> You can change it a little if you want but ultimately its just an invitation to type commands. What kind of interface did you have in mind? If you want a GUI to develop code there are literally dozens of those. But ultimately programming is about typing text into an editor. > me like young student to learn ,can u have any updates? There are many tools to help you work with python. If you tell us what kind of things you want we can tell you where to find them (if they exist!) But the basic Python interpreter is primarily there to run your programs, it's hard to see how you can make that less boring without also making it very inefficient. And professional users would hate that! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: on writing a while loop for rolling two dice
On 28/08/2021 21:50, Hope Rouselle wrote: >>> roll_count = 0 >>> while True: >>> outcome = roll_two_dice() >>> roll_count += 1 >>> if outcome[ 0 ]== outcome[ 1 ]: break >>> return roll_count, outcome[ 0 ] >> > > Wait, I'm surprised ``outcome'' is still a valid name at the > return-statement. Wasn't it defined inside the while? If that really bugs you just replace the break with the return. >>> if outcome[ 0 ]== outcome[ 1 ]: >>>return roll_count, outcome[ 0 ] Now its all inside the loop. But remember readable code is better than cute code every time. And personally I'd just declare the x,y up front. Easier to understand and debug IMHO. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: tkinter
On 21/08/2021 19:37, Tony Genter wrote: >Tkinter stopped working overnight from 8/20/2021 to 8/21/2021. Last night >I was working on tutorials to work on a GUI and this morning every file >that uses tkinter is broken stating that no module `tkinter' exists. Are you sure you were running Python v3 and not python v2? In v2 tkinter is spelled Tkinter. If that is the issue then reinstalling python v3.x and ensuring that it is the executable used should resolve the issue. Another option might be that you are using virtual environments which could result in all manner of chaos and confusion if you inadvertently start the wrong one... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Tkinter widgets for desktop database application
On 13/07/2021 21:24, Rich Shepard wrote: > What have other developers used for the UI on a stand-alone database > application not using a web browser? Mostly I just use a scrolledlistbox and a set of functions for formatting the data into columns for display. The big snag is you can't do spreadsheet-like things such as select a single field value or sort by a single column without writing a fair bit of code. But for simple display, and selection of a single record it works ok. But a good grid control would be nice. I did try to use the Tix.grid widget but failed. And now Tix is deprecated. I'm sure there must be a third-party one somewhere but I've never taken the time to hunt one down. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: tkinter: tksheet
On 17/06/2021 00:15, Rich Shepard wrote: > When I view my contacts table it needs to includes attributes from the > company, people, and contacts tables so I can view all prior contacts with > that person. Sounds like a job for a database view. Can you modify the database schema? Could you create a view - even a temporary one just while your app is running? Alternatively, and I've done this trick myself, create an in-memory SqlLite database with a table that holds all the columns you want then fetch the data from the master and manipulate/view it from Sqlite - this makes sorting by different columns fast and simple. The downside is you have to refresh it periodically or you will miss all changes in the master. > Many years ago I used wxPython. For several reasons I decided to learn and > use tkinter from now one. One reason is that the application for my clients > will run mostly on windows hosts and I want to limit the software they need > to install and maintain in order to run it. Sure, that's the main reason I use tkinter too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: tkinter: tksheet
On 16/06/2021 21:45, Rich Shepard wrote: > The two applications I'm building are both database applications. If > tksheet() is not the most appropriate widget to display database tables what > alternative would be better? I've not used tksheet but it sounds like it might be worth investigating. There is a grid in Tix but its quite hard to use and Tix is now deprecated. It was also a bit unreliable when used from Python (that's euphemistic for "I couldn't get it to work!" :-) But there is nothing I know of for Tkinter that provides views of database tables in the way that Delphi or VB or C# do, for example. You have to extract the data using SQL and populate the table and manage all changes (of both view and data) yourself. A good grid component would be a huge boon for tkinter, its one of the most commonly used widgets in VB/Delphi etc A DB-API linked grid would be the height of luxury... If you do a lot of that kind of desktop apps then you could look at Dabo which is built on wxPython but has links to databases. Unfortunately it looks like work ground to a halt about 5 years ago. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Terminology: EU language skills, and Master to Main (or ...)
On 13/06/2021 04:21, dn via Python-list wrote: > What do you think a professionally-recognisable series of skill-levels > for programmers? This has been done or attempted many times, with perhaps the most complete scheme being the British Computer Society's "Industry Standard Model" which breaks jobs/skills in the industry into many categories(30 or so?) and within each category there are up to 6 levels of achievement. (Some skills don't have the lowest levels(e.g. architect) while some only have lower levels. The theory being a level 6 practitioner in and skill is equally "good" as a level 6 in any other skill. One of the skills is programming, and significantly, it is language independent. I don't know if the ISM is still in use, it is many years since I worked with the BCS as the training officer for our office. But there used to be a comprehensive set of web pages describing the requirements for each level for each skill. A quick search for BCS ISM didn't throw up a link, sorry. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Tkinter8.6: date picker
On 11/06/2021 22:20, Rich Shepard wrote: > I need a date picker +1 -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: fabric: fab command
On 02/06/2021 14:35, jayshankar nair via Python-list wrote: > import tools.fab.dev_utils as dev_utilsImportError: No module named > tools.fab.dev_utils > Please let me know which package i have to install. Work backwards. Can you import tools.fab? Can you import tools? Once you know what you do have you can figure out what you don't and why. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Neither pdb or print() displays the bug
On 01/06/2021 21:18, Rich Shepard wrote: > On Sun, 30 May 2021, Cameron Simpson wrote: > >> I've only just started with pdb. As of Python 3.7 there's a builtin >> function named breakpoint() which drops you into the debugger. > I'm stuck with neither approach (pdb, print()) working. > The activitytypes.py module: > > class ATMainWindow(qtw.QMainWindow): > > def __init__(self): > super().__init__() > > # Model/View here. > self.model = qts.QSqlTableModel(db=db) # for single table > self.model.setTable('activitytypes') > self.model.select() > > self.table = qtw.QTableView() > self.table.setModel(self.model) > > self.setFixedSize(qtc.QSize(800, 600)) Assuming this is the line you want to examine set a beakpoint just above it using the function that Cameron mentioned (Or just set a breakpoint on the init() from pdb... Trying to use step/next to debug an event driven application is next to impossible. set breakpoints on the methods that get triggered by events then generate the event to reach the breakpoint. Or, as in this case, on the init if you want to examine objects as they are created. As a general rule if you have to hit next/step more than half a dozen times in a row you are probably making extra work for yourself! >> $/development/business_tracker/activitytypes.py(29)() > -> window = ATMainWindow() > (Pdb) n > False >> $/development/business_tracker/activitytypes.py(30)() > -> window.show() > (Pdb) n >> $/development/business_tracker/activitytypes.py(32)() > -> app.exec_() > (Pdb) n > n >> $/development/business_tracker/activitytypes.py(32)()->None > -> app.exec_() > (Pdb) n I'm not sure why you got that twice. I'd expect you to only see it once. > > and there it sits. No (Pdb) prompt, nothing. And no printed statements. It's waiting while the app runs and for you to terminate it. > I'd appreciate recommendations on the process to find where the bug lives > since I can't seem to find it with print() or line-by-line in pdb. Use breakpoints, don't try to step through the code from the beginning - there lies madness! And for event handlers that get called a lot use conditional breakpoints so that you only stop when you want to. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Definition of "property"
On 31/05/2021 15:59, Dennis Lee Bieber wrote: > On Sun, 30 May 2021 21:20:24 +0100, Alan Gauld via Python-list > declaimed the following: > >> On 30/05/2021 17:57, Irv Kalb wrote: >>> I am doing some writing (for an upcoming book on OOP), and I'm a little >>> stuck. >> >> Oh dear, that's one of myt hot buttons I'm afraid! >> I hope it really is about OOP and not about classes. Classes >> are such a minor part of OOP that it is depressing how many > To me, OOP tends to be language specific... OOP is supposed to be a programming paradigm in the same way that Functional or Logic programming are paradigms. Its all about how you organise your code. It should be based on message passing between autonomous agents(objects). Classes etc are language constructs aimed at making OOP easier, but they are not OOP. It's very easy to build a class/object based program that is not in any way OOP (in fact I'd go as far as to say the majority of such programs today come into that category). It's also possible (but difficult!) to build an OOP program without classes. Incidentally, I'm not arguing that classes should not be used in imperative programming, they can be very powerful there too. Just that using classes is not necessarily OOP. > Finding books on OOAD -- which should be language agnostic -- is > more difficult, and tend to turn into books about how to use > UML rather than how to analyze/design using OO. That's a fairly modern phenomenon. Most of the early books about OOAD were language agnostic - even when they used a language for demonstration purposes. Books like Grady Booch's classic OOAD, or Peter Coad's series with Ed Yourdon. The so-called method wars. They all had their own methodology, but mostly that was just diagrammatic variances. The underlying techniques and resultant structures were the same. (And hence the move to UML, which is just a notation - an extremely useful one, although often abused through over zealous application.) Even Rumbaugh's OMT book was meant to be general OOD, although IMHO it was the least OO of all of them being heavily based on data modelling. Sadly, there are very few books today that even attempt to describe the difference between OOP and the more common procedural programming paradigm. Discussions of OOP have degenerated into discussions about OOPL features rather than how to build worlds of objects passing messages to each other. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: How to debug python + curses? [was: RE: Applying winpdb_reborn]
On 31/05/2021 16:16, Grant Edwards wrote: > On 2021-05-30, Alan Gauld via Python-list wrote: >> You are not alone. debugging curses is one of the biggest obstacles to >> its use. > > Can't you just run the debugger in a different window and attach to > the process you want to debug? That's how one uses a debugger with > curses apps written in C/C++. That's how we did it when I used curses on VMS/Unix using C. But I confess I didn't think you could attach any python debugger to another python session? > Or I add debugging printf calls which > write to stderr and redirect stderr to a file. I do use logging sometimes but its not as immediate as seeing the messages in the application as you run it. >> My approach is to define a status line at the bottom of my program and >> write print statements into that window. Something like: > > Why not just use the standard python logging facility and log to a > file or another terminal window? I find the immediacy of an in-window message much easier. Its like using print() statements in a regular CLI application. Its there in front of you, no other terminals to look at. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Definition of "property"
On 31/05/2021 01:24, Greg Ewing wrote: > On 31/05/21 8:20 am, Alan Gauld wrote: >> >> That's a very Pythonic description. > > If it's a book about Python, it needs to be. The word "property" > has a very specialised meaning in Python. > > In some other languages it's used the way we use "attribute" in > Python. So a Python-specific definition is necessarily going > to be very different from a generic one. That was the point, the OP said it was a book about OOP. Not a book about "OOP in Python". The two are not synonymous. If we go back to the very beginnings of OOP, properties were defined as the publicly available state variables of the object. (Some others favoured using "properties" to describe the entire set of messages to which an object could respond). In classification theory they are defined as "the essential characteristics of an object that identify it with a class" Some theorists also insist that such properties be immutable after instantiation of the object. The first could be considered quite close to what Python does(or allows you to do) but the second is quite different! Although properties can be used to create a form of immutablity. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Definition of "property"
On 30/05/2021 23:57, Mike Dewhirst wrote: > > A property is an object method masquerading as a cachable object attribute Or a group of methods perhaps? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: How to debug python + curses? [was: RE: Applying winpdb_reborn]
On 30/05/2021 18:26, pjfarl...@earthlink.net wrote: > I tried winpdb-reborn some time last year on my Win10 system (python 3.8.3 > at that time), but could not figure out how to use it to debug a python > script that uses the curses module. You are not alone. debugging curses is one of the biggest obstacles to its use. My approach is to define a status line at the bottom of my program and write print statements into that window. Something like: def main(stdwin): appwin = curses.newwin(...) # LINES-1 high status = curses.newwin(...) # 1 line high positioned on bottom # more code here status.addstr(0,0, "Value of foo = %s" % foo) curses.wrapper(main) After debugging the status window can either be retained as an application status bar or removed and the main window enlarged by one line... If anyone else has found a better way to debug curses code I'm also keen to hear! HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list
Re: Definition of "property"
On 30/05/2021 17:57, Irv Kalb wrote: > I am doing some writing (for an upcoming book on OOP), and I'm a little > stuck. Oh dear, that's one of myt hot buttons I'm afraid! I hope it really is about OOP and not about classes. Classes are such a minor part of OOP that it is depressing how many books and articles focus on them to the exclusion of all else that make up the OOP paradigm! Anyway, rant over... > I understand what a "property" is, how it is used and the benefits, Do you? What is that based on? Is it how properties are used in OOP? Or how they are used in Python? Is your book truly about OOP or how Python does OOP (very different things!) How do python properties compare to properties in other languages like Object Pascal(aka Delphi) and Eiffel for example? Which of these 3 options most closely models the pure OOP concept of a property? > definition of property. In OOP or in Python? Or both? > A property object has getter, setter, and deleter methods > usable as decorators that create a copy of the property > with the corresponding accessor function set to the decorated function. That's a very Pythonic description. > (I would like to avoid going through the whole derivation > with the property function, as that would distract from > the points that I am trying to make.) Which are? Hopefully, about abstraction of data and function/methods therby encouraging polymorphic representations of program structures, which is the essence of OOP. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos -- https://mail.python.org/mailman/listinfo/python-list