Correct syntax for pathological re.search()
I'm trying to discard lines that include the string "\sout{" (which is TeX, for those who are curious. I have tried: if not re.search("\sout{", line): if not re.search("\sout\{", line): if not re.search("\\sout{", line): if not re.search("\\sout\{", line): But the lines with that string keep coming through. What is the right syntax to properly escape the backslash and the left curly bracket? -- Michael F. Stemper No animals were harmed in the composition of this message. -- https://mail.python.org/mailman/listinfo/python-list
Re: Correct syntax for pathological re.search()
On 07/10/2024 08.56, Stefan Ram wrote: "Michael F. Stemper" wrote or quoted: if not re.search("\\sout\{", line): So, if you're not down to slap an "r" before your string literals, you're going to end up doubling down on every backslash. Never heard of that before, but it did the trick. Long story short, those double backslashes in your regex? They'll be quadrupling up in your Python string literal! for line in lines: product = re.search( "sout\\{", line ) This also worked. For now, I'll use the "r" in a cargo-cult fashion, until I decide which syntax I prefer. (Is there any reason that one or the other is preferable?) Thanks for your help, Mike -- Michael F. Stemper Economists have correctly predicted seven of the last three recessions. -- https://mail.python.org/mailman/listinfo/python-list
Re: troglodytes
On 8/13/24 3:24 AM, Robin Becker via Python-list wrote: > I am clearly one of the troglodytes referred to in recent discussions around > the PSF. I've been around in python land > for far too long, my eyesight fails etc etc. > > I feel strongly that a miscarriage of justice has been made in the 3-month > banning of a famous python developer from > some areas of discourse. > > I have had my share of disagreements with others in the past and have been > sometimes violent or disrespectful in emails. > > I might have been in the kill list of some, but never banned from any mailing > lists. > > Honest dialogue is much better than imposed silence. > > -- grumblingly-yrs -- > Robin Becker Agreed. Here's a good summary of the issue: https://chrismcdonough.substack.com/p/the-shameful-defenestration-of-tim The PSF has really screwed this up. Really embarrassing, frankly. And sad. -- https://mail.python.org/mailman/listinfo/python-list
Re: IDLE: clearing the screen
On 08/06/2024 14.18, Rob Cliffe 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. The only flaw is that there is a blank line at the very top of the screen, and the ">>>" prompt appears on the SECOND line. (This blank line is because the IDLE prints the blank value returned by "return ''" and adds a newline to it, as it does when printing the value of any expression.) Why have it return anything at all? -- Michael F. Stemper Indians scattered on dawn's highway bleeding; Ghosts crowd the young child's fragile eggshell mind. -- https://mail.python.org/mailman/listinfo/python-list
Re: IDLE: clearing the screen
On 10/06/2024 09.32, Stefan Ram wrote: "Michael F. Stemper" wrote or quoted: On 08/06/2024 14.18, Rob Cliffe wrote: OK, here is the advanced version: import os class _cls(object): def __repr__(self): os.system('cls') return '' cls = _cls() ... Why have it return anything at all? Because __repr__ needs to return a str. Got it. Thanks for clarifying. -- Michael F. Stemper 87.3% of all statistics are made up by the person giving them. -- https://mail.python.org/mailman/listinfo/python-list
Re: A technique from a chatbot
On 03/04/2024 13.45, Gilmeh Serda wrote: On 2 Apr 2024 17:18:16 GMT, Stefan Ram wrote: first_word_beginning_with_e Here's another one: def ret_first_eword(): ... return [w for w in ['delta', 'epsilon', 'zeta', 'eta', 'theta'] if w.startswith('e')][0] ... ret_first_eword() 'epsilon' Doesn't work in the case where there isn't a word starting with 'e': >>> def find_e( l ): ... return [w for w in l if w.startswith('e')][0] ... >>> l = ['delta', 'epsilon', 'zeta', 'eta', 'theta'] >>> find_e(l) 'epsilon' >>> l = ['The','fan-jet','airline'] >>> find_e(l) Traceback (most recent call last): File "", line 1, in File "", line 2, in find_e IndexError: list index out of range >>> -- Michael F. Stemper If it isn't running programs and it isn't fusing atoms, it's just bending space. -- https://mail.python.org/mailman/listinfo/python-list
Re: Popping key causes dict derived from object to revert to object
On 25/03/2024 01.56, Loris Bennett wrote: Grant Edwards writes: On 2024-03-22, Loris Bennett via Python-list wrote: Yes, I was mistakenly thinking that the popping the element would leave me with the dict minus the popped key-value pair. It does. Indeed, but I was thinking in the context of dict_list = [d.pop('a') for d in dict_list] and incorrectly expecting to get a list of 'd' without key 'a', instead of a list of the 'd['a]'. I apologize if this has already been mentioned in this thread, but are you aware of "d.keys()" and "d.values"? >>> d = {} >>> d['do'] = 'a deer, a female deer' >>> d['re'] = 'a drop of golden sunshine' >>> d['mi'] = 'a name I call myself' >>> d['fa'] = 'a long, long way to run' >>> d.keys() ['fa', 'mi', 'do', 're'] >>> d.values() ['a long, long way to run', 'a name I call myself', 'a deer, a female deer', 'a drop of golden sunshine'] >>> -- Michael F. Stemper Exodus 22:21 -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 3.12.1, Windows 11: shebang line #!/usr/bin/env python3 doesn't work any more
On 12/22/23 20:16, rbowman via Python-list wrote: > On Fri, 22 Dec 2023 17:27:58 -0700, Michael Torrie wrote: > >> Using the py launcher as your Windows association with .py and.pyw files >> you can have multiple versions of python installed and everything works >> as it should, according to your shebang, just like on Unix. > > Does that work with virtualenv or conda? I'm slowly getting up to speed > with those. I don't know. I imagine py is aware of venv if you run it from the command line within the activated venv. But I doubt it is if you launch the python script by double-clicking on it from Explorer. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 3.12.1, Windows 11: shebang line #!/usr/bin/env python3 doesn't work any more
On 12/22/23 20:56, Thomas Passin via Python-list wrote: > It's just better not to make assumptions about which version of Python > will be running. Just specify it yourself when you can, and then you can > be sure. Precisely, which is why the shebang is so useful, even on Windows with py launcher. For example, set the shebang to: #!/usr/bin/python3.6 And py launcher will always try to run it with Python 3.6. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 3.12.1, Windows 11: shebang line #!/usr/bin/env python3 doesn't work any more
On 12/22/23 07:02, Thomas Passin via Python-list wrote: > On my Windows 10 machine, Python scripts run without a shebang line. > Perhaps Windows 11 has added the ability to use one, but then you would > need to use the actual location of your Python executable. Yes if you associate .py or .pyw with python.exe (or pythonw.exe), then things work as you describe. However it's no longer recommended to do that. Instead---and I think this is the default now when you install python---you should associate both .py and .pyw files with the py launcher (py.exe) and it will examine the shebang line of the script and determine which version of python to run. As I said this should work regardless of the path listed in the shebang. Note that the shebang is meaningless to Windows itself, and Windows Explorer. It is only meaningful to the py launcher. So it's customary to just use a unix-style shebang in your python scripts. So either #!/usr/bin/python3 or #!/usr/bin/env python3 as you would in unix. Using the py launcher as your Windows association with .py and.pyw files you can have multiple versions of python installed and everything works as it should, according to your shebang, just like on Unix. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 3.12.1, Windows 11: shebang line #!/usr/bin/env python3 doesn't work any more
On 12/22/23 11:42, Thomas Passin via Python-list wrote: > There is some important context that is missing here. Python on Windows > does not normally install to that location. That is not even a Windows > path, neither by directory name nor by path separators. No, that's just the way the py launcher on Windows has always worked in the past. This way you can take a script from a nix system and drop it in Windows and it has half a chance of running through the launcher, from Windows explorer, or by running py myscript.py at the command propmpt. The Py launcher essentially ignores (or used to ignore) the path in the shebang and focuses on what version of Python it should fire up. -- https://mail.python.org/mailman/listinfo/python-list
Re: RE: Newline (NuBe Question)
On 24/11/2023 21.45, avi.e.gr...@gmail.com wrote: Grizz[l]y, I think the point is not about a sorted list or sorting in general It is about reasons why maintaining a data structure such as a list in a program can be useful beyond printing things once. There are many possible examples such as having a list of lists containing a record where the third item is a GPA for the student and writing a little list comprehension that selects a smaller list containing only students who are Magna Cum Laude or Summa Cum Laude. studs = [ ["Peter", 82, 3.53], ["Paul", 77, 2.83], ["Mary", 103, 3.82] ] I've seen Mary, and she didn't look like a "stud" to me. Of course, for serious work, some might suggest avoiding constructs like a list of lists and switch to using modules and data structures [...] Those who would recommend that approach do not appear to include Mr. Rossum, who said: Avoid overengineering data structures. Tuples are better than objects (try namedtuple too though). Prefer simple fields over getter/setter functions... Built-in datatypes are your friends. Use more numbers, strings, tuples, lists, sets, dicts. Also check out the collections library, eps. deque.[1] I was nodding along with the people saying "list of lists" until I reread this quote. A list of tuples seems most appropriate to me. [1] <https://gist.github.com/hemanth/3715502>, as quoted by Bill Lubanovic in _Introducing Python_ -- Michael F. Stemper This sentence no verb. -- https://mail.python.org/mailman/listinfo/python-list
Re: xor operator
>AFAICT, it's not nothing at all to do with 'xor' in any sense. As much as I agree that the function needn't be in the base of python, I can easily follow the OP's logic on the function name. With two items in the iterator, it is a standard binary exclusive or. It is true if one of but not both of the items is true. OP then generalized this to is exclusively one of any number of these options are true, which is different than the repetitious binary operator application, certainly, but is still very much an 'or' that excludes the case of other options being true. OP then generalized this from exclusively one truth in the set of variables to some other specific number of truths that need be. I expect the OP could then generalize this to a range of truthiness for the set with a minimum and maximum allowable truthiness, and probably a key function to extract some facet from the iterable for consideration. I understand why you find it disagreeable, but I cannot find it necessarily illogical, and it is easy, I think, to see what it has to do with xor. A better name for OP's generalization, however, could likely be 'aut', from the Latin exclusive or. On Mon, Nov 13, 2023 at 7:20 PM Grant Edwards via Python-list < python-list@python.org> wrote: > On 2023-11-13, Dom Grigonis via Python-list > wrote: > > > I am not asking. Just inquiring if the function that I described > > could be useful for more people. > > > > Which is: a function with API that of `all` and `any` and returns > > `True` if specified number of elements is True. > > I've got no objection to a function that counts True objects returned > by an iterator and returns True IFF count == . > > I've got no objection to a function that counts True objects returned > by an iterator and returns True IFF count >= . > > I've got no objection if that latter function short-circuits by > stopping the iteration and returning True when it has seen true > objects. > > I don't recall ever having a need for such a function in the 25 years > I've been writing Python code, but I'm not going to claim that nobody > else has a need for such a function. > > I would object to that being called 'xor', and would fight to the > death (yes, I'm being hyperbolic) the addition of a builtin with the > name 'xor' that does what you describe. > > > It is not a generalised `xor` in strict programatic space. > > AFAICT, it's not nothing at all to do with 'xor' in any sense. > > > I.e. NOT bitwise xor applied to many bits. This is more in line > > with cases that `any` and `all` builtins are used. > > Except the 'any' and 'all' builtins are _exactly_ the same as bitwise > or and and applided to many bits. To do something "in line" with that > using the 'xor' operator would return True for an odd number of True > values and False for an even Number of True values. > > -- > Grant > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: xor operator
I don't think an exclusive-or/truthy-entries-count-checker needs to be a builtin by any stretch. >>> def xor( iterable, n = 1 ): ... return sum( map( bool, iterable ) ) == n Or if you insist on short circuiting: >>> def xor_ss( iterable, n = 1 ): ... for intermediate in itertools.accumulate( iterable, (lambda x, y: x + bool(y)), initial = 0 ): ... if intermediate > n: ... return False ... return intermediate == n On Mon, Nov 13, 2023 at 4:05 PM Barry via Python-list < python-list@python.org> wrote: > > > > On 13 Nov 2023, at 17:48, Dom Grigonis wrote: > > > > Short circuiting happens, when: > > xor([True, True, False, False], n=1) > > At index 1 it is clear that the answer is false. > > Can you share an example with 4 values that is true? > And explain why it is xor. > > Barry > > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: on a tail-recursive square-and-multiply
On 11/7/23 18:26, Julieta Shem via Python-list wrote: > For the first time I'm trying to write a tail-recursive > square-and-multiply and, even though it /seems/ to work, I'm not happy > with what I wrote and I don't seem to understand it so well. > > --8<---cut here---start->8--- > def sam(b, e, m, acc = 1): > if e == 0: > return acc > if is_even(e): > return sam(remainder(b * b, m), e//2, m, acc) > else: > return sam(b, e - 1, m, remainder(b * acc, m)) > --8<---cut here---end--->8--- I don't see any definition of "remainder()" When you post to the list, please provide short but complete code, including a demonstration of using the code provided. That will help others understand what you are trying to do, and perhaps comment on your concerns. > You see, I tried to use an accumulator, but I'm only accumulating when > the exponent is odd. When it's even, I feel I'm forced to change the > base into b * b mod m and leave the accumulator alone. This feels so > unnatural to me. I feel I broke some symmetry there. I'm having to > think of two cases --- when I change the accumulator and when I change > the base. That seems too much for my small head. Can you help? I don't really understand the code either, so I cannot help much. -- https://mail.python.org/mailman/listinfo/python-list
Re: Checking if email is valid
On 11/4/23 02:51, Simon Connah via Python-list wrote: > Wow. I'm half tempted to make a weird email address to see how many websites > get it wrong. > > Thank you for the link. Nearly all websites seem to reject simple correct email addresses such as myemail+sometext@example.domain. I like to use this kind of email address when I can to help me filter out the inevitable spam that comes from companies selling off my address even after claiming they won't. So I suspect that nearly all websites are going to reject other kinds of weird email addresses you can create that are actually correct. -- https://mail.python.org/mailman/listinfo/python-list
Re: Checking if email is valid
On 11/2/23 00:42, Simon Connah via Python-list wrote: > Basically I'm writing unit tests and one of them passess in a string > with an invalid email address. I need to be able to check the string > to see if it is a valid email so that the unit test passess. If you truly have managed to code an RFC-compliant verifier, I commend you. > Valid as in conforms to the standard. Although having looked at the > standard that might be more difficult than originally planned. You'll have to read the relevant RFCs. Lots of corner cases! From what I can see virtually no one on the internet gets it right, judging by the number of times I have valid email addresses flagged as not valid by poor algorithms. -- https://mail.python.org/mailman/listinfo/python-list
Re: Checking if email is valid
On 11/1/23 04:09, Simon Connah via Python-list wrote: > Hi, > > I'm building a simple project using smtplib and have a question. I've been > doing unit testing but I'm not sure how to check if an email message is > valid. Using regex sounds like a bad idea to me and the other options I found > required paying for third party services. > > Could someone push me in the right direction please? I just want to find out > if a string is a valid email address. If I had a nickle for every time a web site claimed my email address wasn't valid I'd be a rich person. Seems like most attempts at solving this little problem fall short! -- https://mail.python.org/mailman/listinfo/python-list
Re: Question(s)
On 10/26/23 10:41, Michael Torrie wrote: > By the way you definitely can step > through MicroPython code one line at a time with a remote debugger, say > with Visual Studio Code. I meant to edit that bit out. After doing a bit more research, it appears remote debugging with MicroPython may not be possible or easy. But the MicroPython lists and forums will know more about that than I do. But there are some nice IDEs for developing code in MicroPython and deploying it to devices. -- https://mail.python.org/mailman/listinfo/python-list
Re: Question(s)
On 10/26/23 06:34, o1bigtenor wrote: > Interesting - - - - ". . . see if it runs." - - - that's the issue! > When the code is accessing sensors there isn't an easy way to > check that the code is working until one has done the all of the > physical construction. If I'm trying to control a pulsation system > using square waves with distinct needs for timing etc I hadn't > seen any way of 'stepping through the code' (phrase you use later). Having dabbled in embedded electronics, all I can say is you will just have to build it and try to get it working. Failure is always an option. If I understand you correctly, this is for a hobby interest, so go at it and have fun. Stepping through code is a basic part of debugging in any language. They all have tools for it. Google for python debugging. "distinct needs for timing?" Did you forget to tell us you need to use MicroPython? Certainly MicroPython running on a microcontroller with help from hardware timers certainly can do it, but this mailing list is not the place to ask about it. Instead you'll have to visit a forum on MicroPython or CircuitPython. By the way you definitely can step through MicroPython code one line at a time with a remote debugger, say with Visual Studio Code. > I have been following this list for some time. Don't believe that I've ever > seen anything where anyone was referred to 'Idle'. In reading other user > group threads I have heard lots about java and its ide - - - don't remember, > again, any re: an ide for python. Idle has been mentioned on several occasions, but probably more on the python-tutor list. I find it hard to believe that searching for Python IDEs really came up blank. There are even IDEs for MicroPython and embedded devices. I found a nice list with a quick search. > Even in maker threads - - - say for arduino - - its 'use this cut and > paste method > of programming' with no mention of any kind of ide when it was microPython - - > although being a subset of python it Idle may not work with it. You keep dropping little details that, had you included them in the first post, would have helped avoid a lot of answers that ultimately aren't going to be useful to you. Are you working MicroPython or with regular Python on a PC? That makes a big difference in where you go to get help and what kind of help we can provide here. > Oh well - - - I am working on things! That is good. I wish you success. -- https://mail.python.org/mailman/listinfo/python-list
Re: Question(s)
On 25/10/2023 05.45, o1bigtenor wrote: On Tue, Oct 24, 2023 at 8:35 PM Chris Angelico via Python-list wrote: 3. Catch the failure before you commit and push. Unit tests are great for this. Where might I find such please. You don't "find" unit tests; you write them. A unit test tests a specific function or program. Ideally, you write each unit test *before* you write the function that it tests. For instance, suppose that you were writing a function to calculate the distance between two points. We know the following things about distance: 1. The distance from a point to itself is zero. 2. The distance between two distinct points is positive. 3. The distance from A to B is equal to the distance from B to A. 4. The distance from A to B plus the distance from B to C is at least as large as the distance from A to C. You would write unit tests that generate random points and apply your distance function to them, checking that each of these conditions is satisfied. You'd also write a few tests of hard-coded points,such as: - Distance from (0,0) to (0,y) is y - Distance from (0,0) to (x,0) is x - Distance from (0,0) to (3,4) is 5 - Distance from (0,0) to (12,5) is 13 The python ecosystem provides many tools to simplify writing and running unit tests. Somebody has already mentioned "unittest". I use this one all of the time. There are also "doctest", "nose", "tox", and "py.test" (none of which I've used). -- Michael F. Stemper Life's too important to take seriously. -- https://mail.python.org/mailman/listinfo/python-list
Re: Question(s)
On 10/25/23 05:51, o1bigtenor via Python-list wrote: > Looks like I have another area to investigate. (grin!) > Any suggestions? Seems to me you're trying to run before you have learned to walk. Slow down, go to the beginning and just learn python, write some code, see if it runs. Go through the tutorial at https://docs.python.org/3/tutorial/index.html Your first and most basic tool is the python interpreter. It will tell you when you try to run your code if you have syntax errors. It's true that some errors the linters will catch won't show up as syntax errors, but cross the bridge when you get to it. Once you have a basic grasp of Python syntax, you can begin using some of the tools Python has for organizing code: Functions and modules (eventually packages). Eventually when your logic is placed neatly into functions, you can then write other python programs that import those functions and feed different parameters to them and test that the output is what you expect. That is known as a test. Nothing wrong with geany as an editor. However, you might find the Python Idle IDE useful (it usually installs with Python), as it lets you work more interactively with your code, inspecting and interacting with live python objects in memory. It also integrates debugging functionality to let you step through your code one line at a time and watch variables and how they change. When you encounter isses with your code (syntax or logical) that you can't solve, you can come to the list, show your code and the full output of the interpreter that shows the complete error message and back trace and I think you'll get a lot of helpful responses. -- https://mail.python.org/mailman/listinfo/python-list
Re: Question(s)
On 24/10/2023 18.15, o1bigtenor wrote: What is interesting about this is the absolute certainty that it is impossible to program so that that program is provably correct. Not entirely true. If I was to write a program to calculate Fibonacci numbers, or echo back user input, that program could be proven correct. But, there is a huge set of programs for which it is not possible to prove correctness. In fact, there is a huge (countably infinite) set of programs for which it is not even possible to prove that the program will halt. Somebody already pointed you at a page discussing "The Halting Problem". You really should read up on this. Somehow - - - well - - to me that sounds that programming is illogical. If I set up a set of mathematical problems (linked) I can prove that the logic structure of my answer is correct. Exactly the same situation. There are many (again, countably infinite) mathematical statements where it is not possible to prove that the statement is either true or false. I want to be clear that this is not the same as "we haven't figured out how to do it yet." It is a case of "it is mathematically possible to show that we can't either prove or disprove statement ." Look up Kurt Gödel's work on mathematical incompleteness, and some of the statements that fall into this category, such as the Continuum Hypothesis or the Parallel Postulate. As I said at the beginning, there are a lot of programs that can be proven correct or incorrect. But, there are a lot more that cannot. -- Michael F. Stemper Outside of a dog, a book is man's best friend. Inside of a dog, it's too dark to read. -- https://mail.python.org/mailman/listinfo/python-list
Re: Question(s)
On 24/10/2023 17.50, Thomas Passin wrote: The programming team for the Apollo moon mission developed a system which,> if you would write your requirements in a certain way, could generate correct C code for them. Since the last Apollo mission was in 1972, when C was first being developed, I find this hard to believe. -- Michael F. Stemper Outside of a dog, a book is man's best friend. Inside of a dog, it's too dark to read. -- https://mail.python.org/mailman/listinfo/python-list
Re: Where I do ask for a new feature
On 10/19/23 19:32, Bongo Ferno via Python-list wrote: > >> You can actually just do that with simple assignment! >> >> short_view = my_object.stuff.long_stuff.sub_object >> print(short_view.some_method()) > > but then have to delete the variable manually > > del short_view Why? It's just a name in the namespace that you can bind to a function object. You can ignore it or rebind it later to something else. There's no need to del it, although you can. I'm not sure why you want to del it. It's not like a memory leak or something like that. I suspect we might also have a misunderstanding of what python variables are and how they work, which is why I did not use the word, "reassign" but rather "bind" or "rebind." -- https://mail.python.org/mailman/listinfo/python-list
Re: error of opening Python
On 26/09/2023 07.27, Abdelkhelk ashref salay eabakh wrote: Dear Python team, This is my not first time using Python, I tried to launch Python and it showed "Python 3.11.3 (tags/v3.11.3:f3909b8, Apr 4 2023, 23:49:59) [MSC v.1934 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information." I don't know what this meant and how to fix this. Could you please help me? What error did you encounter? Aside from the lack of line breaks, it looks quite similar to what I get when I start up python: Python 3.6.9 (default, Mar 10 2023, 16:46:00) [GCC 8.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> Didn't you get the ">>> " prompt? Once you get it, it shows that the Read, Evaluate, Print Loop (REPL) is ready for you to type some python statements. For instance: >>> x = 2**3 >>> print(x) 8 >>> -- Michael F. Stemper Outside of a dog, a book is man's best friend. Inside of a dog, it's too dark to read. -- https://mail.python.org/mailman/listinfo/python-list
Re: Where is the error?
When i try to open a python script it either says theres no ctk module or no pip On Sun, Aug 6, 2023, 3:51 PM Peter J. Holzer via Python-list < python-list@python.org> wrote: > Mostly, error messages got a lot better in Python 3.10, but this one had > me scratching my head for a few minutes. > > Consider this useless and faulty script: > > > r = { > "x": (1 + 2 + 3) > "y": (4 + 5 + 6) > "z": (7 + 8 + 9) > } > > > Python 3.9 (and earlier) reports: > > > File "/home/hjp/tmp/foo", line 3 > "y": (4 + 5 + 6) > ^ > SyntaxError: invalid syntax > > > This isn't great, but experience with lots of programming languages > tells me that an error is noticed where or after it actually occurs, so > it's easy to see that there is a comma missing just before the "y". > > Python 3.10 and 3.11 report: > > > File "/home/hjp/tmp/foo", line 2 > "x": (1 + 2 + 3) > ^^ > SyntaxError: invalid syntax. Perhaps you forgot a comma? > > > The error message is now a lot better, of course, but the fact that it > points at the expression *before* the error completely threw me. The > underlined expression is clearly not missing a comma, nor is there an > error before that. My real program was a bit longer of course, so I > checked the lines before that to see if I forgot to close any > parentheses. Took me some time to notice the missing comma *after* the > underlined expression. > > Is this "clairvoyant" behaviour a side-effect of the new parser or was > that a deliberate decision? > > hp > > -- >_ | Peter J. Holzer| Story must make more sense than reality. > |_|_) || > | | | h...@hjp.at |-- Charles Stross, "Creative writing > __/ | http://www.hjp.at/ | challenge!" > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: Is npyscreen still alive?
On 4/24/23 08:04, Grant Edwards wrote: > Is putty running on Windows a "modern terminal emulator" in this > context? After observing some of the local IT types work, I suspect > that will be a common use-case for the app I'm working on. Yes, Putty qualifies as a "modern terminal emulator." It supports UTF-8 and unicode fonts. And the mouse events work as well. The only catch is the default font is courier new which seems to not have some of the line drawing characters in it. But if I change to something like Cascadia Code it looks very good. -- https://mail.python.org/mailman/listinfo/python-list
Re: Is npyscreen still alive?
On 4/21/23 15:57, Barry wrote: > Maybe this, recently lwn.net article, https://textual.textualize.io/ > I was planning to check it out. Textual definitely looks slick and modern. And with a modern terminal emulator it works quite well and is responsive. I'd definitely consider it for a TUI. But on the Linux console, or on an older terminal, not so much. Textual's really designed for smallish unicode fonts in a windowed environment, not any kind of real, old-school text mode. Just something to keep in mind. 99% of terminal users are using a modern terminal emulator these days, with full color and unicode, which is the target of textual. Curses-based programs don't look great on anything, but they do look consistent on more primitive terminals. -- https://mail.python.org/mailman/listinfo/python-list
Re: Christoph Gohlke and compiled packages
On 4/11/23 11:48, Oscar Benjamin wrote: > You can hardly blame a lot of people for doing this. A seb search for > "download python" gives this as the first hit: > https://www.python.org/downloads/ Very true, but it points to the difference between how people install Python on Windows compared to Linux, which is what Chris was probably referring to when he said Windows was a nightmare to support. Usually when a full version bump of python hits my distros, all the other packages that need to be rebuilt get rebuilt and install along with the new python package. Or often the older version of Python is patched and continued to be used, not requiring new packages. So most linux users never have to go searching for an appropriate version of Numpy, etc. Whereas Windows only recently has gained a package manager, and as near as I can tell is not widely used outside of serious developers who use Visual Studio. And to make matters worse, MS offers Python in the Windows Store, which is its own thing and causes much confusion with users who often end up with more than one version of Python installed. And nevermind the MingW/MSVC split that affects the distribution of pre-built binaries, although MS's move to the universal C runtime dll system might fix this finally (unless C++ is involved). These are all extremely hard problems to solve, and every solution has its drawbacks, including the packaging systems used by Linux. Especially by an open source organization like the PSF. -- https://mail.python.org/mailman/listinfo/python-list
Re: Windows Gui Frontend
On 2023-04-02 9:09 a.m., Dietmar Schwertberger wrote: >> I've tried wxGlade but never could get into it, or wxWidgets in general. > > Which version? Up to 0.7.2 I agree. Been a long time. I was initially turned off by the event handling system of wx compared to the signals and slots of Gtk and Qt. > For me QtQuick and QML are a step backwards by some ten years when > it comes to development speed. > It's as much 'fun' as doing GUIs with HTML and JavaScript. > Unfortunately, The Qt Company refused to provide an API for QtQuick to > be able to use it without QML. > Anyway, desktop development has long moved out of their focus > (around 15 years ago when Nokia acquired Trolltech). It's not where > their commercial customers are. There are a number of desktop apps built in QtQuick. KDE is transitioning to QtQuick and it's been alright, not without some consistency issues. The Cura slicer is another example of a complete desktop app written in QtQuick which looks and feels quite nicely on all platforms. For me, more and more I need to be able to run on mobile as well as desktop. Qt, GTK, or wx are just not good fits when you need that kind of portability. But traditional Qt will be with us or decades yet. -- https://mail.python.org/mailman/listinfo/python-list
Re: Windows Gui Frontend
On 2023-04-02 9:09 a.m., Dietmar Schwertberger wrote: > That's what I hated with Qt Designer: it does not output Python code > but a .ui file. > This was the point where I could not recommend it to anyone. Well the thing is you don't need to generate Python code at all. Qt provides a UI loader class that loads the UI file at run time, builds the objects in memory, and connects all your signals for you. So much nicer than code generation. -- https://mail.python.org/mailman/listinfo/python-list
Re: Windows Gui Frontend
On 4/1/23 09:37, Eryk Sun wrote: > Here are a few of the GUI toolkit libraries in common use: > > * tkinter (Tk) > * PyQt (Qt) > * PySide (Qt) > * wxPython (wxWidgets) > * PyGObject (GTK) > > tkinter is included in Python's standard library. Another good one is Kivy. Especially if you ever want to target mobile in the future. https://kivy.org/ -- https://mail.python.org/mailman/listinfo/python-list
Re: Windows Gui Frontend
On 4/2/23 05:09, Dietmar Schwertberger wrote: > I also did evaluate all the GUI builder from time to time between > 2000 and 2016 to find one that I could recommend to colleagues, > but could not find one. Then I started contributing to wxGlade > and I can say that since a few years it's as easy again to > build GUIs as it was with VB6. > > I don't want to go back to coding GUIs manually. For most use > cases it's a waste of time and often it does not result in the > best GUI as it's not so easy to try out and rearrange elements. But any modern GUI toolkit has sizers and layout managers. If you're manually placing elements you cannot deal with HiDPI or changing window sizes. Rearranging happens automatically when using sizers and layout managers. That said, the future of GUIs is declarative, using XAML or some other domain-specific language like QML. Examples of this include QtQuick (the long-term direction Qt is heading), and the various dot Net GUI toolkits now popular including MS' own MAUI, WPF, Avalonia. GUI designer tools (Qt Creator, Visual Studio) can be used to assist and help layout the skeleton, but ultimately the GUI is defined by code. And it works very well, is adaptive, and can automatically size and rearrange. If you want portability to mobile devices, this is where it's at. I've tried wxGlade but never could get into it, or wxWidgets in general. I used to use GTK a lot and did use Glade back then, and dynamically loaded the UI definition files at run time. Lately used more Qt with QtDesigner, and even extended Designer to support using some custom widgets I made. but the future of Qt is clearly QtQuick, so I've been learning that. Has its warts, but in general I like the declarative paradigm. It's a learning curve. Overall it's fairly powerful, flexible and portable. I have used the designer in Qt Creator a bit, but it's often faster and just as intuitive to write it in QML, since you're going to be dropping into QML frequently anyway to set properties (not unlike having to set widget properties in Qt Designer. So I guess it's 6s using the graphical designer vs straight Qt. -- https://mail.python.org/mailman/listinfo/python-list
Re: Windows Gui Frontend
On 4/1/23 15:33, Thomas Passin wrote: > OTOH, Qt isn't free for commercial use and the OP seems to be > speculating on coming up with a product to sell at some point. Careful. That's not actually true, even though the marketing team at Qt lets people believe it is. Qt is licensed under the LGPL, which you can definitely use in a proprietary, close-source app, provided you use the dynamically-linked version (which PySide does of course) and do not modify it. Qt's commerical licensing is very hostile to small companies, I can say that much. It's too bad really. But the LGPL will work for most companies, except for those that might wish to use the embedded version, such as in cars where being able to abide by the terms of the LGPL becomes difficult. -- https://mail.python.org/mailman/listinfo/python-list
Re: Rob Cliffe should stop sending me rude email messages.
On 2/27/23 09:17, Grant Edwards wrote: > On 2023-02-27, Michael Torrie wrote: > >> I've been putting off sending this message for days, but the list noise >> level is now to the point that it has to be said. > > Ah, I've finially realized why some of those threads have seemed so > disjointed to me. Years ago, I plonked all posts which are (like Hen > Hanna's) submitted via Googole Groups. > > I highly recommend it. > > FWIW, here's the "score" rule for doing that with srln: > > Score:: =- > Message-ID: .*googlegroups.com Thanks for the tip and reminder. I'll add that to my gmail filter. -- https://mail.python.org/mailman/listinfo/python-list
Re: Rob Cliffe should stop sending me rude email messages.
I've been putting off sending this message for days, but the list noise level is now to the point that it has to be said. Often it is better to contact someone directly and privately rather than publicly embarrass them by calling them out. You've made it clear, however, that publicly calling you out is necessary. No doubt you will think my post rude as well, even though the tone is moderate and deliberate. Sometimes things need to said and others need to be asked to make changes. That's just part of communication in real, grown-up life. Everyone that's responded to you has patiently attempted to answer your questions and engage with you despite your unorthodox and very difficult communications style. I can assure you that not one person who's replied to you has been rude or insulting, yet I cannot say the same about your own disparaging comments in reply. The only ad homimems I've seen have come from you. We are frustrated and exasperated with your unwillingness to read, learn, and understand, yes, definitely! Although your posts are quite a bit less frustrating than those trying to turn Python into Java. We can probably handle trying to turn Python into LISP! :) Do you understand why your posts have been causing frustration? This is an existing community that you've chosen to join. Many of the people you've insulted here, including dn have been participating and helpfully contributing to this list for many years. Please stop posting messages about how you think people have been rude to you. Besides being off-topic they are simply false. -- https://mail.python.org/mailman/listinfo/python-list
Re: Is there a more efficient threading lock?
https://stackoverflow.com/questions/69993959/python-threads-difference-for-3-10-and-others https://github.com/python/cpython/commit/4958f5d69dd2bf86866c43491caf72f774ddec97 it's a quirk of implementation. the scheduler currently only checks if it needs to release the gil after the POP_JUMP_IF_FALSE, POP_JUMP_IF_TRUE, JUMP_ABSOLUTE, CALL_METHOD, CALL_FUNCTION, CALL_FUNCTION_KW, and CALL_FUNCTION_EX opcodes. >>> import code >>> import dis >>> dis.dis( code.update_x_times ) 10 0 LOAD_GLOBAL 0 (range) 2 LOAD_FAST0 (xx) 4 CALL_FUNCTION1 # GIL CAN RELEASE HERE # 6 GET_ITER >>8 FOR_ITER 6 (to 22) 10 STORE_FAST 1 (_) 12 12 LOAD_GLOBAL 1 (vv) 14 LOAD_CONST 1 (1) 16 INPLACE_ADD 18 STORE_GLOBAL 1 (vv) 20 JUMP_ABSOLUTE4 (to 8) # GIL CAN RELEASE HERE (after JUMP_ABSOLUTE points the instruction counter back to FOR_ITER, but before the interpreter actually jumps to FOR_ITER again) # 10 >> 22 LOAD_CONST 0 (None) 24 RETURN_VALUE >>> due to this, this section: 12 12 LOAD_GLOBAL 1 (vv) 14 LOAD_CONST 1 (1) 16 INPLACE_ADD 18 STORE_GLOBAL 1 (vv) is effectively locked/atomic on post-3.10 interpreters, though this is neither portable nor guaranteed to stay that way into the future On Sun, Feb 26, 2023 at 10:19 PM Michael Speer wrote: > I wanted to provide an example that your claimed atomicity is simply > wrong, but I found there is something different in the 3.10+ cpython > implementations. > > I've tested the code at the bottom of this message using a few docker > python images, and it appears there is a difference starting in 3.10.0 > > python3.8 > EXPECTED 256000 > ACTUAL 84533137 > python:3.9 > EXPECTED 256000 > ACTUAL 95311773 > python:3.10 (.8) > EXPECTED 256000 > ACTUAL 256000 > > just to see if there was a specific sub-version of 3.10 that added it > python:3.10.0 > EXPECTED 256000 > ACTUAL 256000 > > nope, from the start of 3.10 this is happening > > the only difference in the bytecode I see is 3.10 adds SETUP_LOOP and > POP_BLOCK around the for loop > > I don't see anything different in the long c code that I would expect > would cause this. > > AFAICT the inplace add is null for longs and so should revert to the > long_add that always creates a new integer in x_add > > another test > python:3.11 > EXPECTED 256000 > ACTUAL 256000 > > I'm not sure where the difference is at the moment. I didn't see anything > in the release notes given a quick glance. > > I do agree that you shouldn't depend on this unless you find a written > guarantee of the behavior, as it is likely an implementation quirk of some > kind > > --[code]-- > > import threading > > UPDATES = 1000 > THREADS = 256 > > vv = 0 > > def update_x_times( xx ): > for _ in range( xx ): > global vv > vv += 1 > > def main(): > tts = [] > for _ in range( THREADS ): > tts.append( threading.Thread( target = update_x_times, args = > (UPDATES,) ) ) > > for tt in tts: > tt.start() > > for tt in tts: > tt.join() > > print( 'EXPECTED', UPDATES * THREADS ) > print( 'ACTUAL ', vv ) > > if __name__ == '__main__': > main() > > On Sun, Feb 26, 2023 at 6:35 PM Jon Ribbens via Python-list < > python-list@python.org> wrote: > >> On 2023-02-26, Barry Scott wrote: >> > On 25/02/2023 23:45, Jon Ribbens via Python-list wrote: >> >> I think it is the case that x += 1 is atomic but foo.x += 1 is not. >> > >> > No that is not true, and has never been true. >> > >> >:>>> def x(a): >> >:...a += 1 >> >:... >> >:>>> >> >:>>> dis.dis(x) >> > 1 0 RESUME 0 >> > >> > 2 2 LOAD_FAST0 (a) >> > 4 LOAD_CONST 1 (1) >> > 6 BINARY_OP 13 (+=) >> > 10 STORE_FAST 0 (a) >> > 12 LOAD_CONST 0 (None) >> > 14 RETURN_VALUE >> >:>>> >> > >> > As you can see there are 4 byte code ops executed. >> > >> > Python's eval loop can switch to another thread between any of them. >> > >> > Its is not true that the GIL provides atomic operations in python. >> >> That's oversimplifying to the point of falsehood (just as the opposite >> would be too). And: see my other reply in this thread just now - if the >> GIL isn't making "x += 1" atomic, something else is. >> -- >> https://mail.python.org/mailman/listinfo/python-list >> > -- https://mail.python.org/mailman/listinfo/python-list
Re: Is there a more efficient threading lock?
I wanted to provide an example that your claimed atomicity is simply wrong, but I found there is something different in the 3.10+ cpython implementations. I've tested the code at the bottom of this message using a few docker python images, and it appears there is a difference starting in 3.10.0 python3.8 EXPECTED 256000 ACTUAL 84533137 python:3.9 EXPECTED 256000 ACTUAL 95311773 python:3.10 (.8) EXPECTED 256000 ACTUAL 256000 just to see if there was a specific sub-version of 3.10 that added it python:3.10.0 EXPECTED 256000 ACTUAL 256000 nope, from the start of 3.10 this is happening the only difference in the bytecode I see is 3.10 adds SETUP_LOOP and POP_BLOCK around the for loop I don't see anything different in the long c code that I would expect would cause this. AFAICT the inplace add is null for longs and so should revert to the long_add that always creates a new integer in x_add another test python:3.11 EXPECTED 256000 ACTUAL 256000 I'm not sure where the difference is at the moment. I didn't see anything in the release notes given a quick glance. I do agree that you shouldn't depend on this unless you find a written guarantee of the behavior, as it is likely an implementation quirk of some kind --[code]-- import threading UPDATES = 1000 THREADS = 256 vv = 0 def update_x_times( xx ): for _ in range( xx ): global vv vv += 1 def main(): tts = [] for _ in range( THREADS ): tts.append( threading.Thread( target = update_x_times, args = (UPDATES,) ) ) for tt in tts: tt.start() for tt in tts: tt.join() print( 'EXPECTED', UPDATES * THREADS ) print( 'ACTUAL ', vv ) if __name__ == '__main__': main() On Sun, Feb 26, 2023 at 6:35 PM Jon Ribbens via Python-list < python-list@python.org> wrote: > On 2023-02-26, Barry Scott wrote: > > On 25/02/2023 23:45, Jon Ribbens via Python-list wrote: > >> I think it is the case that x += 1 is atomic but foo.x += 1 is not. > > > > No that is not true, and has never been true. > > > >:>>> def x(a): > >:...a += 1 > >:... > >:>>> > >:>>> dis.dis(x) > > 1 0 RESUME 0 > > > > 2 2 LOAD_FAST0 (a) > > 4 LOAD_CONST 1 (1) > > 6 BINARY_OP 13 (+=) > > 10 STORE_FAST 0 (a) > > 12 LOAD_CONST 0 (None) > > 14 RETURN_VALUE > >:>>> > > > > As you can see there are 4 byte code ops executed. > > > > Python's eval loop can switch to another thread between any of them. > > > > Its is not true that the GIL provides atomic operations in python. > > That's oversimplifying to the point of falsehood (just as the opposite > would be too). And: see my other reply in this thread just now - if the > GIL isn't making "x += 1" atomic, something else is. > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?
On 2/23/23 01:08, Hen Hanna wrote: > Python VM is seeing an "int" object (123) (and telling me that) ... > so it should be easy to print that "int" object > What does Python VMknow ? and when does it know it ? It knows there is an object and its name and type. It knows this from the first moment you create the object and bind a name to it. > it seems like it is being playful, teasing (or mean),and hiding the > ball from me Sorry you aren't understanding. Whenever you print() out an object, python calls the object's __repr__() method to generate the string to display. For built-in objects this is obviously trivial. But if you were dealing an object of some arbitrary class, there may not be a __repr__() method which would cause an exception, or if the __repr__() method itself raised an exception, you'd lose the original error message and the stack trace would be all messed up and of no value to you. Does that make sense? Remember that Python is a very dynamic language and what might be common sense for a built-in type makes no sense at all for a custom type. Thus there's no consistent way for Python to print out the information you think is so simple. -- https://mail.python.org/mailman/listinfo/python-list
Re: why is a search thru a Tuple slower ? ---- (meaningless indentations)
On 2/20/23 18:01, Hen Hanna wrote: > is Comp.Lang.Python very active Fairly. Apparently the cool kids are using the Python Discourse forum. > why is a linear search thru a Tuple slower > (than thru a (corresponding) List ) ??? I cannot say, unfortunately. Perhaps doing some analysis of the byte code with the disasm module could tell you what the interpreter is doing and why it is slower. Since tuples are read only, I cannot think of any reason to use them for large, generated structures. A list is far better in my opinion. I use tuples mainly for bundling small amounts of information together, such as coordinates, or returning multiple values from a function. > sometimes, i 'd like to put meaningless indentations > like i do (twice) below > ( how can it do this ?) Fortunately you cannot. Such indents are syntax errors. And I have to say it makes your emails very hard to read and understand when you indent your sentences as you do. Looks poetic but hard to read. Also your python example code was not run-able either thanks to those two extra indents which are syntax errors. It's always helpful to post complete and working code examples when asking for help or wanting to get discussion on a piece of code. -- https://mail.python.org/mailman/listinfo/python-list
Re: is [comprehension] the right word???
On 2/20/23 18:06, Hen Hanna wrote: > is [comprehension] the right word??? > > i swear i never heard the word before > getting into Python a few years ago. Seems as though the term was borrowed from formal mathematics set theory. A simple search reveals that the term "list comprehension" predates Python. Back to 1977 to be exact. The term was first coined by Phil Wadler in the late 70s or early 80s. https://en.wikipedia.org/wiki/List_comprehension -- https://mail.python.org/mailman/listinfo/python-list
Re: Tuple Comprehension ???
On 2/20/23 20:36, Hen Hanna wrote: > For a while, i've been curious about a [Tuple Comprehension] I've never heard of a "Tuple comprehension." No such thing exists as far as I know. > So finally i tried it, and the result was a bit surprising... > > > X= [ x for x in range(10) ] > X= ( x for x in range(10) ) > print(X) > a= list(X) > print(a) What was surprising? Don't keep us in suspense! Using square brackets is a list comprehension. Using parenthesis creates a generator expression. It is not a tuple. A generator expression can be perhaps thought of as a lazy list. Instead of computing each member ahead of time, it returns a generator object which, when iterated over, produces the members one at a time. This can be a tremendous optimization in terms of resource usage. See https://docs.python.org/3/reference/expressions.html#generator-expressions. Also you can search google for "generator expression" for other examples. -- https://mail.python.org/mailman/listinfo/python-list
Re: Precision Tail-off?
On 2/17/23 15:03, Grant Edwards wrote: > Every fall, the groups were again full of a new crop of people who had > just discovered all sorts of bugs in the way > implemented floating point, and pointing them to a nicely written > document that explained it never did any good. But to be fair, Goldberg's article is pretty obtuse and formal for most people, even programmers. I don't need lots of formal proofs as he shows. Just a summary is sufficient I'd think. Although I've been programming for many years, I have no idea what he means with most of the notation in that paper. Although I have a vague notion of what's going on, as my last post shows, I don't know any of the right terminology. -- https://mail.python.org/mailman/listinfo/python-list
Re: Precision Tail-off?
On 2/17/23 03:27, Stephen Tucker wrote: > Thanks, one and all, for your reponses. > > This is a hugely controversial claim, I know, but I would consider this > behaviour to be a serious deficiency in the IEEE standard. No matter how you do it, there are always tradeoffs and inaccuracies moving from real numbers in base 10 to base 2. That's just the nature of the math. Any binary floating point representation is going to have problems. There are techniques for mitigating this: https://en.wikipedia.org/wiki/Floating-point_error_mitigation It's interesting to note that the article points out that floating point error was first talked about in the 1930s. So no matter what binary scheme you choose there will be error. That's just the nature of converting a real from one base to another. Also we weren't clear on this, but the IEEE standard is not just implemented in software. It's the way your CPU represents floating point numbers in silicon. And in your GPUs (where speed is preferred to precision). So it's not like Python could just arbitrarily do something different unless you were willing to pay a huge penalty for speed. For example the decimal module which is arbitrary precision, but quite slow. Have you tried the numpy cbrt() function? It is probably going to be more accurate than using power to 0.. > Perhaps this observation should be brought to the attention of the IEEE. I > would like to know their response to it. Rest assured the IEEE committee that formalized the format decades ago knew all about the limitations and trade-offs. Over the years CPUs have increased in capacity and now we can use 128-bit floating point numbers which mitigate some of the accuracy problems by simply having more binary digits. But the fact remains that some rational numbers in decimal are irrational in binary, so arbitrary decimal precision using floating point is not possible. -- https://mail.python.org/mailman/listinfo/python-list
Re: Precision Tail-off?
On 2/14/23 00:09, Stephen Tucker wrote: > I have two questions: > 1. Is there a straightforward explanation for this or is it a bug? To you 1/3 may be an exact fraction, and the definition of raising a number to that power means a cube root which also has an exact answer, but to the computer, 1/3 is 0.333 repeating in decimal, which is some other fraction in binary. And even rational numbers like 0.2, which are precise and exact, are not in binary (0.01010101010101010101). 0.2 is .0011011011011011011 on and on forever. IEEE floating point has very well known limitations. All languages that use IEEE floating point will be subject to these limitations. So it's not a bug in the sense that all languages will exhibit this behavior. > 2. Is the same behaviour exhibited in Python 3.x? Yes. And Java, C++, and any other language that uses IEEE floating point. -- https://mail.python.org/mailman/listinfo/python-list
Re: Am I banned from Discuss forum?
On 2/10/23 14:10, Marco Sulla wrote: > I was banned from the mailing list and Discuss forum for a very long time. > Too much IMHO, but I paid my dues. > > Now this is my state in the forum: > - I never posted something unrespectful in the last months > - I have a limitation of three posts per threads, but only on some threads > - Some random posts of mine are obscured and must be restored manually by > moderators > - I opened a thread about the proposal of a new section called > Brainstorming. It was closed without a reason. > - I can't post links > - Two discussions I posted in section Idea were moved to Help, without a > single line of explanation. > > If I'm not appreciated, I want to be publicly banned with a good reason, or > at least a reason. Your posts are showing up on the mailing list here just it seems. I didn't know there was a Discourse forum. Is it supposed to be sync with the mailing list and USENET? Or is it intended to replace this mailing list? I rarely see Python devs on this list, so maybe they've chosen to hang out exclusively in Discourse, which would be unfortunate. The Discourse format has never appealed to me. It's way to unstructured and gamified. I much prefer the mailing list, but alas it seems like most open source projects are moving to Discourse. -- https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?
On 1/25/23 19:50, Jach Feng wrote: > To me, argparse has been just a tool which I can use in a CLI app. argparse is just a tool for dealing with command-line *flags*, which are common in command-line tools. argparse interprets the command line as a bunch of flags because that's what it's designed to do. I find it baffling that you expect some other behavior from argparse. You don't need or want argparse in this situation. sys.argv has everything you need in it. Use it directly! -- https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?
On 1/23/23 18:58, Jach Feng wrote: > More pathonic, but don't work. The '--' must be at index 1:-) I'm very confused. Why are you even using argparse, since if you put -- at index 1 then argparse wont't do any argument parsing at all. If all you want is the expression on the command line, just access it directly. If it's spread out with spaces, you can do something like this to put it back together: expression = " ".join(sys.argv[1:] Otherwise the standard unix way of doing this is to require the user to either provide the -- himself, or put the expression in quotes so it's one unit. -- https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?
On 1/22/23 11:44, Stefan Ram wrote: > Jach Feng writes: >> e:\Works\Python>py infix2postfix.py "-4^2+5.3*abs(-2-1)/2" > > Well, it's a nice exercise! But I only made it work for the > specific example given. I have not tested whether it always > works. Haha. Yes a nice exercise, but has nothing to do with the original question which is how to convince argparse to accept a string like that without thinking it's a switch. Many unix utilities treat "--" as a special argument that turns off argument parsing for the rest of the command line. Maybe argparse follows this convention too; I don't know. But if it did you'd do: infix2postfix.py -- "-4^2+5.3*abs(-2-1)/2" -- https://mail.python.org/mailman/listinfo/python-list
Re: A natural magnet for the craziest TKinter lovers out there
On 1/18/23 18:01, Dan Kolis wrote: > Hangs after maybe between 4 and 50 screen rewrites. sometimes CTRL C under > Ubuntu starts it up again. Click go rewrites al the fonts the thing can find > in a few windows Repeated. > Not sure what you mean by "screen rewrites." I ran your test program here and it generates 25 windows on my machine, and I can click "run" at least half a dozen times. I tried closing the font windows before clicking run again, and also just leaving the windows up and generating many more windows. 300 windows. No hangs here at all. Fedora 35 with Mate Desktop on X11 with compositing enabled. -- https://mail.python.org/mailman/listinfo/python-list
Re: Improvement to imports, what is a better way ?
On 1/18/23 14:42, Dan Kolis wrote: > >> I don't think you've described this. I don't know what you mean here. > > When I trace it in VSCode the imports seem like they endlessly suspend > scanning and go to other ones over and over. Like "Whats this doing ?" > Nothing to worry about there. Python knows what it's doing! :) Lots of modules import other modules, so there will be a spanning tree of sorts. Each module will only actually be formally imported once. The rest is just setting up name spaces. Yes it all adds to run time latency, but it certainly won't lead to any leaks. Definitely there's no need to import a module's dependencies; it will do that itself. Just import what your own module explicitly needs. -- https://mail.python.org/mailman/listinfo/python-list
Re: What should go to stdout/stderr and why Python logging write everything to stderr?
On 1/3/23 11:45, Keith Thompson wrote: > MRAB writes: > [...] >> The purpose of stderr is to display status messages, logging and error >> messages, even user prompts, and not mess up the program's actual >> output. This is important on a *nix system where you might be piping >> the output of one program into the input of another. > > I would expect user prompts to be written to stdout, or perhaps to some > system-specific stream like the current tty, not to stderr. If a > program has user prompts, it probably doesn't make sense to pipe its > output to the input of another. I can't think of a specific example, but I know I have piped the output of a program while at the same time interacting with a prompt on stderr. A rare thing, though. Maybe some day an interface and shell syntax will be developed to interact with an arbitrary number of standard streams. Current piping syntax really only works well with one stream and even trying to use stderr and stdout with pipes and filters in a shell is awkward. -- https://mail.python.org/mailman/listinfo/python-list
Re: Fwd: About the Python
On 1/1/23 22:27, Ramya M wrote: > This is from JNN College of Engineering, Shimoga. we are facing some > problems while using python. Please can you resolve this issue. Without any further information on your part, we can only guess at what the problems might be. Crystal ball says that Thomas' suggestion will probably solve your problem. But since we don't know what the problems even are, this is just a wild guess. > We are using python 3.11.1 (64 bit) for windows 10. but while installing > the "numpy and matplotlib" packages we are getting errors. In some cases > after installation of the above said packages we are getting errors while > working. You'll need to provide more information than that. What are these errors? Copy and paste the text into your message. Attachments are not allowed on this list. -- https://mail.python.org/mailman/listinfo/python-list
Re: String to Float, without introducing errors
On 19/12/2022 09.14, MRAB wrote: On 2022-12-19 14:10, Peter J. Holzer wrote: On 2022-12-19 09:25:17 +1100, Chris Angelico wrote: On Mon, 19 Dec 2022 at 07:57, Stefan Ram wrote: > G = Decimal( 6.6743015E-11 ) > r = Decimal( 6.371E6 ) > M = Decimal( 5.9722E24 ) What's the point of using Decimal if you start with nothing more than float accuracy? Right. He also interpreted the notation "6.67430(15)E-11" wrong. The digits in parentheses represent the uncertainty in the same number of last digits. So "6.67430(15)E-11" means "something between 6.67430E-11 - 0.00015E-11 and 6.67430E-11 + 0.00015E-11". The r value has only a precision of 1 km and I'm not sure how accurate the mass is. Let's just assume (for the sake of the argument) that these are actually accurate in all given digits. ntal misunderstanding of the numbers they are working with. To be fair, I don't think I've never seen that notation either! I've only ever seen the form 6.67430E-11 ± 0.00015E-11, which is much clearer. See, for instance: <https://www.physics.nist.gov/cgi-bin/cuu/Value?bg> In particular, the "concise form". For more detail, see: <https://en.wikipedia.org/wiki/Uncertainty#Measurements> -- Michael F. Stemper Isaiah 58:6-7 -- https://mail.python.org/mailman/listinfo/python-list
Re: Subject: problem activating python
On 12/17/22 15:45, Anne wrote: >I tried several times to install and use python for youtube views with Tor >using Youtube tutorials but I keep getting error after error. Please help >me. >regards Dimpho Given the lack of any information in your post, I can only assume you're trying to get Python installed on Windows. Please read this page and post here if you have any questions: https://docs.python.org/3/using/windows.html -- https://mail.python.org/mailman/listinfo/python-list
Re: Top level of a recursive function
On 13/12/2022 09.03, Stefan Ram wrote: "Michael F. Stemper" writes: def fred(cf,toplevel=True): x = cf[0] if len(cf)>1: if toplevel: return x + fred(cf[1:],False) else: return "(" + x + fred(cf[1:],False) + ")" else: if toplevel: return x else: return "(" + x + ")" def rest( s ): return "(" + s[ 0 ] +( rest( s[1:] ) if len( s )> 1 else '' )+ ')' def nest( s ): return( s[ 0 ] if s else '' )+( rest( s[1:] )if len( s )> 1 else '' ) Hey, that's slick! And if I define rest within nest, it's not going to be externally accessible. Thanks -- Michael F. Stemper No animals were harmed in the composition of this message. -- https://mail.python.org/mailman/listinfo/python-list
Top level of a recursive function
It's easy enough -- in fact necessary -- to handle the bottom level of a function differently than the levels above it. What about the case where you want to handle something differently in the top level than in lower levels? Is there any way to tell from within a function that it wasn't invoked by itself? I've come up with a hack to support different processing, by use of an extra argument, as shown in this simplified example: def fred(cf,toplevel=True): x = cf[0] if len(cf)>1: if toplevel: return x + fred(cf[1:],False) else: return "(" + x + fred(cf[1:],False) + ")" else: if toplevel: return x else: return "(" + x + ")" Aside from being ugly, this lets the caller diddle with "toplevel", which shouldn't really be externally modifiable. Are there better ways to do this? -- Michael F. Stemper I refuse to believe that a corporation is a person until Texas executes one. -- https://mail.python.org/mailman/listinfo/python-list
Re: Passing information between modules
On 18/11/2022 04.53, Stefan Ram wrote: Can I use "sys.argv" to pass information between modules as follows? in module A: import sys sys.argv.append( "Hi there!" ) in module B: import sys message = sys.argv[ -1 ] I just tried and it appears that one can append to sys.argv. However, it seems like an incredibly bad idea. -- Michael F. Stemper The name of the story is "A Sound of Thunder". It was written by Ray Bradbury. You're welcome. -- https://mail.python.org/mailman/listinfo/python-list
Re: In code, list.clear doesn't throw error - it's just ignored
Python doesn't care what an expression returns. You've written an expression that returns the value of the 'clear' function that is bound to that particular list. The interpreter doesn't know or care if accessing that 'clear' attribute on the class returns a function or for some reason triggers a bunch of side effects that the author decided they wanted to use __getattr__ to trigger. 'list.clear' might be a perfectly reasonable expression in some library. I'd rather it not be, but hey, there are millions of python programmers making all kinds of code out there arbitrary expressions can have arbitrary effects. just because a value isn't assigned, returned or used as an argument to a function doesn't mean it isn't doing anything. you might then want python to inspect the result of the function, but how can python know if the author isn't purposely ignoring the return value of the expression? people can call functions that return values for only their side effects. if you can't tell by the form of the expression or the value it returns, what is the linter supposed to look for? what is the interpreter supposed to look for? if you want to avoid accidentally failing to clear a list during a function, you should write tests that check that various inputs to the function produce the expected outputs. 'unit tests' are a good place to make sure that code is acting as you want it to for one-off scripts, you should always make the thing dry-run or convert from an input to an output (rather than in-place) so you can rerun them a few times and make sure they're doing what you want. sometimes making sure things are right is just on you. there will always be the occasional silly error in a script that is hard to see until you step away for a moment. stepping away and coming back is a pretty good thing to do if you're stuck on something that feels impossible. On Sun, Nov 13, 2022 at 10:33 PM DFS wrote: > On 11/13/2022 9:11 PM, Chris Angelico wrote: > > On Mon, 14 Nov 2022 at 11:53, DFS wrote: > >> > >> On 11/13/2022 5:20 PM, Jon Ribbens wrote: > >>> On 2022-11-13, DFS wrote: > In code, list.clear is just ignored. > At the terminal, list.clear shows > > > > in code: > x = [1,2,3] > x.clear > print(len(x)) > 3 > > at terminal: > x = [1,2,3] > x.clear > > print(len(x)) > 3 > > > Caused me an hour of frustration before I noticed list.clear() was > what > I needed. > > x = [1,2,3] > x.clear() > print(len(x)) > 0 > >>> > >>> If you want to catch this sort of mistake automatically then you need > >>> a linter such as pylint: > >>> > >>> $ cat test.py > >>> """Create an array and print its length""" > >>> > >>> array = [1, 2, 3] > >>> array.clear > >>> print(len(array)) > >>> $ pylint -s n test.py > >>> * Module test > >>> test.py:4:0: W0104: Statement seems to have no effect > (pointless-statement) > >> > >> > >> Thanks, I should use linters more often. > >> > >> But why is it allowed in the first place? > >> > >> I stared at list.clear and surrounding code a dozen times and said > >> "Looks right! Why isn't it clearing the list?!?!" > >> > >> 2 parens later and I'm golden! > >> > > > > No part of it is invalid, so nothing causes a problem. For instance, > > you can write this: > > > If it wastes time like that it's invalid. > > This is an easy check for the interpreter to make. > > If I submit a suggestion to python-list@python.org will it just show up > here? Or do the actual Python devs intercept it? > > > > > > > 1 > > > > And you can write this: > > > 1 + 2 > > > > And you can write this: > > > print(1 + 2) > > > > But only one of those is useful in a script. Should the other two be > > errors? No. But linters WILL usually catch them, so if you have a good > > linter (especially built into your editor), you can notice these > > things. > > > ran pylint against it and got 0.0/10. > > > --disable= > invalid-name > multiple-statements > bad-indentation > line-too-long > trailing-whitespace > missing-module-docstring > missing-function-docstring > too-many-lines > fixme > > > and got 8.9/10. > > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: Any PyQt developers here?
On 10/28/22 21:31, DFS wrote: > I found one person that said they did it but their syntax didn't work. > But it doesn't throw an error either. > > model.setData(model.index(tblRow, col), font, Qt.FontRole) I wouldn't expect that to work but it's understandable why it didn't throw an error. setData() is used to edit the contents of the model at the provided index. Remember a model can store anything. All this does is replace whatever was at that index with a Font object instance. I'm puzzled why you keep trying to mess with the model when it's the view that does the actual font setting. Remember that a single model can be used with more than one view at the same time, each view implementing its own style. Thus a model has no information like fonts in it, nor should it, other than perhaps HTML text markup that the view will render. Did you consult the folk on the PyQt mailing list? Or even the main Qt lists? This isn't language-specific stuff you're asking about. -- https://mail.python.org/mailman/listinfo/python-list
Re: Quick question about CPython interpreter
On 10/14/22 16:25, DFS wrote: > - > this does a str() conversion in the loop > - > for i in range(cells.count()): >if text == str(ID): > break > > > - > this does one str() conversion before the loop > - > strID = str(ID) > for i in range(cells.count()): >if text == strID: > break > > > But does CPython interpret the str() conversion away and essentially do > it for me in the first example? No. You can use the dis module to show you what CPython is doing under the hood. -- https://mail.python.org/mailman/listinfo/python-list
Re: Find the path of a shell command
On 10/11/22 22:00, Paulo da Silva wrote: > Hi! > > The simple question: How do I find the full path of a shell command > (linux), i.e. how do I obtain the corresponding of, for example, > "type rm" in command line? > > The reason: > I have python program that launches a detached rm. It works pretty well > until it is invoked by cron! I suspect that for cron we need to specify > the full path. > Of course I can hardcode /usr/bin/rm. But, is rm always in /usr/bin? > What about other commands? There are certain standards that suggest where to look. For example, there's the Linux Filesystem Hiearchy Standard 3.0: https://refspecs.linuxfoundation.org/FHS_3.0/fhs/ch03s04.html In short, you want to hard code /bin for a command like rm. And yes it will always be in /bin on any standard Linux OS. Despite modern distros making /bin and /usr/bin the same directory, if the target OS is anywhere close to the standard, you can always find the basic commands in /bin. I would not hard code any script to use /usr/bin for any basic commands and I would not use anything other than /bin/sh or /bin/bash as the shell script shebang if you want any sort of portability. -- https://mail.python.org/mailman/listinfo/python-list
Re: Find the path of a shell command
On 12/10/2022 07.20, Chris Green wrote: jak wrote: Il 12/10/2022 09:40, jkn ha scritto: On Wednesday, October 12, 2022 at 6:12:23 AM UTC+1, jak wrote: I'm afraid you will have to look for the command in every path listed in the PATH environment variable. erm, or try 'which rm' ? You might but if you don't know where the 'rm' command is, you will have the same difficulty in using 'which' command. Do not you think? From a command prompt use the bash built-in 'command' :- command -v rm ... and rm will just about always be in /usr/bin. On two different versions of Ubuntu, it's in /bin. -- Michael F. Stemper Psalm 94:3-6 -- https://mail.python.org/mailman/listinfo/python-list
Re: for -- else: what was the motivation?
On 09/10/2022 15.02, Peter J. Holzer wrote: On 2022-10-09 15:32:13 -0400, Avi Gross wrote: and of course no pipelines. Since you've now used that term repeatedly: What is a pipeline in Python? Could it be what's discussed starting on page 35 of this presentation? <http://www.dabeaz.com/generators/Generators.pdf> -- Michael F. Stemper Life's too important to take seriously. -- https://mail.python.org/mailman/listinfo/python-list
Re: What to use for finding as many syntax errors as possible.
On 09/10/2022 10.49, Avi Gross wrote: Anton There likely are such programs out there but are there universal agreements on how to figure out when a new safe zone of code starts where error testing can begin? For example a file full of function definitions might find an error in function 1 and try to find the end of that function and resume checking the next function. But what if a function defines local functions within it? What if the mistake in one line of code could still allow checking the next line rather than skipping it all? My guess is that finding 100 errors might turn out to be misleading. If you fix just the first, many others would go away. If you spell a variable name wrong when declaring it, a dozen uses of the right name may cause errors. Should you fix the first or change all later ones? How does one declare a variable in python? Sometimes it'd be nice to be able to have declarations and any undeclared variable be flagged. When I was writing F77 for a living, I'd (temporarily) put: IMPLICIT CHARACTER*3 at the beginning of a program or subroutine that I was modifying, in order to have any typos flagged. I'd love it if there was something similar that I could do in python. -- Michael F. Stemper 87.3% of all statistics are made up by the person giving them. -- https://mail.python.org/mailman/listinfo/python-list
Re: for -- else: what was the motivation?
>Well, the value is productivity. No need to save puzzles "what this >hanging else belongs to?" if you get to the point where it's hard to tell which else lines up with which if or for statement, I would suggest breaking things out into well-named helper functions rather than worrying over ordering by block size On Sun, Oct 9, 2022 at 2:26 AM Axy via Python-list wrote: > > > Yes, I'm aware that code readability becomes irrelevant for > > short-duration projects. Beside the point. I'm wondering how important > > it really is to have the shortest block first. > > > >> I also might be wrong in terminology, anyway, there are many rules that > >> make programmer's life easier, described in the literature from the old > >> good "How to write unmaintainable code" to "The Art of Readable Code". > >> And I hope there are a lot of recent books on this subject I did not > >> track and read yet. > > Also not really a justification for "shortest block first". Wanting > > some elaboration on that. What's the value in it? > > Well, the value is productivity. No need to save puzzles "what this > hanging else belongs to?" regardless of semantic, which ideally should > not be a puzzle as well. Code small things first and return early, same > as taking a test: do easy and quick things first and boring and > difficult ones later. > > Axy. > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: TkSheet
On 08/10/2022 07.58, Benny Rieger wrote: What a great work;-) I need a solution for save my tabel as csv. How to do that? Has someone a solution for that? Is this what you're seeking? <https://www.pythontutorial.net/python-basics/python-write-csv-file/> -- Michael F. Stemper No animals were harmed in the composition of this message. -- https://mail.python.org/mailman/listinfo/python-list
Re: Regarding python 3.10 installation
In order to save time for the experts here: On 19/09/2022 00.51, Shadid Alam wrote: Hello I’ve been trying to install updated python version i.e. python 10.7. There is no python 10.7. Are you possibly trying to install python 3.10.7? On what OS are you trying to install it? How are you trying to install it? Do you get any error messages when you try to install it? Its showing installed but whenever I open python it comes up with the older How are you "opening" it? version i.e. 10.9 . Please fix this issue is possible In order to do that, we'll need your root password and IP address. -- Michael F. Stemper Psalm 82:3-4 -- https://mail.python.org/mailman/listinfo/python-list
Re: Coffee
On 29/08/2022 07.16, Stefan Ram wrote: |Python's obviously a great tool for all kinds of programming things, |and I would say if you're only gonna use one programming |language in your live, Python will probably the right one. Brian Kernighan I transcribed this from the recent video "Coffee with Brian Kernighan". For those who'd like to see the whole chat: <https://www.youtube.com/watch?v=GNyQxXw_oMQ> -- Michael F. Stemper Deuteronomy 24:17 -- https://mail.python.org/mailman/listinfo/python-list
Re: python 3.10 vs breakage
On 8/26/22 14:37, gene heskett wrote: > Greetings all; > > Its now become obvious that 3.10 has broken some things. I can't build > linuxcnc with it. And > Octoprint has quit talking to 3d printers, now pronterface won't buy it, > can't find a 4.0.7 > version of wxPython with it sitting there staring at us. I have Fedora 35 here, nearing it's end of life. It has Python 3.10.6, and wxPython 4.0.7. I installed Pronterface 2.0.0 from the Fedora repos and it runs fine as near as I can tell. So there's no inherent incompatibility with Python 3.10 and wxPython 4.0.7. > Whats chances of a fixed version for bookworm? Or even a bugs fixed > release for bullseye? Seems like it is a distro-specific problem; I cannot replicate your error with pronterface on Fedora 35. I have no idea why octoprint won't work. -- https://mail.python.org/mailman/listinfo/python-list
Re: Conecting to MySQL
On 8/8/22 19:26, Guilherme Campos wrote: > Hello folks, > > trying to connect to MYSQL it appears the error msg below: > InterfaceError: 2003: Can't connect to MySQL server on 'localhost:3306' > (111 Connection refused) > [image: conexao.png] > How can i fix that.? MySQL can listen on a local unix socket (named pipe in Windows), an internet TCP/IP port, or both. If your MySQL is running, it could be listening on the local socket or named port, which has a different url than localhost:3306. MySQL can be configured to also listen on a TCP/IP port, which is what you code is apparently expecting. Although the fact that your MySQL Workbench cannot connect either suggests that MySQL is not running at all. Configuring MySQL is a bit beyond the scope of this list, although I'm sure there are people here who know how to do it. What OS are you using? -- https://mail.python.org/mailman/listinfo/python-list
Re: random.SystemRandom().randint() inefficient
On 26/07/2022 16.47, Cecil Westerhof wrote: Chris Angelico writes: On Wed, 27 Jul 2022 at 06:06, Cecil Westerhof via Python-list wrote: Chris Angelico writes: On Wed, 27 Jul 2022 at 01:06, Cecil Westerhof via Python-list wrote: I need to get a random integer. At first I tried it with: from secrets import randbelow index = randbelow(len(to_try)) This works perfectly, but it took some time. So I thought I try: from random import SystemRandom index = SystemRandom().randint(0, len(to_try) - 1) A first indication is that the second version would take about two times as much time as the first. Is there a reason for this, or should this not be happening? You're setting up a brand new SystemRandom instance just for a single random number. For a fairer comparison, set up the instance, then generate far more than just a single number, and see how that goes. Thanks. I thought I did something wrong and I did. I will try to implement like you said and look what the result will be. (And share it.) Thanks! Don't feel bad; performance testing is *hard*, getting meaningful results takes a lot of of fiddling with parameters, and getting interesting AND meaningful results can sometimes seem about impossible. (As I understand it both do more, or less the same and should have comparable performance.) In normal production work? Yes (the SystemRandom object doesn't have any significant state - a seeded RNG could have a lot more overhead here). But for performance testing? The work of instantiating the class could be completely irrelevant, or it could be dominating your results. It's hard to say, hence the suggestion to try it without reinstantiating. It had a very big influence. Original it took about three times more time to run my program. (The program was still running when I posted the original post and the difference was higher as I anticipated.) Removing that did cut about 45% of the execution time of the program. (So the initiation is quit expensive.) But it still takes about 50% more time. So I am still a bit flabbergasted. The new code: from random import SystemRandom system_random = SystemRandom() index = system_random.randint(0, len(to_try) - 1) This is orthogonal to your question, but might be of some use to you: The combination of using len(to_try) as an argument to randint() and saving the output to a variable named "index" suggests that you might be setting up to select a random element from to_try, as in: something = to_try[index] If that is the case, you might want to consider using random.choice() instead: >>> from random import choice >>> to_try = [2,3,5,7,11,13,"seventeen",19] >>> choice(to_try) 2 >>> choice(to_try) 'seventeen' >>> choice(to_try) 13 >>> choice(to_try) 5 >>> -- Michael F. Stemper This sentence no verb. -- https://mail.python.org/mailman/listinfo/python-list
Re: calculate diff between dates
On 12/07/2022 07.37, נתי שטרן wrote: [snip ugly code that I'm not going to try to understand] I glad for any help There wasn't any question in your post. However, I'm going to guess that there was the implied question of "How does one find the difference between two dates?" >>> import datetime >>> d1 = datetime.date(2022,1,1) >>> d2 = datetime.date(2022,7,12) >>> d2-d1 datetime.timedelta(192) >>> -- Michael F. Stemper If it isn't running programs and it isn't fusing atoms, it's just bending space. -- https://mail.python.org/mailman/listinfo/python-list
Re: Why isn't there a built-in product()?
On 07/07/2022 19.06, Oscar Benjamin wrote: On Thu, 7 Jul 2022 at 22:55, Michael F. Stemper wrote: sum() is wonderful. I understand that there is no product() or prod(). Does anybody here know why that was not included in the language? It seems as if it would be useful, so there must have been some rationale for that decision. There is math.prod: >>> from math import prod >>> prod([1, 2, 3, 4]) 24 https://docs.python.org/3/library/math.html#math.prod I did not know that. Thanks. -- Michael F. Stemper Outside of a dog, a book is man's best friend. Inside of a dog, it's too dark to read. -- https://mail.python.org/mailman/listinfo/python-list
Why isn't there a built-in product()?
sum() is wonderful. >>> nums = [1,2,3] >>> sum(nums) 6 >>> product(nums) Traceback (most recent call last): File "", line 1, in NameError: name 'product' is not defined >>> I understand that there is no product() or prod(). Does anybody here know why that was not included in the language? It seems as if it would be useful, so there must have been some rationale for that decision. -- Michael F. Stemper 87.3% of all statistics are made up by the person giving them. -- https://mail.python.org/mailman/listinfo/python-list
Re: fill out bulletins
On 13/06/2022 08.49, jak wrote: Hello everyone, I would like to write a tool to compile post office bulletins because here, unfortunately, they are still the most convenient way to interface the public administration. I don't want to create a UI to edit the bulletin, I will take the data from some file or database but I'd like to print or save the bulletin to the file with all the fields filled in. To accomplish this, I thought about creating a basic graphic (jpg?) file with the bulletin image, Please don't create an image. Create something that preserves text as text, so that your recipients can (if they so desire) search on that text, or copy/paste from your bulletin. Somebody suggested TeX/LaTeX. Excellent idea. -- Michael F. Stemper A preposition is something you should never end a sentence with. -- https://mail.python.org/mailman/listinfo/python-list
Re: Function to Print a nicely formatted Dictionary or List?
On 09/06/2022 12.52, Chris Angelico wrote: On Fri, 10 Jun 2022 at 03:44, Dave wrote: Before I write my own I wondering if anyone knows of a function that will print a nicely formatted dictionary? By nicely formatted I mean not all on one line! https://docs.python.org/3/library/pprint.html from pprint import pprint pprint(thing) >>> from pprint import pprint >>> d = {'two':2, 'three':5} >>> pprint(d) {'three': 5, 'two': 2} >>> This is all on one line. That might be acceptable to the OP, but it doesn't actually match what he said. -- Michael F. Stemper Outside of a dog, a book is man's best friend. Inside of a dog, it's too dark to read. -- https://mail.python.org/mailman/listinfo/python-list
Re: min, max with position
On 04/06/2022 14.08, Stefan Ram wrote: "Michael F. Stemper" writes: Are there similar functions that return not only the minimum or maximum value, but also its position? The maximum value does not need to have a unique position. Which is something that I'll just have to live with, whether I use home-brew or something from a standard module. For the particular application, my lists have 24 elements and are converted from data that is received in a %5.2f format, so collisions aren't too likely anyway. The World-Wide Web holds several suggestions like l.index( max( l )) or max( enumerate( l ), key=( lambda x: x[ 1 ])). Oh, I like that second one. I tried playing around with a lambda function, but combining with enumerate eluded me. It's much better than my for-loop with extraneous variables. -- Michael F. Stemper Psalm 94:3-6 -- https://mail.python.org/mailman/listinfo/python-list
Re: min, max with position
On 04/06/2022 13.56, Dennis Lee Bieber wrote: On Sat, 4 Jun 2022 13:36:26 -0500, "Michael F. Stemper" declaimed the following: Are there similar functions that return not only the minimum or maximum value, but also its position? If it isn't in the library reference manual, NO... But it also isn't that difficult to write... I already wrote it. I was wondering if there was something standard that I should have used instead. I have multiple functions that I wrote, only to later learn that there were standard functions that did the same thing. -- Michael F. Stemper This email is to be read by its intended recipient only. Any other party reading is required by the EULA to send me $500.00. -- https://mail.python.org/mailman/listinfo/python-list
min, max with position
Python contains built-in functions that return the minimum or maximum items in a list. >>> l = [1.618033,3.141593,2.718282] >>> min(l) 1.618033 >>> max(l) 3.141593 >>> Are there similar functions that return not only the minimum or maximum value, but also its position? >>> specialmin(l) (0,1.618033) >>> specialmax(l) 3.141593 >>> -- Michael F. Stemper I feel more like I do now than I did when I came in. -- https://mail.python.org/mailman/listinfo/python-list
Re: Automatic Gain Control in Python?
On 29/05/2022 10.04, Steve GS wrote: What you seem to be missing is that you could get the podcasts from a browser, and all a browser is is a program. It isn't that much work to write a rudimentary browser in python, especially if you don't actually need to display the results to a user, but are only trying to automate a particular task. Writing my own browser in Python might work. Do you have a sample one that I could twerk to fit my needs? I would have to be able to invoke it and an hour later devoke it least I end up with multiple audio channels playing. Somebody has already shown the rudiments of urllib. Another option to consider is the use of something like curl or wget to download the podcasts, which can be automated separately from your replay program. -- Michael F. Stemper This email is to be read by its intended recipient only. Any other party reading is required by the EULA to send me $500.00. -- https://mail.python.org/mailman/listinfo/python-list
Re: Request for assistance (hopefully not OT)
On 5/21/22 06:19, o1bigtenor wrote: > more useful - - - - well - - - - I don't have to wonder why 'linux' is > used as much > by the general populace as it is. The community likes to destroy > itself - - - it > is a pity - - - - the community has so much to offer. As far as community goes, the Linux community (whatever that might refer to) is pretty typical of all communities, including communities that surround proprietary systems like Windows. For those that realize that communication is two-way and individual effort is required, the community is a wonderful resource of help and support. For those that approach it with impatience and demands for support without evidence of individual effort, community members respond with much less alacrity. This is true of *all* communities of all types. I think in the Windows world people don't seem to have as many community problems because most people simply aren't a part of the community--the most impatient, grumpy people seem to have enough young relatives they can coax to solve their problems for them. -- https://mail.python.org/mailman/listinfo/python-list
Re: "py" command for Linux and Mac?
On 5/12/22 11:59, De ongekruisigde wrote: > On 2022-05-12, Mats Wichmann wrote: >> On 5/12/22 10:25, Dan Stromberg wrote: >>> Hi folks. >>> >>> I heard there's a Windows-like "py" command for Linux (and Mac?). >>> >>> I'm finally getting to porting a particular project's Python 2.7 code to >>> 3.x, and one of the first steps will probably be changing a lot of "python2 >>> script.py" to use #!/usr/bin/env python2 and chmod +x. Then we can update >>> the scripts one at a time to use #!/usr/bin/env python3. >>> >>> However, would this be Linux-and-Mac-only? I'm not at all sure this code >>> will ever move to Windows, but in case it does, would a "py" command work >>> on all 3 if I use #!/usr/bin/env py? >> >> The py command (python lanucher) respects shebang lines. > > Linux by itself respects shebang lines, so you don't need a separate > launcher program. Just put e.g.: Dan knows this already. His question is about whether the shebang should instead refer to a py launcher so that this script will run on Windows or Linux. And of course the answer given by the grandparent is that Dan should use a normal linux shebang line in his scripts and on Windows the py launcher will read that shebang and guestimate the proper python interpreter to use and execute the script with that. Thus if I'm reading this correctly, a Linux shebang line should function as expected on Windows when python files are associated and launched with the py.exe launcher, even though there's no such thing as /usr/bin/python3 on Windows. Py launcher makes it work as if there was. -- https://mail.python.org/mailman/listinfo/python-list
Re: Request for assistance (hopefully not OT)
On 5/17/22 05:20, o1bigtenor wrote: > What can I do to correct this self-inflicted problem? Those are always the fun ones. Reminds me of when I was first learning Linux using Red Hat Linux 5.0 or 5.1. This was long before nice dependency-solving tools like apt. I wanted to install and run StarOffice, but it needed a newer libc (this was during the painful transition from libc5 to glibc6). I ended up removing libc which *everything depends on, trying to get the glibc update installed. Needless to say that broke the entire system. Nothing but a reinstall could be done in those days. Anyway, good luck. I think you can rescue it yet following the advice others have given. -- https://mail.python.org/mailman/listinfo/python-list
Re: Changing calling sequence
On 11/05/2022 14.58, anthony.flury wrote: Why not do : def TempsOneDayDT(date:datetime.date): return TempsOneDay(date.year, date.month, date.day) No repeat of code - just a different interface to the same functionality. Yeah, a one-line wrapper around the original function seems a lot simpler that any of my ideas. I think that I'll even use the name from your example. Thanks to all who posted, as well as the many lurkers who support me in email. -- Michael F. Stemper Economists have correctly predicted seven of the last three recessions. -- https://mail.python.org/mailman/listinfo/python-list
Changing calling sequence
I have a function that I use to retrieve daily data from a home-brew database. Its calling sequence is; def TempsOneDay( year, month, date ): After using it (and its friends) for a few years, I've come to realize that there are times where it would be advantageous to invoke it with a datetime.date as its single argument. As far as I can tell, there are three ways for me to proceed: 1. Write a similar function that takes a single datetime.date as its argument. 2. Rewrite the existing function so that it takes a single argument, which can be either a tuple of (year,month,date) or a datetime.date argument. 3. Rewrite the existing function so that its first argument can be either an int (for year) or a datetime.date. The existing month and date arguments would be optional, with default=None. But, if the first argument is an int, and either of month or date is None, an error would be raised. The first would be the simplest. However, it is obviously WET rather than DRY. The second isn't too bad, but a change like this would require that I find all places that the function is currently used and insert a pair of parentheses. Touching this much code is risky, as well as being a bunch of work. (Admittedly, I'd only do it once.) The third is really klunky, but wouldn't need to touch anything besides this function. What are others' thoughts? Which of the approaches above looks least undesirable (and why)? Can anybody see a fourth approach? -- Michael F. Stemper This post contains greater than 95% post-consumer bytes by weight. -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 24/04/2022 08.24, Michael F. Stemper wrote: On 23/04/2022 12.43, Avi Gross wrote: Given what you added, Michael, your function is part of a larger collection of functions and being compatible with the others is a valid consideration. Whatever you decide, would ideally be done consistently with all or most of them. And, of course, it others in the collection also can handle multiple ways to specify a permutation, it may be simpler to have each call something like as.permutation() that handlesmultiple forms and converts to the one easiest for you to use. I am not sure that is needed as I suspect the simplest storage is something like a list: [0,3,2,4,5,6,7,1,9,8] but could also be shown with each cycle as a sub-list or something like anumpy vector or a customized class. Since you ask, I'm using dictionaries as the internal representation. If you think about it, a python dictionary *is* a function from one finite set to another, mathematically. And a (finite) permutation is a bijection from a (finite) set to itself. For convenience, the module provides two methods of defining a permutation other than just entering a dictionary: >>> import PermGroups as pg >>> a = {'1':'2', '2':'1', '3':'3'} >>> b = pg.ParsePerm( '(12)(3)' ) >>> c = pg.ParseDomImg( '123', '213' ) >>> a==b True >>> b==c True >>> All of the other functions work on these dictionaries. I had thought about defining a permutation object, but the conceptual match between "dict" and "permutation" was too good to discard. Clearly if you control the package and how it is used, errors from bad data may not be a concern. An invalidly-constructed permutation will cause an exception, so the function won't return. The below was *not* intended to illustrate what I said above. It shows the validation function provided by the module. This allows the user to avoid the consequences of an invalidly-constructed permutation. (It's only for users who don't subscribe to "EAFP", of course.) >>> d = {'1':'2', '2':'2', '3':'3'} >>> pg.ValidateDict(d) False >>> If I was to do it over, I would have named this function something like IsValidPermutation(), hiding the internal representation as well as making the function's Boolean nature explicit. -- Michael F. Stemper Psalm 82:3-4 -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 23/04/2022 12.43, Avi Gross wrote: Given what you added, Michael, your function is part of a larger collection of functions and being compatible with the others is a valid consideration. Whatever you decide, would ideally be done consistently with all or most of them. And, of course, it others in the collection also can handle multiple ways to specify a permutation, it may be simpler to have each call something like as.permutation() that handlesmultiple forms and converts to the one easiest for you to use. I am not sure that is needed as I suspect the simplest storage is something like a list: [0,3,2,4,5,6,7,1,9,8] but could also be shown with each cycle as a sub-list or something like anumpy vector or a customized class. Since you ask, I'm using dictionaries as the internal representation. If you think about it, a python dictionary *is* a function from one finite set to another, mathematically. And a (finite) permutation is a bijection from a (finite) set to itself. For convenience, the module provides two methods of defining a permutation other than just entering a dictionary: >>> import PermGroups as pg >>> a = {'1':'2', '2':'1', '3':'3'} >>> b = pg.ParsePerm( '(12)(3)' ) >>> c = pg.ParseDomImg( '123', '213' ) >>> a==b True >>> b==c True >>> All of the other functions work on these dictionaries. I had thought about defining a permutation object, but the conceptual match between "dict" and "permutation" was too good to discard. Clearly if you control the package and how it is used, errors from bad data may not be a concern. An invalidly-constructed permutation will cause an exception, so the function won't return. >>> d = {'1':'2', '2':'2', '3':'3'} >>> pg.ValidateDict(d) False >>> If I was to do it over, I would have named this function something like IsValidPermutation(), hiding the internal representation as well as making the function's Boolean nature explicit. -- Michael F. Stemper No animals were harmed in the composition of this message. -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 22/04/2022 16.12, alister wrote: On Fri, 22 Apr 2022 14:36:27 -0500, Michael F. Stemper wrote: I'm writing a function that is nearly self-documenting by its name, but still want to give it a docstring. Which of these would be best from a stylistic point of view: for guidance I would sugest Pep257 as a start point which would suggest "Return True if permutation is even" I'll take a look at the PEP. Thanks. -- Michael F. Stemper This email is to be read by its intended recipient only. Any other party reading is required by the EULA to send me $500.00. -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 22/04/2022 21.58, Avi Gross wrote: Python does have a concept of "truthy" that includes meaning for not just the standard Booleans but for 0 and non-zero and the empty string and many more odd things such as an object that defines __bool__ (). But saying it returns a Boolean True/False valuesounds direct and simple and informative enough if that is True. What bothers me is the assumption that anyone knows not so muchjust group theory but what the argument to the function looks like as a Python object of some kind. Does the function accept only some permutation object managed by a specific module? Will it accept some alternate representation such as a list structure or other iterator? That's a fair point. However, this function will be the 22nd one in a module for dealing with permutations and groups of permutations. The module has a lengthy docstring explaining the several ways provided to specify a permutation. That way, the same information doesn't need to be written twenty-plus times. Obviously deeper details would normally be in a manual page or other documentation but as "permutations" are likely not to be what most people think about before breakfast, or even after, odd as that may seem, ... I see what you did there :-> -- Michael F. Stemper Psalm 94:3-6 -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 22/04/2022 14.59, Chris Angelico wrote: On Sat, 23 Apr 2022 at 05:56, Michael F. Stemper wrote: I'm writing a function that is nearly self-documenting by its name, but still want to give it a docstring. Which of these would be best from a stylistic point of view: Tells caller whether or not a permutation is even. Determines if a permutation is even. (Alternative is that it's odd.) Returns True if permutation is even, False if it is odd. I'd go with the third one, but "Return" rather than "Returns". Or possibly "Test whether a permutation is even". "So let it be written. So let it be done." That's just one opinion though, others may disagree :) Two for two. Thanks. -- Michael F. Stemper Always remember that you are unique. Just like everyone else. -- https://mail.python.org/mailman/listinfo/python-list
Style for docstring
I'm writing a function that is nearly self-documenting by its name, but still want to give it a docstring. Which of these would be best from a stylistic point of view: Tells caller whether or not a permutation is even. Determines if a permutation is even. (Alternative is that it's odd.) Returns True if permutation is even, False if it is odd. (Before somebody suggests it, I'm not going to put six weeks' worth of a course in group theory in there to help somebody who doesn't know what those standard terms mean.) -- Michael F. Stemper 87.3% of all statistics are made up by the person giving them. -- https://mail.python.org/mailman/listinfo/python-list
Re: Feature Request
On 23/03/2022 03.55, Kazuya Ito wrote: Add "trun()" function to Python to truncate decimal part. Which of these should its behavior copy? from math import pi int(pi) 3 pi-int(pi) 0.14159265358979312 -- Michael F. Stemper This post contains greater than 95% post-consumer bytes by weight. -- https://mail.python.org/mailman/listinfo/python-list
Re: Suggestion for Linux Distro (from PSA: Linux vulnerability)
On 3/11/22 11:03, Marco Sulla wrote: > Anyway I think I'll not install Debian, because it's LTS releases are > not long enough for me. I don't know if there's a distro based on > Debian that has a long LTS support, Ubuntu apart. Both Debian stable and Ubuntu LTS state they have a five year support life cycle. Ubuntu will support longer if you pay for it. Do you require more than five years? Anyway, use whatever works for you. -- https://mail.python.org/mailman/listinfo/python-list
Re: Suggestion for Linux Distro (from PSA: Linux vulnerability)
On 3/10/22 12:42, Marco Sulla wrote: > PS: Is it just my impression or is there a plebiscite for Debian? A vote? No I don't think so. Not sure what you mean. The reason we're all suggesting Debian is because you specifically said you want a LTS Debian-like distro. Can't get any more Debian-like than Debian! Debian with XFCE should give you the same experience as Xubuntu, and is always supported for a very long time. Personally I run Fedora with Mate or KDE and I upgrade the OS every 12-18 months, usually skipping a version or two. I did consider Centos 8 stream, but I needed something a little newer for various reasons. -- https://mail.python.org/mailman/listinfo/python-list
Re: Suggestion for Linux Distro (from PSA: Linux vulnerability)
On 3/10/22 06:03, Marco Sulla wrote: > I tried Debian on a VM, but I found it too much basical. A little > example: it does not have the shortcut ctrl+alt+t to open a terminal > that Ubuntu has. I'm quite sure it's simple to add, but I'm starting > to be old and lazy... Debian has the same desktop environments available for install as the rest of the distros. Gnome 3, Mate, LXDE, XFCE, KDE, etc. Whatever works for you on Ubuntu should work on Debian. -- https://mail.python.org/mailman/listinfo/python-list
Re: PSA: Linux vulnerability
On 3/9/22 13:05, Marco Sulla wrote: > So my laziness pays. I use only LTS distros, and I update only when > there are security updates. > PS: any suggestions for a new LTS distro? My Lubuntu is reaching its > end-of-life. I prefer lightweight debian-like distros. Maybe Debian itself? -- https://mail.python.org/mailman/listinfo/python-list
Re: Behavior of the for-else construct
On 04/03/2022 18.11, Peter J. Holzer wrote: On 2022-03-04 23:47:09 +, Avi Gross via Python-list wrote: I am not sure a reply is needed, Peter, and what you say is true. But as you point out, when using a German keyboard, I would already have a way to enter symbols like ä, ö, ü and ß and no reason not to include them in variable names and so on if UNICODE is being used properly. I can use my last name in German notation as a variable in Python now: Groß = 144 Groß / 12 12.0 Yes, I'm using umlauts occasionally in variable names in Python, and I've also used Greek characters and others. But in Python I CAN use them. I DON'T HAVE to. That's a big difference. Characters like [] or {} are a part of Python's syntax. You can't avoid using them. If you can't type them, you can't write Python. If it is awkward to enter them (like having to type Alt-91 or pasting them from a character table) it is painful to write programs. German keyboards aquired an AltGr key and the ability to type these characters in the mid to late 1980's. Presumably because those characters were common in C and other programming languages ... especially Pascal, which was probably bigger in Germany and Austria in the 1980s than was C. -- Michael F. Stemper Psalm 94:3-6 -- https://mail.python.org/mailman/listinfo/python-list
Re: Behavior of the for-else construct
On 03/03/2022 19.54, Rob Cliffe wrote: On 04/03/2022 01:44, Ethan Furman wrote: On 3/3/22 5:32 PM, Rob Cliffe via Python-list wrote: > There are three types of programmer: those that can count, and those that can't. Actually, there are 10 types of programmer: those that can count in binary, and those that can't. 1, 10, many. No problem. Ah, a George Gamow fan. -- Michael F. Stemper Psalm 82:3-4 -- https://mail.python.org/mailman/listinfo/python-list