From nhlanhlah198506 at gmail.com Tue Nov 1 12:08:05 2022 From: nhlanhlah198506 at gmail.com (nhlanhlah198506) Date: Tue, 01 Nov 2022 18:08:05 +0200 Subject: Information about slow execution notebook Message-ID: <63614468.df0a0220.5de3d.b823@mx.google.com> I wish to know why sometimes my notebook won't execute my program?And VS code won't connect to kernels.?Thank you?Nhlanhla Ndwandwe?Sent from my Galaxy From jshem at yaxenu.org Tue Nov 1 13:46:48 2022 From: jshem at yaxenu.org (Julieta Shem) Date: Tue, 01 Nov 2022 14:46:48 -0300 Subject: an oop question References: <86y1sxmmvo.fsf@yaxenu.org> <86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org> <86v8o0hlno.fsf@yaxenu.org> Message-ID: <86h6zih8jb.fsf@yaxenu.org> Chris Angelico writes: > On Mon, 31 Oct 2022 at 14:38, Julieta Shem wrote: >> >> Chris Angelico writes: >> >> > The most straight-forward way to represent this concept in an >> > object-oriented way is subclassing. >> > >> > class Stack: >> > ... # put whatever code is common here >> > >> > class Empty(Stack): >> > ... # put Empty-specific code here, possibly overriding Stack methods >> > >> > class Pair(Stack): >> > ... # ditto, overriding or augmenting as needed >> > >> > This way, everything is an instance of Stack, but they are still >> > distinct types for when you need to distinguish. >> >> Can you provide a small example? I can't see what you mean, but it >> seems interesting. > > Sure. The easiest way would be to take your existing Empty and Pair > classes, have them subclass Stack, and don't bother putting any code > at all into Stack. Then construct an Empty and a few Pairs, and what > you'll see is that all of them are also instances of Stack. > > After that, it's really a question of what you expect to be able to do > with either an Empty or a Pair. Anything that should be possible with > both types (that is, anything that should be possible with either > variant of Stack) should get moved into the Stack type, while anything > that is specific to one or the other stays in its own class. So here's > a very very simple example: > > class Stack: > def prepend(self, other): > return Pair(other, self) > > class Empty(Stack): > def is_last(self): > return True > def get_current(self): > raise ValueError("Stack empty") > def get_next(self): > raise ValueError("Stack empty") > > class Pair(Stack): > def __init__(self, item1, item2): > self.item1 = item1 > self.item2 = item2 > def get_current(self): > return self.item1 > def get_next(self): > return self.item2 > def is_last(self): > return isinstance(self.item2, Empty) > > With this setup, you can build a stack by prepending items onto an > Empty endpoint, and can iterate over it with the get_current and > get_next methods. (Making this actually iterable, so that it works > with a Python 'for' loop, would be a good exercise.) > > In this example, there isn't much code in the Stack class. But you > could easily add more, and it would apply to both Empty and Pair. Thank you so much for the example. It's very interesting as it sort of reverses my intuition. It seems non-obvious. I had in mind to build a Stack out of Empty and Pair, but you seem to have done it the other way around. But I still don't see a way of using your classes up there in which I have a single name to build empty and non-empty stacks. Let me clarify. If I wish for an empty stack, I wish I could just say >>> Stack() Stack() and if I wish for a nonempty stack, I'd write >>> Stack(1, Stack(2, Stack(3, Stack()))) Stack(1, Stack(2, Stack(3, Stack()))) With your classes, I think I must write >>> Empty() # That's an empty stack ... >>> Pair(1, Pair(2, Empty())) # That's a non-empty stack ... In other words, I need to memorize two different names for using stacks. I'm trying to have a single name for both parts of the union (that is my design of a stack). Thanks so much! From jshem at yaxenu.org Tue Nov 1 13:58:54 2022 From: jshem at yaxenu.org (Julieta Shem) Date: Tue, 01 Nov 2022 14:58:54 -0300 Subject: an oop question References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> Message-ID: <865yfyh7z5.fsf@yaxenu.org> Alan Gauld writes: > On 30/10/2022 14:01, Julieta Shem wrote: > >> I wrote the classes >> >> class Empty: >> ... >> class Pair: >> ... >> >> (*) How to build a stack? >> >> These Lisp-like sequences are clearly a stack. > > That is a very important observation. A Pair IS-A Stack(sort of). > If you had a stack you could create a Pair from it certainly. Yes, they are the same thing --- in my mind ---, except possibly for the user interface, names and stuff. I do prefer to make the user think he has something else simply because it has a different name. It is not the user's business to know what things are on the inside. >> So far so good, but when it comes to building a better user interface >> for it I have no idea how to do it. I think one of the purposes of OOP >> is to organize code hierarchically so that we can reuse what we wrote. > > One of the purposes of classes certainly. I'm not so sure it's a purpose > of OOP. They are not the same thing. A class is a programming construct > OOP is a programming style. Classes facilitate OOP but can be used > outside of OOP too. That's an interesting observation. I like that. Classes are one thing and OOP is another. Of course, at the extreme I think I will get nowhere in trying to detect in high-precision what is OOP and what is not. The same for classes. I always liked to think of C structures as some class. Instead of saying ``new Whatever()'', I'd say ``malloc(sizeof ...)''. I'd then have many procedures whose first argument were a pointer to Whatever. They're the methods. So the structure Whatever si the class itself. Is this use of C outside of OOP? I say it is not because my notion of OOP is that --- a way to make objects and have methods operate on them, changing them or not. Should I allow the non-change of objects to be OOP as well? I think so. To me what distinguishes functional from imperative is, for example, imperative has side-effects. We can take an imperative set of tools and do not produce any side-effects (locally speaking, of course) and that would be indisguishable from functional programming. We can say that imperative languages are more general than functional ones. (That's my non-educated guess for the moment anyhow.) >> So I tried to make a Stack by inheriting Pair. > > But you said above that a Pair was a Stack. Inheritance implies an > IS-A relationship, so Stack inheriting Pair would mean that a Stack > was a Pair. That is not really true. That's another interesting observation. I do not have much understanding of how to really think of these things and that's most likely why I never tried to understand OOP or imperative programming. It seems very difficult. What I meant is that a Pair was a Stack and a Stack was a Pair. The reason I was creating a Stack at all was just to make the user think it's something different --- and with more obvious names for the case under analysis, which was the use of a stack-like data structure. > A Stack could use a Pair (or many of them) but it is not a Pair. Is this how I should design it? I tried that, actually. It seemed to complicate my life because I had to provide to my Stack class various other methods my Pair class already had. > Trying to use inheritance inappropriately is one of the > biggest (and commonest) mistakes in OOP. It invariably leads > to complications. If in doubt use delegation instead. What is delegation? I think that's why I never went into OOP and imperative languages. It just seems bloody difficult to get anything right. Call me stupid or what you will, but it seems very difficult. Any book recomendations on getting this thing mathematics-clear? Thank you! From gweatherby at uchc.edu Tue Nov 1 16:32:33 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Tue, 1 Nov 2022 20:32:33 +0000 Subject: an oop question In-Reply-To: References: <86y1sxmmvo.fsf@yaxenu.org> <86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org> <86v8o0hlno.fsf@yaxenu.org> <86h6zih8jb.fsf@yaxenu.org> Message-ID: I think: class Stack: def __init__( self, *args ): self.data = args def __str__( self ): return f"Stack({','.join(str(x) for x in self.data)})" gives equivalent output for the if len(args) is 0 or 2, if it?s okay for self.data to be a tuple. class Stack: def __init__( self, *args ): self.data = list(args) def __str__( self ): return f"Stack({','.join(str(x) for x in self.data)})" If it?s desired self.data be a list. From: Python-list on behalf of Stefan Ram Date: Tuesday, November 1, 2022 at 3:43 PM To: python-list at python.org Subject: Re: an oop question *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** Julieta Shem writes: >clarify. If I wish for an empty stack, I wish I could just say >>>> Stack() >Stack() >and if I wish for a nonempty stack, I'd write >>>> Stack(1, Stack(2, Stack(3, Stack()))) >Stack(1, Stack(2, Stack(3, Stack()))) If this is all, main.py class Stack: def __init__( self, *args ): self.data = [ args[ 0 ], args[ 1 ]]if len( args ) else [] def __str__( self ): if len( self.data ): return f"Stack({self.data[0]}, {self.data[1]})" else: return f"Stack()" print( Stack() ) print( Stack(1, Stack(2, Stack(3, Stack()))) ) output Stack() Stack(1, Stack(2, Stack(3, Stack()))) . -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!itEYnwU5jJ0z8_rkW_q_ogw3ZJUNdHdMNkMLpSAqBdozBNrr7NqPs_gNsbx8W9uXRLZpG38C9an17Yx2zUf-mSA$ From barry at barrys-emacs.org Tue Nov 1 16:49:26 2022 From: barry at barrys-emacs.org (Barry Scott) Date: Tue, 1 Nov 2022 20:49:26 +0000 Subject: Information about slow execution notebook In-Reply-To: <63614468.df0a0220.5de3d.b823@mx.google.com> References: <63614468.df0a0220.5de3d.b823@mx.google.com> Message-ID: <79269441-3108-43B8-990B-9E1D4151B86D@barrys-emacs.org> > On 1 Nov 2022, at 16:08, nhlanhlah198506 wrote: > > I wish to know why sometimes my notebook won't execute my program And VS code won't connect to kernels. Thank you Nhlanhla Ndwandwe Sent from my Galaxy You need to provide details on what you do and what happens. Reminder do not attach screen shots, they are striped in this mailing list. Cut-n-paste full error message information. Barry > -- > https://mail.python.org/mailman/listinfo/python-list From jshem at yaxenu.org Tue Nov 1 16:54:37 2022 From: jshem at yaxenu.org (Julieta Shem) Date: Tue, 01 Nov 2022 17:54:37 -0300 Subject: an oop question References: <86y1sxmmvo.fsf@yaxenu.org> <86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org> <86v8o0hlno.fsf@yaxenu.org> <86h6zih8jb.fsf@yaxenu.org> Message-ID: <86sfj2fl9u.fsf@yaxenu.org> ram at zedat.fu-berlin.de (Stefan Ram) writes: > Julieta Shem writes: >>clarify. If I wish for an empty stack, I wish I could just say >>>>> Stack() >>Stack() >>and if I wish for a nonempty stack, I'd write >>>>> Stack(1, Stack(2, Stack(3, Stack()))) >>Stack(1, Stack(2, Stack(3, Stack()))) > > If this is all, > > main.py > > class Stack: > def __init__( self, *args ): > self.data = [ args[ 0 ], args[ 1 ]]if len( args ) else [] > def __str__( self ): > if len( self.data ): > return f"Stack({self.data[0]}, {self.data[1]})" > else: > return f"Stack()" > > print( Stack() ) > > print( Stack(1, Stack(2, Stack(3, Stack()))) ) > > output > > Stack() > Stack(1, Stack(2, Stack(3, Stack()))) Thanks! But we've left behind a more basic requirement --- the Stack class wishes for all the methods already written in some class called Pair, which has a certain connection with a class Empty. This requirement has been implicit in the first message in this thread, though. I didn't make it explicit. (In other words, this part of the thread only makes sense by taking into account all the previous messages up in the thread.) From jshem at yaxenu.org Tue Nov 1 16:56:41 2022 From: jshem at yaxenu.org (Julieta Shem) Date: Tue, 01 Nov 2022 17:56:41 -0300 Subject: an oop question References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> Message-ID: <86leoufl6e.fsf@yaxenu.org> ram at zedat.fu-berlin.de (Stefan Ram) writes: > ram at zedat.fu-berlin.de (Stefan Ram) writes: >>The crucial feature OOP adds to this is polymorphism ("late binding"). > > If polymorphism is so crucial, the idea of subclasses > has something to it! [...] I wonder what Rich Hickey would say here. Didn't he design Clojure with ``multimethods'' so that we can get some kind of polymorphism without subclassing? From eryksun at gmail.com Tue Nov 1 17:18:32 2022 From: eryksun at gmail.com (Eryk Sun) Date: Tue, 1 Nov 2022 16:18:32 -0500 Subject: Problems with IDLE in Windows 8.1 and installer x86 Version 3.10.8 In-Reply-To: <202211011649.2A1GnNrU115152@mail36c50.megamailservers.eu> References: <202210311822.29VIMTpw130438@mail92c50.megamailservers.eu> <202210312138.29VLcBUQ008124@mail118c50.megamailservers.eu> <202211011649.2A1GnNrU115152@mail36c50.megamailservers.eu> Message-ID: On 11/1/22, darkstone at o2online.de wrote: > > **IDLE can?t Import TKINTER > > Python may not be configured for TK** > > Checkmark for TK is set in the Installation Progress. What went wrong and ho > can I fix it? Run the following command to check whether the ImportError has any further information. py -3.10-32 -c "from tkinter import *" It could be a missing extension module or DLL, or mismatched version. You could try modifying the installation to remove tkinter and IDLE, and then again to restore it. From eryksun at gmail.com Tue Nov 1 21:40:24 2022 From: eryksun at gmail.com (Eryk Sun) Date: Tue, 1 Nov 2022 20:40:24 -0500 Subject: Problems with IDLE in Windows 8.1 and installer x86 Version 3.10.8 In-Reply-To: References: <202210311822.29VIMTpw130438@mail92c50.megamailservers.eu> <202210312138.29VLcBUQ008124@mail118c50.megamailservers.eu> <202211011649.2A1GnNrU115152@mail36c50.megamailservers.eu> Message-ID: On 11/1/22, Nithish Ramasamy wrote: > > pip install tkinter > Wait some minutes to install tkinter There is no tkinter package on PyPI. It's part of the standard library and included with the python.org installer as an optional component. From greg.ewing at canterbury.ac.nz Wed Nov 2 02:10:05 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Wed, 2 Nov 2022 19:10:05 +1300 Subject: an oop question In-Reply-To: <86sfj2fl9u.fsf@yaxenu.org> References: <86y1sxmmvo.fsf@yaxenu.org> <86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org> <86v8o0hlno.fsf@yaxenu.org> <86h6zih8jb.fsf@yaxenu.org> <86sfj2fl9u.fsf@yaxenu.org> Message-ID: On 2/11/22 9:54 am, Julieta Shem wrote: > But we've left behind a more basic requirement --- the Stack > class wishes for all the methods already written in some class called > Pair, Is that *really* what you want, though? To my way of thinking, a Stack and a Pair are quite different data structures, each having their own characteristic operations. Things I want to be able to do with a Stack: - Create an empty stack - Push an item onto the top of the stack - Pop an item off the top of the stack Things I want to be able to do with a Pair: - Create a pair containing two given objects - Get the first item - Get the second item I don't see any overlap between these at the conceptual level. Possibly I might want to use Pairs as part of the *implementation* of a stack, but that doesn't mean that any Pair methods should appear as Stack methods. Here's how I might do this in a functional style using Python: class Pair: def __init__(self, first, second): self._first = first self._second = second def first(self): return self._first def second(self): return self._second class Stack: def __init__(self): self._data = None def push(self, item): result = Stack() result._data = Pair(item, self._data) return result def pop(self): rest = Stack() rest._data = self._data.second() return self._data.first(), rest Note that neither Stack nor Pair inherits from the other. -- Greg From learn2program at gmail.com Wed Nov 2 13:52:11 2022 From: learn2program at gmail.com (Alan Gauld) Date: Wed, 2 Nov 2022 17:52:11 +0000 Subject: an oop question In-Reply-To: <865yfyh7z5.fsf@yaxenu.org> References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> Message-ID: <49e71d27-8a6b-bfe7-95e7-dc3b8cb83ea5@yahoo.co.uk> On 01/11/2022 17:58, Julieta Shem wrote: > nowhere in trying to detect in high-precision what is OOP and what is > not. Stefan has given a good answer but essentially OOP is a program that is structured around objects communicating by sending messages to one another. Objects are, in most (but not all) languages implemented using classes. A class is just a record or structure that can contain data and functions. In most (but not all) implementations of OOP messages are implemented as calls to the functions within an objects class. > The same for classes. I always liked to think of C structures as > some class. Provided that we allow pointers to functions within the struct then yes. Indeed the difference between structs and classes in C++ is very thin. And with the recent introduction of data classes in Python the boundaries are blurred here too. In pure OOP a class with only data would be pointless(since the data should ideally be hidden or "private"!) > structure Whatever si the class itself. Is this use of C outside of > OOP? I say it is not because my notion of OOP is that --- a way to make > objects and have methods operate on them, changing them or not. It's how many early attempts at OOP in C worked, including C++. Others, such as Objective C and cFlavours took a different approach. But conceptually methods do not "operate on objects" methods are how objects respond to messages. Eah object has its own method of handling a particular message. (This is polymorphism) In most (but not all) practical implementations methods are usually implemented as functions and so it seems like a message is just a synonym for acalling a method, but is more than that, it implies some kind of dynamic lookup. (for example when the method is implemented in a paremt class rather than the directly referenced one. But the functions that represent methods do indeed operate on their own object - ie self. > To me what distinguishes functional from imperative is, Not that imperative programming is not the same as OOP. Or at least it encompasses much more than OOP. Most OOP programs are written in imperative languages but it is possible to have functional OOP programs too. (If we consider the state data to be a single compound value that can only be changed by the object internally, or a new object with different state values returned.) >> IS-A relationship, so Stack inheriting Pair would mean that a Stack >> was a Pair. That is not really true. > > That's another interesting observation. I do not have much > understanding of how to really think of these things Read up on the Liskoff substitution principle as one approach to determining what an IS-A relationship means. Its not the only approach but it is less vague than some others! >> to complications. If in doubt use delegation instead. > > What is delegation? A fancy OOP term to mean containment. Specifically a method delegates the work top some internal object. eg. You can build a stack by containg a list within it. The stack delegates much of the work to the list object. In fact, in Python a stack can be a very thin wrapper over a list! > Any book recomendations on getting this thing mathematics-clear? The best book is IMHO Bertrand Meyer's book "Object Oriented Software Construction". It uses his own language,. Eiffel, but gives an excellent description of applied OOP and all of its features (Eiffel is perhaps the most feature complete OOPL of all - but, being proprietary (and somewhat buggy!) it has never quite caught on) But for a mathematical basis you need to look outside programming at systems engineering and the work done on cellular automata. In a pure OOP program each object should act as an independant cell communicating by asynchronous messages. Exactly as in cellular automata theory. .. Unfortunately, there is a huge gap between pure OOP theory and practical OOP languages! And just as big a gap between OOP language potential and real-world OOP usage. Very few purely OOP programs exist (maybe excepting in Smalltalk - see Stefan's posts again). :-( -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From elasstiika at gmail.com Wed Nov 2 18:22:57 2022 From: elasstiika at gmail.com (elas tica) Date: Wed, 2 Nov 2022 15:22:57 -0700 (PDT) Subject: Operator: inappropriate wording? In-Reply-To: References: <4a3bbb16-0d2e-4230-948d-793e5915721an@googlegroups.com> <91181647-7008-4912-86a2-e6f39cda4744n@googlegroups.com> Message-ID: <61004995-396e-4bb6-bbdd-bd877defc275n@googlegroups.com> Le lundi 31 octobre 2022 ? 22:18:57 UTC+1, Chris Angelico a ecrit?: > Wording is hard. Just ask the SQL standard whether NULL is a value. > Indeed, but I think our problem here is simpler ;) One could for example omit the incorrect term "operator" while remaining unambiguous. This would give: If the object is a class instance and the attribute reference occurs on both sides of the assignment, the right-hand side expression,... Now, as for the other formulation from the reference document: The second half of the list, the augmented assignment operators, serve lexically as delimiters, but also perform an operation. (link: https://docs.python.org/3/reference/lexical_analysis.html#delimiters) it is incorrect (as explained by the FAQ I quoted in my last post) and the explanations it gives are even more incorrect suggesting that anything that performs an operation is the result of the action of an operator. Under these conditions, we could say that del is an operator and even that return is an operator! I opened an issue on the CPython GitHub repository, here: https://github.com/python/cpython/issues/98814 From learn2program at gmail.com Wed Nov 2 20:15:05 2022 From: learn2program at gmail.com (Alan Gauld) Date: Thu, 3 Nov 2022 00:15:05 +0000 Subject: [correction]an oop question In-Reply-To: References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <86leoufl6e.fsf@yaxenu.org> Message-ID: On 02/11/2022 20:21, Dennis Lee Bieber wrote: >> shows that in Python we do *not* need subclassing/inheritance >> for polymorphism! >> > To me, that is not really an example of polymorphism, but more an > example of Python's "duck typing". But duck typing is a perfectly good implementation of polymorphism. The term just means that different objects respond to the same message in different ways. Nothing more, nothing less. Inheritance just happens to be the most common way of building that, especially in statically typed languages. > > I'd implement the example hierarchy as > >>>> class Language: > ... def f(self): > ... print(self.greeting) And that would be perfectly valid too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From jshem at yaxenu.org Wed Nov 2 20:25:30 2022 From: jshem at yaxenu.org (Julieta Shem) Date: Wed, 02 Nov 2022 21:25:30 -0300 Subject: an oop question References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> Message-ID: <865yfwevet.fsf@yaxenu.org> ram at zedat.fu-berlin.de (Stefan Ram) writes: > Julieta Shem writes: >>Any book recomendations on getting this thing mathematics-clear? > > OOP cannot be mathematics-clear because it is an /attempt/ to > abstract from several different programming languages. > > When you ask Alan Kay (and I did!), the man who coined the term > "object-oriented", he will tell you (in my words): > "Object-oriented programming is possible in Smalltalk only.". That's very interesting. Would you share the complete thread of e-mail? I would love to read it word for word. > So, to get OOP crystal clear from the one who coined the > term, go ahead an learn Smalltalk! After your message, I looked up THE EARLY HISTORY OF SMALLTALK https://dl.acm.org/doi/pdf/10.1145/234286.1057828 and gave it a read. Very nice read. > But while Kay coined the term, many ideas of OOP are based > on Simula. So, you might think about learning Simula to get > the Dahl-flavor of OOP. > > This is comp.lang.python. Here we do Python programming. The impression I got from Smalltalk in the paper above was that Python is so much based on it. > 10 or 20 years ago there were still famous people, such as > Robert C. Martin, hanging around in "comp.object", and I would > have told you to go there, but today that newsgroup is deserted. So sad. > Here's an excerpt from an older post by me, written in May this year: > > In 2003, I became aware of the fact that Alan Kay, the man > who coined the term "object-oriented programming" in 1967 > (or in the temporal proximity of this year), never has given > a definition for it. I asked him via e-mail, and he kindly > responded. In that e-mail he also wrote something to the effect > that for him only Smalltalk allows object-oriented programming. > (On another occasion, he also said, "I invented the term Object- > Oriented and I can tell you I did not have C++ in mind.".) So, > I think that this point of view by Alan Kay is similar to what > Liam wrote about Smalltalk! > > So, what did Alan Kay write to me in 2003? Here's the crucial excerpt: > > |OOP to me means only messaging, local retention and protection and > |hiding of state-process, and extreme late-binding of all things. It > |can be done in Smalltalk and in LISP. There are possibly other > |systems in which this is possible, but I'm not aware of them. > Alan Kay, 2003 I'm wondering how Python fails to satisfy his definition. > . I should add that the deepest insight I gained into what is the > actual point of OOP (as I wrote in my previous post in this thread) > I got from the writings of Robert C. Martin who clarified that > OOP makes it easy to add new types but hard to add new operations, > while procedural programming makes it easy to add new operations, > but hard to add new types. > > |Procedural code (code using data structures) makes it easy to > |add new functions without changing the existing data > |structures. OO code, on the other hand, makes it easy to add > |new classes without changing existing functions. > Robert Cecil Martin > > |Procedural code makes it hard to add new data structures > |because all the functions must change. OO code makes it hard > |to add new functions because all the classes must change. > Robert Cecil Martin > > When one first reads this, it might not be obvious why this > is so spot on, but one can find this quotation in the book > "Clean Code" by Robert C. Martin and read more explanations > about it there. Thank you for the reference. His comments make sense to me, although it's not crystal-clear. I'll eventually read his book. > Objects with data abstraction can already be found in CLU by > Barbara Liskov. But this is not yet OOP. The crucial feature > OOP adds to this is polymorphism ("late binding"). That's helpful. I saw Alan Kay talking about late binding in the paper I mentioned above. Thank you so much. From jshem at yaxenu.org Wed Nov 2 20:35:01 2022 From: jshem at yaxenu.org (Julieta Shem) Date: Wed, 02 Nov 2022 21:35:01 -0300 Subject: [correction]an oop question References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <86leoufl6e.fsf@yaxenu.org> Message-ID: <86y1ssdgei.fsf@yaxenu.org> Dennis Lee Bieber writes: > On 2 Nov 2022 09:56:28 GMT, ram at zedat.fu-berlin.de (Stefan Ram) declaimed > the following: > > >> Now, in the next program, I have removed the subclassings, >> there is no inheritance from the base class "Language" >> anymore. Yet the polymorphism in "f" still works. And this >> shows that in Python we do *not* need subclassing/inheritance >> for polymorphism! >> > To me, that is not really an example of polymorphism, but more an > example of Python's "duck typing". > > I'd implement the example hierarchy as > >>>> class Language: > ... def f(self): > ... print(self.greeting) > ... >>>> class English(Language): > ... def __init__(self): > ... self.greeting = "Good Morning" > ... >>>> class French(Language): > ... def __init__(self): > ... self.greeting = "Bonjour" > ... >>>> English().f() > Good Morning >>>> French().f() > Bonjour > > ... with no explicit /function/ for greeting -- it's just an attribute > set in each subtype, inheriting the "f" function for printing. A popular encyclopedia would enumerate various specifications of the word polymorphism. Ad hoc polymorphism, parametric polymorphim, subtype polymorphim et cetera. ``One of the most difficult matters in all controversy is to distinguish disputes about words from disputes about facts: it ought not to be difficult, but in practice it is.'' -- ABC of Relativity, Bertrand Russell, chapter 12, 1925. ``What's in a name?'' -- Romeo and Juliet, Shakespeare, 1597. From jshem at yaxenu.org Wed Nov 2 20:37:51 2022 From: jshem at yaxenu.org (Julieta Shem) Date: Wed, 02 Nov 2022 21:37:51 -0300 Subject: an oop question References: <86y1sxmmvo.fsf@yaxenu.org> <86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org> <86v8o0hlno.fsf@yaxenu.org> <86h6zih8jb.fsf@yaxenu.org> <86sfj2fl9u.fsf@yaxenu.org> Message-ID: <86pme4dg9s.fsf@yaxenu.org> Greg Ewing writes: > On 2/11/22 9:54 am, Julieta Shem wrote: >> But we've left behind a more basic requirement --- the Stack >> class wishes for all the methods already written in some class called >> Pair, > > Is that *really* what you want, though? > > To my way of thinking, a Stack and a Pair are quite different > data structures, each having their own characteristic operations. > > Things I want to be able to do with a Stack: > - Create an empty stack > - Push an item onto the top of the stack > - Pop an item off the top of the stack > > Things I want to be able to do with a Pair: > - Create a pair containing two given objects > - Get the first item > - Get the second item > > I don't see any overlap between these at the conceptual level. > Possibly I might want to use Pairs as part of the *implementation* > of a stack, but that doesn't mean that any Pair methods should > appear as Stack methods. The code for computing the length of a Pair (which is really a linked list) happens to be the same for computing the length of a Stack. My class Pair has methods map, filter, reduce, ... Stacks could use them too. > Here's how I might do this in a functional style using Python: > > class Pair: > def __init__(self, first, second): > self._first = first > self._second = second > def first(self): > return self._first > def second(self): > return self._second > > class Stack: > def __init__(self): > self._data = None > def push(self, item): > result = Stack() > result._data = Pair(item, self._data) > return result > def pop(self): > rest = Stack() > rest._data = self._data.second() > return self._data.first(), rest > > Note that neither Stack nor Pair inherits from the other. That works too. From jshem at yaxenu.org Wed Nov 2 20:45:46 2022 From: jshem at yaxenu.org (Julieta Shem) Date: Wed, 02 Nov 2022 21:45:46 -0300 Subject: an oop question References: <86y1sxmmvo.fsf@yaxenu.org> <86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org> <86v8o0hlno.fsf@yaxenu.org> <86h6zih8jb.fsf@yaxenu.org> <86sfj2fl9u.fsf@yaxenu.org> Message-ID: <86a658dfwl.fsf@yaxenu.org> ram at zedat.fu-berlin.de (Stefan Ram) writes: > Greg Ewing writes: >>I don't see any overlap between these at the conceptual level. > > It might come from early LISP dialects. In early LISPs, the > only basic means to combine data into a larger assembly of > data was the dotted pair and NULL (as an end marker). So, > whenever you wanted to create a data structure, you would > wonder how to build it from dotted pairs and NULLs. > > You also had lists, of course, but these were themselves build > from dotted pairs and NULLs, as I explained in a recent post. > > (I wrote "early LISP", because I don't know much about modern > "Lisp" dialects.) > > And when people learn a new (programming) language, until they > become more confident in it, they start to emulate their > previous language(s) in it. Writing FORTRAN in Pascal, and > so on. So when you know Clojure and then come to Python, you > might wonder how to do Clojure things in Python. (Clojure > is a kind of Lisp.) And that's very interesting. It's a nice evidence of that conjecture that the languages we use affect the way we see things. Noam Chomsky has been saying that the primary function of language is to be a tool of thought rather than communication; communication is definitely important and real, but not the primary reason why language was developed. From jshem at yaxenu.org Wed Nov 2 20:53:33 2022 From: jshem at yaxenu.org (Julieta Shem) Date: Wed, 02 Nov 2022 21:53:33 -0300 Subject: an oop question References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <49e71d27-8a6b-bfe7-95e7-dc3b8cb83ea5@yahoo.co.uk> Message-ID: <86tu3gc0z6.fsf@yaxenu.org> Alan Gauld writes: > On 01/11/2022 17:58, Julieta Shem wrote: [...] >>> IS-A relationship, so Stack inheriting Pair would mean that a Stack >>> was a Pair. That is not really true. >> >> That's another interesting observation. I do not have much >> understanding of how to really think of these things > > Read up on the Liskoff substitution principle as one approach to > determining what an IS-A relationship means. Its not the only > approach but it is less vague than some others! Thanks so much for the references. I'll definitely look up the Liskov substitution principle and try to understand it. More on this soon. Thanks also for the Meyer's reference too, the explanation of ``delegation'' and all your comments. I appreciate it. From greg.ewing at canterbury.ac.nz Wed Nov 2 21:47:31 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Thu, 3 Nov 2022 14:47:31 +1300 Subject: an oop question In-Reply-To: <86pme4dg9s.fsf@yaxenu.org> References: <86y1sxmmvo.fsf@yaxenu.org> <86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org> <86v8o0hlno.fsf@yaxenu.org> <86h6zih8jb.fsf@yaxenu.org> <86sfj2fl9u.fsf@yaxenu.org> <86pme4dg9s.fsf@yaxenu.org> Message-ID: On 3/11/22 1:37 pm, Julieta Shem wrote: > The code for computing the length of a Pair (which is really a linked > list) happens to be the same for computing the length of a Stack. I would question whether that should be a method of Pair at all, since it's not the length of the pair itself, but the length of a structure built out of pairs. But in any case, the way to do this in a conceptually clean way is for the length method of Stack to call whatever it is that computes the length of a linked list of Pairs. This is what the term "delegation" refers to. -- Greg From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Wed Nov 2 23:24:19 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Thu, 3 Nov 2022 03:24:19 +0000 Subject: typing: property/setter and lists? Message-ID: Hi! And a typing problem again!!! _______________________________________ class C: def __init__(self): self.__foos=5*[0] @property def foos(self) -> list[int]: return self.__foos @foos.setter def foos(self,v: int): self.__foos=[v for __i in self.__foos] c=C() c.foos=5 print(c.foos) _______________________________________ mypy gives the following error: error: Incompatible types in assignment (expression has type "int", variable has type "List[int]") How do I turn around this? Thanks. Paulo From PythonList at DancesWithMice.info Thu Nov 3 03:55:43 2022 From: PythonList at DancesWithMice.info (dn) Date: Thu, 3 Nov 2022 20:55:43 +1300 Subject: typing: property/setter and lists? In-Reply-To: References: Message-ID: On 03/11/2022 16.24, Paulo da Silva wrote: > class C: > ????def __init__(self): > ??????? self.__foos=5*[0] > > ????@property > ????def foos(self) -> list[int]: > ??????? return self.__foos > > ????@foos.setter > ????def foos(self,v: int): > ??????? self.__foos=[v for __i in self.__foos] > > c=C() > c.foos=5 > print(c.foos) > _______________________________________ > > mypy gives the following error: > error: Incompatible types in assignment (expression has type "int", > variable has type "List[int]") To help us to help you please copy-paste the *exact* message - especially which line is in-question. The above code passes without complaint in PyCharm, and executes. However, the general rule?convention would be to establish type at the first mention of the identifier, eg def __init__(self): self.__foos:list[int] = 5 * [ 0 ] # or [ 0, 0, 0, 0, 0, ] Why the "__i", and not "i", or "_"? -- Regards, =dn From __peter__ at web.de Thu Nov 3 04:53:20 2022 From: __peter__ at web.de (Peter Otten) Date: Thu, 3 Nov 2022 09:53:20 +0100 Subject: typing: property/setter and lists? In-Reply-To: References: Message-ID: <56add15e-90d9-c250-1062-0b7d3a3e6f72@web.de> On 03/11/2022 04:24, Paulo da Silva wrote: > Hi! > > And a typing problem again!!! > _______________________________________ > class C: > ????def __init__(self): > ??????? self.__foos=5*[0] > > ????@property > ????def foos(self) -> list[int]: > ??????? return self.__foos > > ????@foos.setter > ????def foos(self,v: int): > ??????? self.__foos=[v for __i in self.__foos] > > c=C() > c.foos=5 > print(c.foos) > _______________________________________ > > mypy gives the following error: > error: Incompatible types in assignment (expression has type "int", > variable has type "List[int]") > > How do I turn around this? Quoting https://github.com/python/mypy/issues/3004: """ gvanrossum commented on Mar 15, 2017 IIRC we debated a similar issues when descriptors were added and decided that it's a perverse style that we just won't support. If you really have this you can add # type: ignore. """ From learn2program at gmail.com Thu Nov 3 06:43:28 2022 From: learn2program at gmail.com (Alan Gauld) Date: Thu, 3 Nov 2022 10:43:28 +0000 Subject: an oop question In-Reply-To: <865yfwevet.fsf@yaxenu.org> References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <865yfwevet.fsf@yaxenu.org> Message-ID: On 03/11/2022 00:25, Julieta Shem wrote: >> |OOP to me means only messaging, local retention and protection and >> |hiding of state-process, and extreme late-binding of all things. > > I'm wondering how Python fails to satisfy his definition. Python doesn't do any form of data protection/hiding. All attributes are public by default. In Smalltalk all attributes are private, with no way to make them public... Actually in C++/Java terms I believe they are "protected" because subclasses can access them(I think?). Also Python is not a purely OOP language, in that you can write functional and procedural code in Python if you wish. In Smalltalk thats notionally impossible because everything is an object. And all programming statements are messages to objects. Even an if/else test is a message to the boolean object: (5>3) ifTrue: ifFalse: ifTrue is a message to the boolean result of the expression which has a parameter of a block of code. It executes the block if the boolean is true. ifFalse is likewise a message to the same boolean object but only executes its block if the boolean is false. (Apologies if the syntax is out, its been a while since I wrote any Smalltalk!) Similarly loops are implemented as messages: whileTrue: to: do: So in Smalltalk absolutely everything is a message to an object. Python by comparison is much more traditional in form. It is possible to write procedural, non OOP code in Smalltalk but you really have to fight the system to do so. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From gweatherby at uchc.edu Thu Nov 3 07:07:19 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Thu, 3 Nov 2022 11:07:19 +0000 Subject: an oop question In-Reply-To: References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <865yfwevet.fsf@yaxenu.org> Message-ID: C++/Java class variables can be public, protected (accessible to class and subclasses) or private (accessible only to class). Of course the language protections can be hacked around. Python does conceptual private variables by using the single underscore: object._myvar is considered private From: Python-list on behalf of Alan Gauld Date: Thursday, November 3, 2022 at 6:45 AM To: Julieta Shem , python-list at python.org Subject: Re: an oop question *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** On 03/11/2022 00:25, Julieta Shem wrote: >> |OOP to me means only messaging, local retention and protection and >> |hiding of state-process, and extreme late-binding of all things. > > I'm wondering how Python fails to satisfy his definition. Python doesn't do any form of data protection/hiding. All attributes are public by default. In Smalltalk all attributes are private, with no way to make them public... Actually in C++/Java terms I believe they are "protected" because subclasses can access them(I think?). From rosuav at gmail.com Thu Nov 3 07:50:23 2022 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 3 Nov 2022 22:50:23 +1100 Subject: an oop question In-Reply-To: References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <865yfwevet.fsf@yaxenu.org> Message-ID: On Thu, 3 Nov 2022 at 21:44, Alan Gauld wrote: > Also Python is not a purely OOP language, in that you can write > functional and procedural code in Python if you wish. In > Smalltalk thats notionally impossible because everything > is an object. And all programming statements are messages > to objects. In Python, everything is an object. Doesn't that equally mean that Python is purely OOP? ChrisA From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Thu Nov 3 01:32:18 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Thu, 3 Nov 2022 05:32:18 +0000 Subject: typing: property/setter and lists? [RESOLVED] References: Message-ID: ?s 03:24 de 03/11/22, Paulo da Silva escreveu: > Hi! > > And a typing problem again!!! > _______________________________________ > class C: > ????def __init__(self): > ??????? self.__foos=5*[0] > > ????@property > ????def foos(self) -> list[int]: > ??????? return self.__foos > > ????@foos.setter > ????def foos(self,v: int): > ??????? self.__foos=[v for __i in self.__foos] > > c=C() > c.foos=5 > print(c.foos) > _______________________________________ > > mypy gives the following error: > error: Incompatible types in assignment (expression has type "int", > variable has type "List[int]") > > How do I turn around this? > Changing def foos(self) -> list[int]: to def foos(self) -> Union[list[int]]: fixes the problem. Not so elegant, however! Regards. Paulo From jshem at yaxenu.org Thu Nov 3 08:29:20 2022 From: jshem at yaxenu.org (Julieta Shem) Date: Thu, 03 Nov 2022 09:29:20 -0300 Subject: an oop question References: <86y1sxmmvo.fsf@yaxenu.org> <86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org> <86v8o0hlno.fsf@yaxenu.org> <86h6zih8jb.fsf@yaxenu.org> <86sfj2fl9u.fsf@yaxenu.org> <86pme4dg9s.fsf@yaxenu.org> Message-ID: <86iljwb4rj.fsf@yaxenu.org> Greg Ewing writes: > On 3/11/22 1:37 pm, Julieta Shem wrote: >> The code for computing the length of a Pair (which is really a linked >> list) happens to be the same for computing the length of a Stack. > > I would question whether that should be a method of Pair at all, > since it's not the length of the pair itself, but the length of > a structure built out of pairs. You make a lot of sense. > But in any case, the way to do this in a conceptually clean way > is for the length method of Stack to call whatever it is that > computes the length of a linked list of Pairs. This is what > the term "delegation" refers to. Thank you for the example. I agree with you. Perhaps I can reduce the class Pair to just being a pair as we know it, made of two things, then we create a class called Sequence, which is really a composition of Pairs, comes with a length method and we derive Stack from it. From jshem at yaxenu.org Thu Nov 3 08:41:54 2022 From: jshem at yaxenu.org (Julieta Shem) Date: Thu, 03 Nov 2022 09:41:54 -0300 Subject: an oop question References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <865yfwevet.fsf@yaxenu.org> Message-ID: <86bkpob46l.fsf@yaxenu.org> ram at zedat.fu-berlin.de (Stefan Ram) writes: > Julieta Shem writes: >>That's very interesting. Would you share the complete thread of e-mail? >>I would love to read it word for word. > > Yes, with pleasure! A quotation from my corresponding web page: > > (For technical reasons, the web page today gives > "https://www.purl.org/stefan_ram/pub/doc_kay_oop_en" as the > "canonical URI", but both should work. I prefer the old one > with "http:", but am afraid that one day "http" might stop > to work.) [...] Nice! Thank you so much! From jshem at yaxenu.org Thu Nov 3 08:57:57 2022 From: jshem at yaxenu.org (Julieta Shem) Date: Thu, 03 Nov 2022 09:57:57 -0300 Subject: an oop question References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <865yfwevet.fsf@yaxenu.org> Message-ID: <8635b0b3fu.fsf@yaxenu.org> Chris Angelico writes: > On Thu, 3 Nov 2022 at 21:44, Alan Gauld wrote: >> Also Python is not a purely OOP language, in that you can write >> functional and procedural code in Python if you wish. In >> Smalltalk thats notionally impossible because everything >> is an object. And all programming statements are messages >> to objects. > > In Python, everything is an object. Doesn't that equally mean that > Python is purely OOP? I think Alan Gauld pointed out that even syntax is an object in Smalltalk --- or was. An if-statement in Python is not an object. From sureshbabu22061980 at gmail.com Thu Nov 3 11:20:24 2022 From: sureshbabu22061980 at gmail.com (Suresh Babu) Date: Thu, 3 Nov 2022 20:50:24 +0530 Subject: Fwd: Issues in python 3.11.0 (64-bit) installation In-Reply-To: References: Message-ID: ---------- Forwarded message --------- From: Suresh Babu Date: Thu, 3 Nov 2022, 16:37 Subject: Issues in python 3.11.0 (64-bit) installation To: Sir/ Madam, I downloaded the latest version of python i.e. python 3.11.0 ( 64-bit) in my laptop recently. But the " py launcher " and " available for all users " option is not working in the customization menu of python 3.11.0 . Kindly help me in solving this issue. My operating system is Windows 11. Kindly guide me in this regard. Yours sincerely, Sureshbabu. From rosuav at gmail.com Thu Nov 3 14:16:59 2022 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 4 Nov 2022 05:16:59 +1100 Subject: typing: property/setter and lists? [RESOLVED] In-Reply-To: References: Message-ID: On Fri, 4 Nov 2022 at 05:03, Paulo da Silva wrote: > Changing def foos(self) -> list[int]: to > def foos(self) -> Union[list[int]]: > fixes the problem. > Not so elegant, however! Wait, what?! Union[X, Y] means "X or Y" Union[X] means "X, but don't complain if it's a @property". Is that how it goes? ChrisA From rosuav at gmail.com Thu Nov 3 14:29:25 2022 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 4 Nov 2022 05:29:25 +1100 Subject: an oop question In-Reply-To: <8635b0b3fu.fsf@yaxenu.org> References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <865yfwevet.fsf@yaxenu.org> <8635b0b3fu.fsf@yaxenu.org> Message-ID: On Fri, 4 Nov 2022 at 05:21, Julieta Shem wrote: > > Chris Angelico writes: > > > On Thu, 3 Nov 2022 at 21:44, Alan Gauld wrote: > >> Also Python is not a purely OOP language, in that you can write > >> functional and procedural code in Python if you wish. In > >> Smalltalk thats notionally impossible because everything > >> is an object. And all programming statements are messages > >> to objects. > > > > In Python, everything is an object. Doesn't that equally mean that > > Python is purely OOP? > > I think Alan Gauld pointed out that even syntax is an object in > Smalltalk --- or was. An if-statement in Python is not an object. Okay, fair; although I would be highly surprised if syntax is actually an object ("flow control is an object", I would believe, though). Is the concept "pass this message to this object" an object? Is the message itself an object? Is it objects all the way down? At some point, any language with objects in it is "object oriented" to some extent, and after that, it's all a spectrum. Some people claim that Java is "more object-oriented" than Python because all Java code has to be in a class, and others counteract by saying that Python is "more object-oriented" because every value in Python is a subclass of object and has a type which is a subclass of type. I'm sure that someone somewhere has claimed that Python "isn't object-oriented" on the basis that len(x) is the WRONG way to put it, and it should be x.length() instead. On second thoughts, it's not a single spectrum, it's a multidimensional thing that's so tangled up that it guarantees that people can happily debate for years to come. ChrisA From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Thu Nov 3 14:35:21 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Thu, 3 Nov 2022 18:35:21 +0000 Subject: typing: property/setter and lists? [RESOLVED ERRATA] References: Message-ID: ?s 05:32 de 03/11/22, Paulo da Silva escreveu: > ?s 03:24 de 03/11/22, Paulo da Silva escreveu: >> Hi! >> >> And a typing problem again!!! >> _______________________________________ >> class C: >> ?????def __init__(self): >> ???????? self.__foos=5*[0] >> >> ?????@property >> ?????def foos(self) -> list[int]: >> ???????? return self.__foos >> >> ?????@foos.setter >> ?????def foos(self,v: int): >> ???????? self.__foos=[v for __i in self.__foos] >> >> c=C() >> c.foos=5 >> print(c.foos) >> _______________________________________ >> >> mypy gives the following error: >> error: Incompatible types in assignment (expression has type "int", >> variable has type "List[int]") >> >> How do I turn around this? >> > Changing def foos(self) -> list[int]:? to > ?def foos(self) -> Union[list[int]]: I meant, of course, def foos(self) -> Union[list[int],int]: Sorry. Paulo From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Thu Nov 3 14:37:43 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Thu, 3 Nov 2022 18:37:43 +0000 Subject: typing: property/setter and lists? [RESOLVED] References: Message-ID: ?s 18:16 de 03/11/22, Chris Angelico escreveu: > On Fri, 4 Nov 2022 at 05:03, Paulo da Silva > wrote: >> Changing def foos(self) -> list[int]: to >> def foos(self) -> Union[list[int]]: >> fixes the problem. >> Not so elegant, however! > > Wait, what?! > > Union[X, Y] means "X or Y" > Union[X] means "X, but don't complain if it's a @property". > > Is that how it goes? I'm sorry. A bad transposition of the text. I meant def foos(self) -> Union[list[int],int]: Regards. Paulo From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Thu Nov 3 14:42:35 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Thu, 3 Nov 2022 18:42:35 +0000 Subject: typing: property/setter and lists? References: Message-ID: ?s 07:55 de 03/11/22, dn escreveu: > On 03/11/2022 16.24, Paulo da Silva wrote: >> class C: >> ?????def __init__(self): >> ???????? self.__foos=5*[0] >> >> ?????@property >> ?????def foos(self) -> list[int]: >> ???????? return self.__foos >> >> ?????@foos.setter >> ?????def foos(self,v: int): >> ???????? self.__foos=[v for __i in self.__foos] >> >> c=C() >> c.foos=5 >> print(c.foos) >> _______________________________________ >> >> mypy gives the following error: >> error: Incompatible types in assignment (expression has type "int", >> variable has type "List[int]") > > > To help us to help you please copy-paste the *exact* message - > especially which line is in-question. > > > The above code passes without complaint in PyCharm, and executes. > > > However, the general rule?convention would be to establish type at the > first mention of the identifier, eg > > def __init__(self): > ??? self.__foos:list[int] = 5 * [ 0 ] > # or [ 0, 0, 0, 0, 0, ] > > > Why the "__i", and not "i", or "_"? Just because of my personal taste. I know that __ means (for me) a "not used anymore" var and i is an indexer/counter/... Regards. Paulo From rosuav at gmail.com Thu Nov 3 14:50:49 2022 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 4 Nov 2022 05:50:49 +1100 Subject: typing: property/setter and lists? [RESOLVED ERRATA] In-Reply-To: References: Message-ID: On Fri, 4 Nov 2022 at 05:48, Paulo da Silva wrote: > > ?s 05:32 de 03/11/22, Paulo da Silva escreveu: > > ?s 03:24 de 03/11/22, Paulo da Silva escreveu: > >> Hi! > >> > >> And a typing problem again!!! > >> _______________________________________ > >> class C: > >> def __init__(self): > >> self.__foos=5*[0] > >> > >> @property > >> def foos(self) -> list[int]: > >> return self.__foos > >> > >> @foos.setter > >> def foos(self,v: int): > >> self.__foos=[v for __i in self.__foos] > >> > >> c=C() > >> c.foos=5 > >> print(c.foos) > >> _______________________________________ > >> > >> mypy gives the following error: > >> error: Incompatible types in assignment (expression has type "int", > >> variable has type "List[int]") > >> > >> How do I turn around this? > >> > > Changing def foos(self) -> list[int]: to > > def foos(self) -> Union[list[int]]: > I meant, of course, > def foos(self) -> Union[list[int],int]: > Ohhh! I thought this was triggering a strange quirk of the checker in some way... ChrisA From jshem at yaxenu.org Thu Nov 3 14:48:41 2022 From: jshem at yaxenu.org (Julieta Shem) Date: Thu, 03 Nov 2022 15:48:41 -0300 Subject: an oop question References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <865yfwevet.fsf@yaxenu.org> Message-ID: <86wn8ban7a.fsf@yaxenu.org> ram at zedat.fu-berlin.de (Stefan Ram) writes: > Julieta Shem writes: [...] > 2. a. 1. Remark > > One can observe this ease especially when one defines a new > class with a standard verb and then standard procedures > "magically" use this new method, as in: > > class MyNewClass: > def __str__( self ): > return "Howdy!" > > print( MyNewClass() ) > > How can "print" possibly know about the method "__str__" > I just defined if "print" was written long before I defined > my class? <-- A beginner could ask this in bewilderment! That's a good question. > 2. b. Adding a New Verb (Procedure) in Object-Oriented Programming > > In object-oriented programming adding a new verb (a new > "procedure") is hard. Assume that now we would like to add > another verb such as "emit", say "length". All classes would > have to be changed and a new method definition for "length" > would have to be added to them! Some classes might even be > standard classes from libraries we can't easily change. > So this clearly violates the Open-Closed-Principle! > > 3. Comments > > So, this would suggest to use procedural programming when > one foresees the need to add more object-specific procedures > later and object-oriented programming when one foresees the > need to add more types later. > > The problems with OOP which make adding new verbs violate > the open-closed principle possibly would not occur in > a language where one could add new methods to a library > class in a user program. Thank you! That did clarify everything for me! (I'll find a way to read Martin's book!) From jshem at yaxenu.org Thu Nov 3 14:51:12 2022 From: jshem at yaxenu.org (Julieta Shem) Date: Thu, 03 Nov 2022 15:51:12 -0300 Subject: an oop question References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <49e71d27-8a6b-bfe7-95e7-dc3b8cb83ea5@yahoo.co.uk> <86tu3gc0z6.fsf@yaxenu.org> Message-ID: <86mt97an33.fsf@yaxenu.org> ram at zedat.fu-berlin.de (Stefan Ram) writes: > Julieta Shem writes: >> I'll definitely look up the Liskov >>substitution principle and try to understand it. > > I found the LSP to be very confusing: > > First, it's was hard for me to actually get a clear source > (citation) for it. What exactly are the words of Barbara > Liskov that are called "LSP"? > > Then, I found some words that that might possibly be the LSP > in the words of Barbara Liskov: > > |If for each object o1 of type S there is an object o2 of > |type T such that for all programs P defined in terms of T, > |the behavior of P is unchanged when o1 is substituted for o2 > |then S is a subtype of T. > > This uses nested quantifiers, somewhat like > > ( ?(o1?S) ?(o2?T) ?(P?P(T)) B(P(o2))=(P(o1)) )==> S < T > > . And such a proposition is hard for me to understand! For me too. > Later, I looked at a book in a bookstore; it was a book > about programming by Barbara Liskov that came out after the > LSP was already mentioned often, and as far as I could see, > that book did not mention the LSP at all, although it > actually had a chapter about subtypes! Do you remember the book's title? > So, here's my personal principle, that I use instead of the LSP: > > An object-oriented program is not complete without proper > documentation, i.e., contracts. The documentation of a class > must be true for all objects of this class and for all objects > of all direct and indirect subclasses. That's much easier to ``parse'' indeed. Thanks for the contribution. (The empty documentation seems to satisfy the principle.) > . If this was too long, one could abbreviate this to just: > > Class contracts must hold for subclasses. > > . I think the original LSP unfortunately tried to avoid > references to contracts and just talks about code. From eryksun at gmail.com Thu Nov 3 17:50:16 2022 From: eryksun at gmail.com (Eryk Sun) Date: Thu, 3 Nov 2022 16:50:16 -0500 Subject: Problems with IDLE in Windows 8.1 and installer x86 Version 3.10.8 In-Reply-To: <202211032129.2A3LTmtc065950@mail193c50.megamailservers.eu> References: <202210311822.29VIMTpw130438@mail92c50.megamailservers.eu> <202210312138.29VLcBUQ008124@mail118c50.megamailservers.eu> <202211011649.2A1GnNrU115152@mail36c50.megamailservers.eu> <202211032129.2A3LTmtc065950@mail193c50.megamailservers.eu> Message-ID: On 11/3/22, darkstone at o2online.de wrote: > Is there a reason, why it is not installed? Its the same check mark in the > installer like IDLE? Did you try what I suggested? Modify the installation to remove the tkinter/IDLE component. Then modify it again to select the component to be reinstalled. Also, try to repair the installation. This may reset any DLLs or extension modules that were missing or that were the wrong version. Ignore the suggestion from Nithish to install tkinter via pip. tkinter is part of the standard library and cannot be installed via pip. There is no tkinter package on the Python package index (pypi.org). From learn2program at gmail.com Thu Nov 3 20:09:59 2022 From: learn2program at gmail.com (Alan Gauld) Date: Fri, 4 Nov 2022 00:09:59 +0000 Subject: an oop question In-Reply-To: References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <865yfwevet.fsf@yaxenu.org> <8635b0b3fu.fsf@yaxenu.org> Message-ID: On 03/11/2022 18:29, Chris Angelico wrote: > On Fri, 4 Nov 2022 at 05:21, Julieta Shem wrote: >> >> Chris Angelico writes: >> >>> On Thu, 3 Nov 2022 at 21:44, Alan Gauld wrote: >>>> Also Python is not a purely OOP language, in that you can write >>>> functional and procedural code in Python if you wish. In >>>> Smalltalk thats notionally impossible because everything >>>> is an object. And all programming statements are messages >>>> to objects. >>> >>> In Python, everything is an object. Doesn't that equally mean that >>> Python is purely OOP? >> >> I think Alan Gauld pointed out that even syntax is an object in >> Smalltalk --- or was. An if-statement in Python is not an object. > > Okay, fair; although I would be highly surprised if syntax is actually > an object The syntax isn't, it is a specification, but the AST certainly is and you can instantiate it and examine it from code. But the context here was Why *Alan Kay* doesn't include Python with Smalltalk as being OOP. There are plenty others who would call it so. But as for everything being an object, that's true but it doesn't alter the fact that the default mode of python programming is not to structure the code as a set of communicating objects (even if at some level everything is an object) but as a set of hierarchical functions. And fundamentally that's what Kay means by OOP. The program (not the language!) is built around objects. One of the greatest barriers to the adoption of OOP is the confusion between OOP and OOPL. And sadly the majority of attention has been on OOPL rather than OOP... > the concept "pass this message to this object" an object? Is the > message itself an object? Is it objects all the way down? At some point you hit C/Assembler. But it is astonishing just how far down the objects go in Smalltalk. But the control flow etc are fully OOP as per my last message. It if quite possible to subclass Boolean and override the whileTrue method to do something completely different to the normal while loop behaviour. Is it wise? No. But it is definitely possible! > At some point, any language with objects in it is "object oriented" to > some extent, and after that, it's all a spectrum. And this is exactly the problem. In the 80s we had a fairly clean concensus of what OOP meant and several different language approaches to that. But when C++ became popular(the defacto standard) peple started focussing on the language features and totally missed that Object Oriented Programming means writing programs that consist of objects communicating by messages. The language features(even classes) are merely implementation details. (I suspect this was partly driven by the fact that many university lecturers at the time didn't really grok OOP and teaching language features was much easier than teaching a new way of thinking about problems!) This was compounded when someone (Booch maybe?) came up with a set of criteria to determine whether a language was a "true OOPL" or merely "Object Based" (Ada and VB they're looking at you!) But frankly that was an irrelevance to OOP. You can do OOP (and I have!) in assembler and in COBOL - you just need to follow some agreed ground rules. It's a lot easier with an OOPL but it's not required. > multidimensional thing that's so tangled up that it guarantees that > people can happily debate for years to come. Exactly so. During the 90's there came to be at least 3 different camps of OOP evangelists and the OOP world slowly coalesced on a kind of hybrid amalgam with multiple names for the same feature and disagrements about which features are required or not to really be OOP. And as a result the whole concept of OOP has been muddied to the point that almost nobody does it anymore apart from (possibly) the Smalltalk crowd who have always smugly sat above the general throng content in the knowledge that theirs is the one true OOP! :-) Which brings us back to Alan Kay... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From PythonList at DancesWithMice.info Thu Nov 3 20:27:33 2022 From: PythonList at DancesWithMice.info (dn) Date: Fri, 4 Nov 2022 13:27:33 +1300 Subject: Challenge-week 4: Groups of solutions, starts today! Message-ID: <7191bb6d-6334-8eb3-127f-e9603589cf6a@DancesWithMice.info> A virtual event run by the Auckland Branch of the New Zealand Python Users' Group. Details from the Meetup site: https://www.meetup.com/nzpug-auckland/events/289531194/ where you may also sign-up. It's Week 4 of the Smart Iterator Challenge! We've looked at taking our early results and generalising them to suit various solutions. The next view is how a range of similar solutions might be grouped - and re-shaped to enable us to re-use and share code. We commence with a review of Challenge-week 3 and sample-code to download and compare with your own efforts. This time there is no tutorial-content. Even the provided testing/proofs are rather sparse - and really only there to make sure you're on-the-right-track. In many ways, the challenge is not so much writing code, as it is designing code-solutions. Putting code-modules together, and then pulling them apart to satisfy groups of solutions. Ooh mysterious! This Challenge will interest Python-Journeymen, and Python-Apprentices ready to move-on from ?the basics?. As usual, there are "Extra Credit" challenges which will 'push' Python-Masters and advanced Journeymen. It's not a requirement that you have completed the previous challenges - but they will help. Challenge-week 4 starts with either your own or a provided template-script. So, you don't have to have completed Challenge-weeks 1, 2, and 3 (but it would help - there's nothing to stop you from 'catching up' and gaining full benefit from the exercise). There's some 'template code' which will enable starting from this week. Challenge Schedule: Groups of solutions Starting: Sat 5 Nov Office Hours: 1830*, Wed 9 Nov Concluding: midnight after Sun 13 Nov * all times NZDT (UTC+13) Are you up for a challenge? Regards =dn (for Pete and DJ) From gweatherby at uchc.edu Thu Nov 3 21:19:37 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Fri, 4 Nov 2022 01:19:37 +0000 Subject: an oop question In-Reply-To: References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <865yfwevet.fsf@yaxenu.org> <8635b0b3fu.fsf@yaxenu.org> Message-ID: https://www.oreilly.com/library/view/beginning-c-30/9780470261293/9780470261293_a_short_history_of_object-oriented_progr.html From PythonList at DancesWithMice.info Thu Nov 3 21:44:18 2022 From: PythonList at DancesWithMice.info (dn) Date: Fri, 4 Nov 2022 14:44:18 +1300 Subject: Fwd: Issues in python 3.11.0 (64-bit) installation In-Reply-To: References: Message-ID: On 04/11/2022 04.20, Suresh Babu wrote: > I downloaded the latest version of python i.e. python 3.11.0 ( 64-bit) > in my laptop recently. But the " py launcher " and " available for all > users " option is not working in the customization menu of python 3.11.0 . > Kindly help me in solving this issue. > > My operating system is Windows 11. Kindly guide me in this regard. Has the documentation left questions? https://docs.python.org/3/using/windows.html -- Regards, =dn From list1 at tompassin.net Thu Nov 3 22:29:12 2022 From: list1 at tompassin.net (Thomas Passin) Date: Thu, 3 Nov 2022 22:29:12 -0400 Subject: Fwd: Issues in python 3.11.0 (64-bit) installation In-Reply-To: References: Message-ID: I just downloaded the 64-bit Windows installer. On my Windows 10 machine, both "py launcher" and "available for all users" options were available. They were available whether I checked the "administrative" box or not. Note that when I unchecked "administrative", then the "available for all users" box became unchecked. That would make sense. When you wrote "option is not working", what did you mean by "not working"? - 1. The options were disabled (i.e., grayed out); 2. The options seemed to be available but the installation seemed to ignore them; 3. The options were completely missing from the wizard; 4. Something else. On 11/3/2022 9:44 PM, dn wrote: > On 04/11/2022 04.20, Suresh Babu wrote: >> ???? I downloaded the latest version of python i.e. python 3.11.0 ( >> 64-bit) >> in my laptop recently. But the " py launcher " and " available for all >> users " option is not working in the customization menu of python >> 3.11.0 . >> Kindly help me in solving this issue. >> >> My operating system is Windows 11. Kindly guide me in this regard. > > Has the documentation left questions? > https://docs.python.org/3/using/windows.html > From PythonList at DancesWithMice.info Fri Nov 4 03:52:24 2022 From: PythonList at DancesWithMice.info (dn) Date: Fri, 4 Nov 2022 20:52:24 +1300 Subject: typing: property/setter and lists? [RESOLVED ERRATA] In-Reply-To: References: Message-ID: <02863bbc-a175-8eda-7775-8837f92d861a@DancesWithMice.info> On 04/11/2022 07.50, Chris Angelico wrote: > On Fri, 4 Nov 2022 at 05:48, Paulo da Silva > wrote: >> >> ?s 05:32 de 03/11/22, Paulo da Silva escreveu: >>> ?s 03:24 de 03/11/22, Paulo da Silva escreveu: >>>> Hi! >>>> >>>> And a typing problem again!!! >>>> _______________________________________ >>>> class C: >>>> def __init__(self): >>>> self.__foos=5*[0] >>>> >>>> @property >>>> def foos(self) -> list[int]: >>>> return self.__foos >>>> >>>> @foos.setter >>>> def foos(self,v: int): >>>> self.__foos=[v for __i in self.__foos] >>>> >>>> c=C() >>>> c.foos=5 >>>> print(c.foos) >>>> _______________________________________ >>>> >>>> mypy gives the following error: >>>> error: Incompatible types in assignment (expression has type "int", >>>> variable has type "List[int]") >>>> >>>> How do I turn around this? >>>> >>> Changing def foos(self) -> list[int]: to >>> def foos(self) -> Union[list[int]]: >> I meant, of course, >> def foos(self) -> Union[list[int],int]: >> > > Ohhh! I thought this was triggering a strange quirk of the checker in > some way... Yes, these personal styles (?quirks) are off-putting to others. Plus "_" means (more or less) "not used anymore" and for most of us, a weak-identifier name such as "i" is indeed "an indexer/counter/... " Accordingly, the question becomes: why not follow the crowd - unless you tell me that this is a team/company convention? ...and whilst I'm griping, "To help us to help you please copy-paste the *exact* message" has been followed by: "I'm sorry. A bad transposition of the text." copy-paste for the win! (and to keep others happy to spend their voluntary time helping you - more working-with-the-team thinking to consider - please) -- Regards, =dn From darkstone at o2online.de Fri Nov 4 10:10:11 2022 From: darkstone at o2online.de (darkstone at o2online.de) Date: Fri, 4 Nov 2022 14:10:11 +0000 Subject: =?utf-8?Q?Re:_Problems_with_IDLE_in_Windows_8.1_and_installer_x86_Version?= =?utf-8?Q?_3.10.8?= In-Reply-To: References: <202210311822.29VIMTpw130438@mail92c50.megamailservers.eu> <202210312138.29VLcBUQ008124@mail118c50.megamailservers.eu> <202211011649.2A1GnNrU115152@mail36c50.megamailservers.eu> <202211032129.2A3LTmtc065950@mail193c50.megamailservers.eu>, Message-ID: <202211041414.2A4EE2xL017716@mail264c50.megamailservers.eu> Yes, there is always the message ?modified successfull?, ?installed sucessfully?, but IDLE does?t start. I tried it with the newer Version, too. Ist 3.11.0 for 32 bit, but it also doesn?t work. Do you have other suggetions, that it works? Von: Eryk Sun Gesendet: ?Donnerstag?, ?3?. ?November? ?2022 ?22?:?50 An: darkstone at o2online.de Cc: python-list at python.org On 11/3/22, darkstone at o2online.de wrote: > Is there a reason, why it is not installed? Its the same check mark in the > installer like IDLE? Did you try what I suggested? Modify the installation to remove the tkinter/IDLE component. Then modify it again to select the component to be reinstalled. Also, try to repair the installation. This may reset any DLLs or extension modules that were missing or that were the wrong version. Ignore the suggestion from Nithish to install tkinter via pip. tkinter is part of the standard library and cannot be installed via pip. There is no tkinter package on the Python package index (pypi.org). From greg.ewing at canterbury.ac.nz Fri Nov 4 03:01:56 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Fri, 4 Nov 2022 20:01:56 +1300 Subject: an oop question In-Reply-To: References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <865yfwevet.fsf@yaxenu.org> Message-ID: On 4/11/22 12:50 am, Chris Angelico wrote: > In Python, everything is an object. Doesn't that equally mean that > Python is purely OOP? Depends on what you mean by "purely oop". To me it suggests a language in which dynamically-dispatched methods are the only form of code. Python is not one of those, because it has stand-alone functions. I'm not sure I know of *any* language that is purely oop in that sense. Smalltalk probably comes the closest, but then its code blocks are essentially lexically-scoped anonymous functions. You *could* write Smalltalk code in a procedural style by assigning a bunch of code blocks to names and calling them like functions. Not that there would be any reason to do that other than as a party trick. Java looks like it's fairly purely OO at first glance, but it has static methods, which are really stand-alone functions by another name. Also it has some primitive types such as ints and floats that don't behave in an OO way at all. -- Greg From greg.ewing at canterbury.ac.nz Fri Nov 4 03:06:37 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Fri, 4 Nov 2022 20:06:37 +1300 Subject: an oop question In-Reply-To: <86mt97an33.fsf@yaxenu.org> References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <49e71d27-8a6b-bfe7-95e7-dc3b8cb83ea5@yahoo.co.uk> <86tu3gc0z6.fsf@yaxenu.org> <86mt97an33.fsf@yaxenu.org> Message-ID: > ram at zedat.fu-berlin.de (Stefan Ram) writes [that Barbara Liskov said]: > >> |If for each object o1 of type S there is an object o2 of >> |type T such that for all programs P defined in terms of T, >> |the behavior of P is unchanged when o1 is substituted for o2 >> |then S is a subtype of T. That seems overly restrictive, because it wouldn't allow S to override a method of T and make it do something different -- which we do all the time in practice. >> Class contracts must hold for subclasses. That sounds like a much better way of saying it! -- Greg From greg.ewing at canterbury.ac.nz Fri Nov 4 03:09:03 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Fri, 4 Nov 2022 20:09:03 +1300 Subject: an oop question In-Reply-To: <86mt97an33.fsf@yaxenu.org> References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <49e71d27-8a6b-bfe7-95e7-dc3b8cb83ea5@yahoo.co.uk> <86tu3gc0z6.fsf@yaxenu.org> <86mt97an33.fsf@yaxenu.org> Message-ID: On 4/11/22 7:51 am, Julieta Shem wrote: > (The empty documentation seems to satisfy the principle.) All the more reason to document your classes! More seriously, there's always at least a (possibly fuzzily) implied contract, because of the names you choose for things if nothing else. -- Greg From greg.ewing at canterbury.ac.nz Fri Nov 4 03:11:50 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Fri, 4 Nov 2022 20:11:50 +1300 Subject: an oop question In-Reply-To: <86iljwb4rj.fsf@yaxenu.org> References: <86y1sxmmvo.fsf@yaxenu.org> <86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org> <86v8o0hlno.fsf@yaxenu.org> <86h6zih8jb.fsf@yaxenu.org> <86sfj2fl9u.fsf@yaxenu.org> <86pme4dg9s.fsf@yaxenu.org> <86iljwb4rj.fsf@yaxenu.org> Message-ID: On 4/11/22 1:29 am, Julieta Shem wrote: > Perhaps I can reduce the > class Pair to just being a pair as we know it, made of two things, then > we create a class called Sequence, which is really a composition of > Pairs, comes with a length method and we derive Stack from it. That sounds better. But be careful -- a Sequence class would probably be expected to have methods for e.g. inserting and removing things in the middle, which you might not want to allow for a Stack. -- Greg From rosuav at gmail.com Fri Nov 4 11:25:00 2022 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 5 Nov 2022 02:25:00 +1100 Subject: an oop question In-Reply-To: References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <865yfwevet.fsf@yaxenu.org> Message-ID: On Sat, 5 Nov 2022 at 02:18, Greg Ewing wrote: > > On 4/11/22 12:50 am, Chris Angelico wrote: > > In Python, everything is an object. Doesn't that equally mean that > > Python is purely OOP? > > Depends on what you mean by "purely oop". To me it suggests a > language in which dynamically-dispatched methods are the only > form of code. Python is not one of those, because it has > stand-alone functions. > Define "stand-alone". In Java, all code has to be associated with a class file, but they can be static methods. A Java-like language in which classes are themselves first-class objects (and thus static methods are instance methods on the class) would, in a sense, have nothing but dynamically-dispatched methods as the only form of code. It wouldn't be materially different from regular Java though (at least, not for the sake of this purity; having first-class classes would probably have other benefits). Pike code, like Java code, is always associated with an object or a program (Pike's name for a class). However, built-in functions (implemented in C) can stand entirely alone. Would Pike become "purely OOP" if all standalone builtins were deemed to be methods of some global object? It wouldn't materially change anything. Maybe it's one of those terms that is useless for actual coding (because practicality beats purity), but good for discussions? Good for arguments, at least. ChrisA From rosuav at gmail.com Fri Nov 4 11:26:53 2022 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 5 Nov 2022 02:26:53 +1100 Subject: an oop question In-Reply-To: References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <49e71d27-8a6b-bfe7-95e7-dc3b8cb83ea5@yahoo.co.uk> <86tu3gc0z6.fsf@yaxenu.org> <86mt97an33.fsf@yaxenu.org> Message-ID: On Sat, 5 Nov 2022 at 02:21, Greg Ewing wrote: > > > ram at zedat.fu-berlin.de (Stefan Ram) writes [that Barbara Liskov said]: > > > >> |If for each object o1 of type S there is an object o2 of > >> |type T such that for all programs P defined in terms of T, > >> |the behavior of P is unchanged when o1 is substituted for o2 > >> |then S is a subtype of T. > > That seems overly restrictive, because it wouldn't allow S to > override a method of T and make it do something different -- > which we do all the time in practice. > > >> Class contracts must hold for subclasses. > > That sounds like a much better way of saying it! > Yeah, I would agree with that latter definition. The trouble is that few programs - and fewer programmers - really define which parts are contracts, so it's much easier to say "a subclass behaves just like the superclass(es) do(es)" - but it would be more accurate to qualify that with "in the ways that the superclass(es) define as standard behaviour". ChrisA From rosuav at gmail.com Fri Nov 4 11:28:54 2022 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 5 Nov 2022 02:28:54 +1100 Subject: Operator: inappropriate wording? In-Reply-To: <61004995-396e-4bb6-bbdd-bd877defc275n@googlegroups.com> References: <4a3bbb16-0d2e-4230-948d-793e5915721an@googlegroups.com> <91181647-7008-4912-86a2-e6f39cda4744n@googlegroups.com> <61004995-396e-4bb6-bbdd-bd877defc275n@googlegroups.com> Message-ID: On Thu, 3 Nov 2022 at 10:17, elas tica wrote: > > Le lundi 31 octobre 2022 ? 22:18:57 UTC+1, Chris Angelico a ecrit : > > Wording is hard. Just ask the SQL standard whether NULL is a value. > > > > Indeed, but I think our problem here is simpler ;) > > One could for example omit the incorrect term "operator" while remaining unambiguous. This would give: Yep. The word "operator" is incorrect when referring to Python's comma (in contrast to, say, C, where the comma actually *is* an operator); and from my understanding, the docs have already been updated to fix this. ChrisA From h.goebel at crazy-compilers.com Fri Nov 4 14:16:18 2022 From: h.goebel at crazy-compilers.com (Hartmut Goebel) Date: Fri, 4 Nov 2022 19:16:18 +0100 Subject: ANN: pdfposter 0.8.1 - scale and tile PDF pages to print on multiple sheets Message-ID: <104d45e0-82bc-1134-d4f4-eb362a16d029@crazy-compilers.com> I'm pleased to announce pdftools.pdfposter 0.8.1, a tool to scale and tile PDF images/pages to print on multiple pages. :Homepage:? https://pdfposter.readthedocs.io/ :Author:??? Hartmut Goebel :License:?? GNU Public License v3 or later (GPL-3.0-or-later) :Quick Installation: ??? pip install -U pdftools.pdfposter :Tarballs:? https://pypi.org/project/pdftools.pdfposter/#files What is pdfposter? -------------------- Scale and tile PDF images/pages to print on multiple pages. ``Pdfposter`` can be used to create a large poster by building it from multiple pages and/or printing it on large media. It expects as input a PDF file, normally printing on a single page. The output is again a PDF file, maybe containing multiple pages together building the poster. The input page will be scaled to obtain the desired size. This is much like ``poster`` does for Postscript files, but working with PDF. Since sometimes poster does not like your files converted from PDF. :-) Indeed ``pdfposter`` was inspired by ``poster``. For more information please refer to the manpage or visit the `project homepage `_. What's new in version 0.8.1 ----------------------------------------- * This is a bug-fix release for release 0.8. What's new in version 0.8 ----------------------------------------- * Be less strict when reading PDF files. * Enhance some help messages. * Drop support for Python 2 and Python <= 3.5. Minimum supported versions are ? now 3.6 to 3.10. * Internal changes: ? - Update required version of `PyPDF` to 2.1.1. ? - Enhance code quality. -- Regards Hartmut Goebel | Hartmut Goebel | h.goebel at crazy-compilers.com | | www.crazy-compilers.com | compilers which you thought are impossible | From p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt Fri Nov 4 12:33:58 2022 From: p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt (Paulo da Silva) Date: Fri, 4 Nov 2022 16:33:58 +0000 Subject: typing: property/setter and lists? [RESOLVED ERRATA] References: <02863bbc-a175-8eda-7775-8837f92d861a@DancesWithMice.info> Message-ID: ?s 07:52 de 04/11/22, dn escreveu: > On 04/11/2022 07.50, Chris Angelico wrote: >> On Fri, 4 Nov 2022 at 05:48, Paulo da Silva >> wrote: >>> >>> ?s 05:32 de 03/11/22, Paulo da Silva escreveu: >>>> ?s 03:24 de 03/11/22, Paulo da Silva escreveu: >>>>> Hi! >>>>> >>>>> And a typing problem again!!! >>>>> _______________________________________ >>>>> class C: >>>>> ????? def __init__(self): >>>>> ????????? self.__foos=5*[0] >>>>> >>>>> ????? @property >>>>> ????? def foos(self) -> list[int]: >>>>> ????????? return self.__foos >>>>> >>>>> ????? @foos.setter >>>>> ????? def foos(self,v: int): >>>>> ????????? self.__foos=[v for __i in self.__foos] >>>>> >>>>> c=C() >>>>> c.foos=5 >>>>> print(c.foos) >>>>> _______________________________________ >>>>> >>>>> mypy gives the following error: >>>>> error: Incompatible types in assignment (expression has type "int", >>>>> variable has type "List[int]") >>>>> >>>>> How do I turn around this? >>>>> >>>> Changing def foos(self) -> list[int]:? to >>>> ?? def foos(self) -> Union[list[int]]: >>> I meant, of course, >>> def foos(self) -> Union[list[int],int]: >>> >> >> Ohhh! I thought this was triggering a strange quirk of the checker in >> some way... > > > Yes, these personal styles (?quirks) are off-putting to others. > > Plus "_" means (more or less) "not used anymore" > and for most of us, a weak-identifier name such as "i" is indeed "an > indexer/counter/... " Thank you for the suggestions. BTW, I am not a python pro programmer. I use it as a tool as many other tools and some other (few) languages. .. > ...and whilst I'm griping, > "To help us to help you please copy-paste the *exact* message" > has been followed by: > "I'm sorry. A bad transposition of the text." > > copy-paste for the win! > (and to keep others happy to spend their voluntary time helping you - > more working-with-the-team thinking to consider - please) The full original message was there. Seemed to me that that was obvious considering the simplicity of the subject and the illustrative toy example. Anyway, I'm sorry. Thank you. Paulo From elasstiika at gmail.com Fri Nov 4 16:46:56 2022 From: elasstiika at gmail.com (elas tica) Date: Fri, 4 Nov 2022 13:46:56 -0700 (PDT) Subject: Operator: inappropriate wording? In-Reply-To: References: <4a3bbb16-0d2e-4230-948d-793e5915721an@googlegroups.com> <91181647-7008-4912-86a2-e6f39cda4744n@googlegroups.com> <61004995-396e-4bb6-bbdd-bd877defc275n@googlegroups.com> Message-ID: Le vendredi 4 novembre 2022 ? 16:29:34 UTC+1, Chris Angelico a ?crit?: > Yep. The word "operator" is incorrect when referring to Python's comma > (in contrast to, say, C, where the comma actually *is* an operator); > and from my understanding, the docs have already been updated to fix > this. > > ChrisA Thanks Chris for your response. This problem of an imaginary comma operator was quite clear. The issue I opened is more about the so-called = operator which is not considered as such by the official Python FAQ, at the same place where it was said that comma was not an operator either. By the way, I opened another issue because the dot operator is missing in the list of tokens that are operators and R. Hettinger seems to consider my objection as admissible. The issue is here: https://github.com/python/cpython/issues/99000 It seems that there are some problems with the use of the term operator in the official documentation ;) From jkn_gg at nicorp.f9.co.uk Fri Nov 4 18:02:16 2022 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Fri, 4 Nov 2022 15:02:16 -0700 (PDT) Subject: ANN: pdfposter 0.8.1 - scale and tile PDF pages to print on multiple sheets In-Reply-To: References: <104d45e0-82bc-1134-d4f4-eb362a16d029@crazy-compilers.com> Message-ID: <73db353e-aa3e-4c9a-b9e8-d4b5cd562dban@googlegroups.com> On Friday, November 4, 2022 at 6:21:55 PM UTC, Hartmut Goebel wrote: > I'm pleased to announce pdftools.pdfposter 0.8.1, a tool to scale and > tile PDF images/pages to print on multiple pages. > > :Homepage: https://pdfposter.readthedocs.io/ > :Author: Hartmut Goebel > :License: GNU Public License v3 or later (GPL-3.0-or-later) > > :Quick Installation: > pip install -U pdftools.pdfposter > > :Tarballs: https://pypi.org/project/pdftools.pdfposter/#files > > > What is pdfposter? > -------------------- > > Scale and tile PDF images/pages to print on multiple pages. > > ``Pdfposter`` can be used to create a large poster by building it from > multiple pages and/or printing it on large media. It expects as input a > PDF file, normally printing on a single page. The output is again a > PDF file, maybe containing multiple pages together building the > poster. > The input page will be scaled to obtain the desired size. > > This is much like ``poster`` does for Postscript files, but working > with PDF. Since sometimes poster does not like your files converted > from PDF. :-) Indeed ``pdfposter`` was inspired by ``poster``. > > For more information please refer to the manpage or visit > the `project homepage `_. > > > What's new in version 0.8.1 > ----------------------------------------- > > * This is a bug-fix release for release 0.8. > > What's new in version 0.8 > ----------------------------------------- > > * Be less strict when reading PDF files. > > * Enhance some help messages. > > * Drop support for Python 2 and Python <= 3.5. Minimum supported > versions are > now 3.6 to 3.10. > > * Internal changes: > > - Update required version of `PyPDF` to 2.1.1. > - Enhance code quality. > > -- > Regards > Hartmut Goebel > > | Hartmut Goebel | h.go... at crazy-compilers.com | > | www.crazy-compilers.com | compilers which you thought are impossible | Thanks for this - yes, I remember poster for n-up Postscript files... From greg.ewing at canterbury.ac.nz Fri Nov 4 20:47:30 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Sat, 5 Nov 2022 13:47:30 +1300 Subject: an oop question In-Reply-To: References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <865yfwevet.fsf@yaxenu.org> Message-ID: On 5/11/22 4:25 am, Chris Angelico wrote: > Maybe it's one of those terms that is useless for actual coding > (because practicality beats purity), but good for discussions? I'm not sure it's much good for discussions, either. I don't really care whether a language is "purely OO" or not, whatever that means, because I don't see purity of OO as a virtue. All I care about is what actual features then language has. -- Greg From jshem at yaxenu.org Fri Nov 4 20:58:19 2022 From: jshem at yaxenu.org (Julieta Shem) Date: Fri, 04 Nov 2022 21:58:19 -0300 Subject: an oop question References: <86y1sxmmvo.fsf@yaxenu.org> <86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org> <86v8o0hlno.fsf@yaxenu.org> <86h6zih8jb.fsf@yaxenu.org> <86sfj2fl9u.fsf@yaxenu.org> <86pme4dg9s.fsf@yaxenu.org> <86iljwb4rj.fsf@yaxenu.org> Message-ID: <861qqi9pzo.fsf@yaxenu.org> Greg Ewing writes: > On 4/11/22 1:29 am, Julieta Shem wrote: >> Perhaps I can reduce the >> class Pair to just being a pair as we know it, made of two things, then >> we create a class called Sequence, which is really a composition of >> Pairs, comes with a length method and we derive Stack from it. > > That sounds better. But be careful -- a Sequence class would > probably be expected to have methods for e.g. inserting and > removing things in the middle, which you might not want to > allow for a Stack. I guess we could override those and raise NotImplementedError? I don't actually know how to do that. Say I have those two classes Empty and Pair. Here's a way to design Seq: class Seq: class SeqEmpty(Empty): pass class SeqPair(Pair): def insert(self): return ... def remove(self): return ... def __new__(clss, *args): if len(args) == 0: return Seq.SeqEmpty() else: return Seq.SeqPair(*args) How do I override insert in Stack? class Stack(Seq): def insert(self): raise NotImplementedError That doesn't work because when I create an object of type Stack, it is actually an object of type Seq.SeqEmpty or of type Seq.SeqPair. So it seems that Stack should inherit Seq.SeqPair or Seq.SeqEmpty and these unions begin to look like a lot of typing. From hjp-python at hjp.at Sat Nov 5 07:53:09 2022 From: hjp-python at hjp.at (Peter J. Holzer) Date: Sat, 5 Nov 2022 12:53:09 +0100 Subject: for -- else: what was the motivation? In-Reply-To: <20221022130458.4svttadgdui2w72q@hjp.at> References: <9db5003a-b38d-51d7-1eae-389adaac394f@btinternet.com> <004e01d8e0e8$7d9ec020$78dc4060$@gmail.com> <0265365a-39bb-f40e-f0b1-31943b74f924@vub.be> <20221016170103.htj57q43ux5lqzy5@hjp.at> <20221019005942.dfnzyukafmibr56c@hjp.at> <20221022130458.4svttadgdui2w72q@hjp.at> Message-ID: <20221105115309.hhyqeharurw6bjzp@hjp.at> On 2022-10-22 15:04:58 +0200, Peter J. Holzer wrote: > On 2022-10-19 12:10:52 +1100, Chris Angelico wrote: > > On Wed, 19 Oct 2022 at 12:01, Peter J. Holzer wrote: > > > On 2022-10-17 09:25:00 +0200, Karsten Hilbert wrote: > > > > http://literateprogramming.com/ > > > > > > Right. That's one of the inspirations for my comment. > > > > > > But literate programming is of course still very much rooted in the > > > "linear text representation" paradigm. You have one definite source > > > which is a linear text. > > > > > > In a world of IDEs, databases and hypertext that's probably not the best > > > we can do. As Raymond Hettinger would say, "there must be a better way". > > > > > > It would be very different from mainstream programming languages, > > > however. And ideally you would want it to integrate with a lot of other > > > infrastructure. So that alone might make it a non-starter, even if it > > > was really good (which realistically early iterations wouldn't be). > > > > There are special-purpose languages like Scratch which are not simple > > text in that form. > > Yes, I know. > > It has a different goal though: Scratch tries to establish a friendly > learning environment. Get rid of typing and syntax errors that beginners > find so frustrating. > > What I'm interested in is an enviroment for developing medium-sized real > applications. Late addendum: Watch ["Stop Writing Dead Programs" by Jack Rusher (Strange Loop 2022)](https://www.youtube.com/watch?v=8Ab3ArE8W3s) for an overview of some ideas about programming environments. hp -- _ | Peter J. Holzer | Story must make more sense than reality. |_|_) | | | | | hjp at hjp.at | -- Charles Stross, "Creative writing __/ | http://www.hjp.at/ | challenge!" -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 833 bytes Desc: not available URL: From python at mrabarnett.plus.com Sat Nov 5 13:15:52 2022 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 5 Nov 2022 17:15:52 +0000 Subject: Need help with custom string formatter In-Reply-To: References: Message-ID: <612eb0e3-9d3d-0f01-6950-5f30a44f9b51@mrabarnett.plus.com> On 2022-11-05 11:07, Stefan Ram wrote: > Robert Latest writes: >>>result += ' ' *( length - len( result )) >>Nice, I didn't know that one could multiply strings by negative numbers without >>error. > > Thanks, but today I thought that maybe there might > be a solution for getting a field of a fixed length > that is even shorter. It uses Python's string > formatting, here in the form of an "f" string. > > main.py > > def f( result, length ): > # get a field with the given length from the string "result" > # - as used in postings from october > result = result[ :length ] > result += ' ' *( length - len( result )) That can be done more compactly as: result = result[ : length].ljust(length) > return result > [snip] From riemannic at gmail.com Sat Nov 5 12:06:41 2022 From: riemannic at gmail.com (cactus) Date: Sat, 5 Nov 2022 09:06:41 -0700 (PDT) Subject: comprehension parsing Message-ID: <0911c76a-a222-490b-a343-583e605b9790n@googlegroups.com> The two comprehensions: all((srt(n, m) in c_np) == (srt(a, b) in c_ap) for (m, b) in na) all( srt(n, m) in c_np == srt(a, b) in c_ap for (m, b) in na) parse differently but I am unclear what the second one produces since I thought it would be the same as the first. Any ideas how the second one parses? From jshem at yaxenu.org Sat Nov 5 12:41:14 2022 From: jshem at yaxenu.org (Julieta Shem) Date: Sat, 05 Nov 2022 13:41:14 -0300 Subject: an oop question References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <865yfyh7z5.fsf@yaxenu.org> <49e71d27-8a6b-bfe7-95e7-dc3b8cb83ea5@yahoo.co.uk> <86tu3gc0z6.fsf@yaxenu.org> <86mt97an33.fsf@yaxenu.org> Message-ID: <86r0yh8ic5.fsf@yaxenu.org> ram at zedat.fu-berlin.de (Stefan Ram) writes: > Julieta Shem writes: >>ram at zedat.fu-berlin.de (Stefan Ram) writes: >>>Later, I looked at a book in a bookstore; it was a book >>>about programming by Barbara Liskov that came out after the >>>LSP was already mentioned often, and as far as I could see, >>>that book did not mention the LSP at all, although it >>>actually had a chapter about subtypes! >>Do you remember the book's title? > > Unfortunately, no. I might have seen it between 1995 and 2010, > so it could have been > > Program Development in Java: > Abstraction, Specification, and Object-Oriented Design > by John Guttag and Barbara Liskov, > June 2000 > > . It has this predecessor: > > Abstraction and Specification in Program Development > by Barbara Liskov and John Guttag, > March 1986 > > . But I also found this paper, which I recommend to look at > in this regard: > > A Behavioral Notion of Subtyping, > Barbara Liskov and Jeannette M. Wing, > 1994 > > . It contains the quite readable > > |Subtype Requirement: Let ?(z) be a property provable about > |objects x of type T. Then ?(y) should be true for objects y > |of type S where S is a subtype of T. Thank you so much for the references! [...] From riemannic at gmail.com Sat Nov 5 14:52:09 2022 From: riemannic at gmail.com (cactus) Date: Sat, 5 Nov 2022 11:52:09 -0700 (PDT) Subject: comprehension parsing In-Reply-To: <0911c76a-a222-490b-a343-583e605b9790n@googlegroups.com> References: <0911c76a-a222-490b-a343-583e605b9790n@googlegroups.com> Message-ID: On Saturday, 5 November 2022 at 16:06:52 UTC, cactus wrote: I should have quoted the full comprehensions: all((srt(m, n) in c_np) == (srt(a, b) in c_ap) for (m, a), (n, b) in combinations(na8, 2)) all( srt(m, n) in c_np == srt(a, b) in c_ap) for (m, a), (n, b) in combinations(na8, 2)) From python at mrabarnett.plus.com Sat Nov 5 18:11:38 2022 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 5 Nov 2022 22:11:38 +0000 Subject: comprehension parsing In-Reply-To: References: <0911c76a-a222-490b-a343-583e605b9790n@googlegroups.com> Message-ID: On 2022-11-05 18:52, cactus wrote: > On Saturday, 5 November 2022 at 16:06:52 UTC, cactus wrote: > > I should have quoted the full comprehensions: > > all((srt(m, n) in c_np) == (srt(a, b) in c_ap) for (m, a), (n, b) in combinations(na8, 2)) > all( srt(m, n) in c_np == srt(a, b) in c_ap) for (m, a), (n, b) in combinations(na8, 2)) The comparison operators can be chained, so: a == b == c is equivalent to: (a == b) and (b == c) except that the common term ('b' in this case) is evaluated only once. 'in' is one of those comparison operators, so: srt(m, n) in c_np == srt(a, b) in c_ap is equivalent to: (srt(m, n) in c_np) and (c_np == srt(a, b)) and (srt(a, b) in c_ap) except that the common terms ('c_np' and 'srt(a, b)') are evaluated only once. Chaining makes most sense with multiple '==' or a series of '<' and/or '<=' or a series of '>' and/or '>=', as in '1 <= n <= 10'. From BlindAnagram at nowhere.org Sat Nov 5 19:54:42 2022 From: BlindAnagram at nowhere.org (BlindAnagram) Date: Sat, 5 Nov 2022 23:54:42 +0000 Subject: comprehension parsing In-Reply-To: References: <0911c76a-a222-490b-a343-583e605b9790n@googlegroups.com> Message-ID: On 05/11/2022 22:11, MRAB wrote: > On 2022-11-05 18:52, cactus wrote: >> On Saturday, 5 November 2022 at 16:06:52 UTC, cactus wrote: >> >> I should have quoted the full comprehensions: >> >> ? all((srt(m, n) in c_np) == (srt(a, b) in c_ap)? for (m, a), (n, b) >> in combinations(na8, 2)) >> ? all( srt(m, n) in c_np? ==? srt(a, b) in c_ap)? for (m, a), (n, b) >> in combinations(na8, 2)) > > The comparison operators can be chained, so: > > ??? a == b == c > > is equivalent to: > > ??? (a == b) and (b == c) > > except that the common term ('b' in this case) is evaluated only once. > > 'in' is one of those comparison operators, so: > > ???? srt(m, n) in c_np == srt(a, b) in c_ap > > is equivalent to: > > ???? (srt(m, n) in c_np) and (c_np == srt(a, b)) and (srt(a, b) in c_ap) > > except that the common terms ('c_np' and 'srt(a, b)') are evaluated only > once. > > Chaining makes most sense with multiple '==' or a series of '<' and/or > '<=' or a series of '>' and/or '>=', as in '1 <= n <= 10'. Thanks for a most helpful explanation From philippe.descharmes at sfr.fr Sat Nov 5 21:55:00 2022 From: philippe.descharmes at sfr.fr (philippe descharmes) Date: Sun, 6 Nov 2022 02:55:00 +0100 (CET) Subject: comprehension parsing Message-ID: <268476793.679.1667699700039@wsfrf1452.priv.atos.fr> Hello, I?ts probably a priority of avalauation in the chain of operators ans association of themselves. I'm not sure. Philippe. ? De : "BlindAnagram" A : python-list at python.org Envoy?: dimanche 6 Novembre 2022 00:57 Objet : Re: comprehension parsing ? On 05/11/2022 22:11, MRAB wrote: > On 2022-11-05 18:52, cactus wrote: >> On Saturday, 5 November 2022 at 16:06:52 UTC, cactus wrote: >> >> I should have quoted the full comprehensions: >> >> ? all((srt(m, n) in c_np) == (srt(a, b) in c_ap)? for (m, a), (n, b) >> in combinations(na8, 2)) >> ? all( srt(m, n) in c_np? ==? srt(a, b) in c_ap)? for (m, a), (n, b) >> in combinations(na8, 2)) > > The comparison operators can be chained, so: > > ??? a == b == c > > is equivalent to: > > ??? (a == b) and (b == c) > > except that the common term ('b' in this case) is evaluated only once. > > 'in' is one of those comparison operators, so: > > ???? srt(m, n) in c_np == srt(a, b) in c_ap > > is equivalent to: > > ???? (srt(m, n) in c_np) and (c_np == srt(a, b)) and (srt(a, b) in c_ap) > > except that the common terms ('c_np' and 'srt(a, b)') are evaluated only > once. > > Chaining makes most sense with multiple '==' or a series of '<' and/or > '<=' or a series of '>' and/or '>=', as in '1 <= n <= 10'. Thanks for a most helpful explanation -- https://mail.python.org/mailman/listinfo/python-list From nospam at please.ty Sun Nov 6 14:51:10 2022 From: nospam at please.ty (jak) Date: Sun, 6 Nov 2022 20:51:10 +0100 Subject: How to manage python shebang on mixed systems? References: <6ddk3j-8pup.ln1@esprimo.zbmc.eu> Message-ID: Il 06/11/2022 11:03, Chris Green ha scritto: > I have a number of python scripts that I run on a mix of systems. I > have updated them all to run on python 3 but many will also run quite > happily with python 2. They all have a #!/usr/bin/python3 shebang. > > This works almost everywhere but there is one system where only > python 2 is available (at /usr/bin/python). > > I don't have python 2 on any of the systems I manage myself now so a > #!/usr/bin/python shebang will fail. > > Is there a neat way of handling this? I could write a sort of wrapper > script to run via the shebang but that seems overkill to me. > hi, If you can call Python from the shell prompt, then you could remove the path from shebang: #!python From cl at isbd.net Sun Nov 6 14:31:06 2022 From: cl at isbd.net (Chris Green) Date: Sun, 6 Nov 2022 19:31:06 +0000 Subject: How to manage python shebang on mixed systems? References: <6ddk3j-8pup.ln1@esprimo.zbmc.eu> Message-ID: rbowman wrote: > On Sun, 6 Nov 2022 10:03:50 +0000, Chris Green wrote: > > > > Is there a neat way of handling this? I could write a sort of wrapper > > script to run via the shebang but that seems overkill to me. > > Can you symlink? Not really, since the system where there's no python3 is one where I only have user access. -- Chris Green ? From cs at cskk.id.au Sun Nov 6 16:56:01 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Mon, 7 Nov 2022 08:56:01 +1100 Subject: How to manage python shebang on mixed systems? In-Reply-To: References: Message-ID: On 06Nov2022 20:51, jak wrote: >Il 06/11/2022 11:03, Chris Green ha scritto: >>I have a number of python scripts that I run on a mix of systems. I >>have updated them all to run on python 3 but many will also run quite >>happily with python 2. They all have a #!/usr/bin/python3 shebang. I usually use: #!/usr/bin/env python3 This runs the default "python3" from my $PATH, whatever that is, avoiding a hardwired path to the python3 executable. >>This works almost everywhere but there is one system where only >>python 2 is available (at /usr/bin/python). >> >>I don't have python 2 on any of the systems I manage myself now so a >>#!/usr/bin/python shebang will fail. >> >>Is there a neat way of handling this? I could write a sort of wrapper >>script to run via the shebang but that seems overkill to me. It is overkill. I generally dislike batch editing scripts. 1: do these scripts work on both python2 and python3? It seems like they would need to. 2: write a tiny script _named_ "python3" which invokes python 2. I keep a personal "~/bin-local" directory for just such per-system special commands like this. 3: with your pseudo "python3" script in place, make all the scripts use the "#!/usr/bin/env python3" shebang suggested above. Cheers, Cameron Simpson From gweatherby at uchc.edu Sun Nov 6 21:24:36 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Mon, 7 Nov 2022 02:24:36 +0000 Subject: How to manage python shebang on mixed systems? In-Reply-To: References: <6ddk3j-8pup.ln1@esprimo.zbmc.eu> Message-ID: A possible solution is here. https://superuser.com/questions/815323/can-i-have-a-conditional-shebang ________________________________ From: Python-list on behalf of jak Sent: Sunday, November 6, 2022 2:51:10 PM To: python-list at python.org Subject: Re: How to manage python shebang on mixed systems? *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** Il 06/11/2022 11:03, Chris Green ha scritto: > I have a number of python scripts that I run on a mix of systems. I > have updated them all to run on python 3 but many will also run quite > happily with python 2. They all have a #!/usr/bin/python3 shebang. > > This works almost everywhere but there is one system where only > python 2 is available (at /usr/bin/python). > > I don't have python 2 on any of the systems I manage myself now so a > #!/usr/bin/python shebang will fail. > > Is there a neat way of handling this? I could write a sort of wrapper > script to run via the shebang but that seems overkill to me. > hi, If you can call Python from the shell prompt, then you could remove the path from shebang: #!python -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!ke_gwJrnkkPx4fdk8CkLm6Qd2lmYIl7st4qz7Mmn0G8BerBOEwRWBfm51eFZ-Ut4WCTXTGoUEP5MTWYjmZE$ From miked at dewhirst.com.au Sun Nov 6 22:02:44 2022 From: miked at dewhirst.com.au (Mike Dewhirst) Date: Mon, 7 Nov 2022 14:02:44 +1100 Subject: How to manage python shebang on mixed systems? In-Reply-To: References: <6ddk3j-8pup.ln1@esprimo.zbmc.eu> Message-ID: On 7/11/2022 6:51 am, jak wrote: > Il 06/11/2022 11:03, Chris Green ha scritto: >> I have a number of python scripts that I run on a mix of systems.? I >> have updated them all to run on python 3 but many will also run quite >> happily with python 2.? They all have a #!/usr/bin/python3 shebang. >> >> This works almost everywhere but there is one system where only >> python 2 is available (at /usr/bin/python). >> >> I don't have python 2 on any of the systems I manage myself now so a >> #!/usr/bin/python shebang will fail. >> >> Is there a neat way of handling this?? I could write a sort of wrapper >> script to run via the shebang but that seems overkill to me. >> Can you link the interpreter on each system to the same-named local link and put that in your shebang? #!~/scripts/mypython > > hi, > If you can call Python from the shell prompt, then you could remove the > path from shebang: > > #!python > -- Signed email is an absolute defence against phishing. This email has been signed with my private key. If you import my public key you can automatically decrypt my signature and be sure it came from me. Just ask and I'll send it to you. Your email software can handle signing. -------------- next part -------------- A non-text attachment was scrubbed... Name: OpenPGP_signature Type: application/pgp-signature Size: 495 bytes Desc: OpenPGP digital signature URL: From barry at barrys-emacs.org Mon Nov 7 03:24:59 2022 From: barry at barrys-emacs.org (Barry) Date: Mon, 7 Nov 2022 08:24:59 +0000 Subject: How to manage python shebang on mixed systems? Message-ID: ? > On 7 Nov 2022, at 03:15, Mike Dewhirst wrote: > > ?On 7/11/2022 6:51 am, jak wrote: >> Il 06/11/2022 11:03, Chris Green ha scritto: >>> I have a number of python scripts that I run on a mix of systems. I >>> have updated them all to run on python 3 but many will also run quite >>> happily with python 2. They all have a #!/usr/bin/python3 shebang. >>> This works almost everywhere but there is one system where only >>> python 2 is available (at /usr/bin/python). >>> I don't have python 2 on any of the systems I manage myself now so a >>> #!/usr/bin/python shebang will fail. >>> Is there a neat way of handling this? I could write a sort of wrapper >>> script to run via the shebang but that seems overkill to me. > > Can you link the interpreter on each system to the same-named local link and put that in your shebang? > > #!~/scripts/mypython I do not think ~ works in a #! line. The ~ is handled by the shell, like bash. But the #! Is handled by the kernel in it exec() handling I recall. Using /usr/local/bin may be more suitable. Otherwise you are forced to use the /usr/bin/env method and ensure the PATH includes the command to run. Barry > >> hi, >> If you can call Python from the shell prompt, then you could remove the >> path from shebang: >> #!python > > > -- > Signed email is an absolute defence against phishing. This email has > been signed with my private key. If you import my public key you can > automatically decrypt my signature and be sure it came from me. Just > ask and I'll send it to you. Your email software can handle signing. > > -- > https://mail.python.org/mailman/listinfo/python-list From gweatherby at uchc.edu Mon Nov 7 06:56:19 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Mon, 7 Nov 2022 11:56:19 +0000 Subject: How to manage python shebang on mixed systems? In-Reply-To: References: <6ddk3j-8pup.ln1@esprimo.zbmc.eu> Message-ID: Write the wrapper script. #!/bin/bash if [ $(hostname) == "oldystem" ]; then exec /usr/bin/python $* else exec /usr/bin/python2 $* fi From: Python-list on behalf of Chris Green Date: Sunday, November 6, 2022 at 3:22 PM To: python-list at python.org Subject: Re: How to manage python shebang on mixed systems? *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** rbowman wrote: > On Sun, 6 Nov 2022 10:03:50 +0000, Chris Green wrote: > > > > Is there a neat way of handling this? I could write a sort of wrapper > > script to run via the shebang but that seems overkill to me. > > Can you symlink? Not really, since the system where there's no python3 is one where I only have user access. -- Chris Green ? -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!gN4FcCAwYqK8bafmF2dr_EB9nahZcdNmU91bHuymdlakU27cNTnIwQ_FckF9PBZlllGnW_vlEjQ$ From 2QdxY4RzWzUUiLuE at potatochowder.com Mon Nov 7 07:44:21 2022 From: 2QdxY4RzWzUUiLuE at potatochowder.com (2QdxY4RzWzUUiLuE at potatochowder.com) Date: Mon, 7 Nov 2022 07:44:21 -0500 Subject: How to manage python shebang on mixed systems? In-Reply-To: References: <6ddk3j-8pup.ln1@esprimo.zbmc.eu> Message-ID: On 2022-11-07 at 11:56:19 +0000, "Weatherby,Gerard" wrote: > Write the wrapper script. > > #!/bin/bash > if [ $(hostname) == "oldystem" ]; then > exec /usr/bin/python $* > else > exec /usr/bin/python2 $* > fi Use "$@" (with the quotes) instead of a bare $*. The former preserves quoted arguments, while the latter does not. Also, it's probably more robust to check explcitly for python2 instead of depending on the hostname. Renaming hosts isn't a common operation, but in general, checking for what something *does* or *has* is better than checking for what it *is* (hey, look: duck typing!). Implementing both suggestions yields this: #! /bin/bash if [ -x /usr/bin/python2 ]; then exec /usr/bin/python2 "$@" else exec /usr/bin/python "$@" fi YMMV. From cl at isbd.net Mon Nov 7 04:05:53 2022 From: cl at isbd.net (Chris Green) Date: Mon, 7 Nov 2022 09:05:53 +0000 Subject: How to manage python shebang on mixed systems? References: Message-ID: Cameron Simpson wrote: > On 06Nov2022 20:51, jak wrote: > >Il 06/11/2022 11:03, Chris Green ha scritto: > >>I have a number of python scripts that I run on a mix of systems. I > >>have updated them all to run on python 3 but many will also run quite > >>happily with python 2. They all have a #!/usr/bin/python3 shebang. > > I usually use: > > #!/usr/bin/env python3 > > This runs the default "python3" from my $PATH, whatever that is, > avoiding a hardwired path to the python3 executable. > Yes, that's probably a good idea, less likely to break than mine. > >>This works almost everywhere but there is one system where only > >>python 2 is available (at /usr/bin/python). > >> > >>I don't have python 2 on any of the systems I manage myself now so a > >>#!/usr/bin/python shebang will fail. > >> > >>Is there a neat way of handling this? I could write a sort of wrapper > >>script to run via the shebang but that seems overkill to me. > > It is overkill. I generally dislike batch editing scripts. > > 1: do these scripts work on both python2 and python3? It seems like they > would need to. Yes, they do, they're mostly very simple utility scripts for doing things like changing spaces to underscores in filenames and such. Just putting 'print' parameters in brackets was all that most of them needed to work in python 3. > 2: write a tiny script _named_ "python3" which invokes python 2. I keep > a personal "~/bin-local" directory for just such per-system special > commands like this. > 3: with your pseudo "python3" script in place, make all the scripts use > the "#!/usr/bin/env python3" shebang suggested above. > Yes, that sounds a good plan to me, thanks Cameron. -- Chris Green ? From cl at isbd.net Mon Nov 7 04:28:18 2022 From: cl at isbd.net (Chris Green) Date: Mon, 7 Nov 2022 09:28:18 +0000 Subject: How to manage python shebang on mixed systems? References: Message-ID: Chris Green wrote: > > 3: with your pseudo "python3" script in place, make all the scripts use > > the "#!/usr/bin/env python3" shebang suggested above. > > > Yes, that sounds a good plan to me, thanks Cameron. > Doesn't '#!/usr/bin/env python3' suffer from the same problem as '#!/usr/bin/python3' in the sense that the env executable might not be in /usr/bin? Wouldn't '#! env python3' be better? -- Chris Green ? From ictezy at gmail.com Mon Nov 7 01:01:08 2022 From: ictezy at gmail.com (ICT Ezy) Date: Sun, 6 Nov 2022 22:01:08 -0800 (PST) Subject: What is the reason from different output generate using logical 'and' and 'or' operator in Python 3.10.8 Message-ID: Please explain how to generate different output in following logical operations >>> 0 and True 0 >>> 0 or True True >>> 1 and True True >>> 1 or True 1 From dioumacorfaye at gmail.com Mon Nov 7 12:12:12 2022 From: dioumacorfaye at gmail.com (Dioumacor FAYE) Date: Mon, 7 Nov 2022 17:12:12 +0000 Subject: How to turn this Matlab code into python Message-ID: hi everyone I wanted to transform this matlab code into python. If anyone can help me please let me know. load /media/lpaosf/Dioumss/maman/data/precip_chirps_SEN_1981-2018.mat prcp = reshape(precip,[140*100,13879]); dates = datenum(1981,1,1):datenum(2018,12,31); date = datevec(dates); ind_mjja=find(date(:,2)>=5 & date(:,2)<=8);% May to Aug (May(31)+ June(30)+ July(31)+ August(31)= 123 days) data_mjja=precp(:,ind_mjja); data_mjja_res=reshape(data_mjja,14000,123,38); -- Bien ? vous, --------------------- ------------------ ----------------- -------------------- ----------------- Dioumacor FAYE doctorant au LPAOSF/ESP/UCAD/BP 5085 Dakar-Fann, S?n?gal. Tel labo: (00221) 33 825 93 64 Email: d.faye20171634 at zig.univ.sn Tel: +221773475098 +221783484308 Physicien en herbe Pseudo Skype: dioumacorfaye From Joseph.Schachner at Teledyne.com Mon Nov 7 13:07:54 2022 From: Joseph.Schachner at Teledyne.com (Schachner, Joseph (US)) Date: Mon, 7 Nov 2022 18:07:54 +0000 Subject: How to manage python shebang on mixed systems? In-Reply-To: References: Message-ID: Maybe you can't do this, but I would suggest only running on the Python 3 systems. Refuse to jump through hoops for the Python 2 system. It is years out of date. It is not hard to upgrade from Python 2 to Python 3. There is a 2to3 utility, and after that there should be very few things you want to manually change. Perhaps you could encourage them to upgrade. --- Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -----Original Message----- From: Chris Green Sent: Monday, November 7, 2022 4:06 AM To: python-list at python.org Subject: Re: How to manage python shebang on mixed systems? Cameron Simpson wrote: > On 06Nov2022 20:51, jak wrote: > >Il 06/11/2022 11:03, Chris Green ha scritto: > >>I have a number of python scripts that I run on a mix of systems. I > >>have updated them all to run on python 3 but many will also run > >>quite happily with python 2. They all have a #!/usr/bin/python3 shebang. > > I usually use: > > #!/usr/bin/env python3 > > This runs the default "python3" from my $PATH, whatever that is, > avoiding a hardwired path to the python3 executable. > Yes, that's probably a good idea, less likely to break than mine. > >>This works almost everywhere but there is one system where only > >>python 2 is available (at /usr/bin/python). > >> > >>I don't have python 2 on any of the systems I manage myself now so a > >>#!/usr/bin/python shebang will fail. > >> > >>Is there a neat way of handling this? I could write a sort of > >>wrapper script to run via the shebang but that seems overkill to me. > > It is overkill. I generally dislike batch editing scripts. > > 1: do these scripts work on both python2 and python3? It seems like > they would need to. Yes, they do, they're mostly very simple utility scripts for doing things like changing spaces to underscores in filenames and such. Just putting 'print' parameters in brackets was all that most of them needed to work in python 3. > 2: write a tiny script _named_ "python3" which invokes python 2. I > keep a personal "~/bin-local" directory for just such per-system > special commands like this. > 3: with your pseudo "python3" script in place, make all the scripts > use the "#!/usr/bin/env python3" shebang suggested above. > Yes, that sounds a good plan to me, thanks Cameron. -- Chris Green ? From list1 at tompassin.net Mon Nov 7 13:34:49 2022 From: list1 at tompassin.net (Thomas Passin) Date: Mon, 7 Nov 2022 13:34:49 -0500 Subject: How to manage python shebang on mixed systems? In-Reply-To: References: Message-ID: The problem is that some Linux systems - I think - still use Python2 to perform various system-related tasks. When they call "python", they need it to be Python2. If someone has a system like that, they can't have the "python" command run Python3. On 11/7/2022 1:07 PM, Schachner, Joseph (US) wrote: > Maybe you can't do this, but I would suggest only running on the Python 3 systems. Refuse to jump through hoops for the Python 2 system. It is years out of date. > It is not hard to upgrade from Python 2 to Python 3. There is a 2to3 utility, and after that there should be very few things you want to manually change. Perhaps you could encourage them to upgrade. > > --- Joseph S. > > > Teledyne Confidential; Commercially Sensitive Business Data > > -----Original Message----- > From: Chris Green > Sent: Monday, November 7, 2022 4:06 AM > To: python-list at python.org > Subject: Re: How to manage python shebang on mixed systems? > > Cameron Simpson wrote: >> On 06Nov2022 20:51, jak wrote: >>> Il 06/11/2022 11:03, Chris Green ha scritto: >>>> I have a number of python scripts that I run on a mix of systems. I >>>> have updated them all to run on python 3 but many will also run >>>> quite happily with python 2. They all have a #!/usr/bin/python3 shebang. >> >> I usually use: >> >> #!/usr/bin/env python3 >> >> This runs the default "python3" from my $PATH, whatever that is, >> avoiding a hardwired path to the python3 executable. >> > Yes, that's probably a good idea, less likely to break than mine. > > >>>> This works almost everywhere but there is one system where only >>>> python 2 is available (at /usr/bin/python). >>>> >>>> I don't have python 2 on any of the systems I manage myself now so a >>>> #!/usr/bin/python shebang will fail. >>>> >>>> Is there a neat way of handling this? I could write a sort of >>>> wrapper script to run via the shebang but that seems overkill to me. >> >> It is overkill. I generally dislike batch editing scripts. >> >> 1: do these scripts work on both python2 and python3? It seems like >> they would need to. > > Yes, they do, they're mostly very simple utility scripts for doing things like changing spaces to underscores in filenames and such. > Just putting 'print' parameters in brackets was all that most of them needed to work in python 3. > > >> 2: write a tiny script _named_ "python3" which invokes python 2. I >> keep a personal "~/bin-local" directory for just such per-system >> special commands like this. >> 3: with your pseudo "python3" script in place, make all the scripts >> use the "#!/usr/bin/env python3" shebang suggested above. >> > Yes, that sounds a good plan to me, thanks Cameron. > > -- > Chris Green > ? From rosuav at gmail.com Mon Nov 7 14:29:14 2022 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 8 Nov 2022 06:29:14 +1100 Subject: How to manage python shebang on mixed systems? In-Reply-To: References: Message-ID: On Tue, 8 Nov 2022 at 06:12, Thomas Passin wrote: > > The problem is that some Linux systems - I think - still use Python2 to > perform various system-related tasks. When they call "python", they > need it to be Python2. If someone has a system like that, they can't > have the "python" command run Python3. > If currently-supported versions of any Linux distributions don't at least make a python3 command available, I would be very surprised. But when you don't have root access, it's not easy to install, even from repositories. ChrisA From cl at isbd.net Mon Nov 7 14:41:50 2022 From: cl at isbd.net (Chris Green) Date: Mon, 7 Nov 2022 19:41:50 +0000 Subject: How to manage python shebang on mixed systems? References: Message-ID: Schachner, Joseph (US) wrote: > Maybe you can't do this, but I would suggest only running on the Python > 3 systems. Refuse to jump through hoops for the Python 2 system. It is > years out of date. Exactly! That's why I (OP) have only one system where this is a problem. The system is my hosting provider's cPanel platform which is running a very old Linux and, as I've said has only python 2. I can ask for python 3 on their system but I suspect that my voice is a very tiny one and there are higher priority things to get done. -- Chris Green ? From barry at barrys-emacs.org Mon Nov 7 15:48:48 2022 From: barry at barrys-emacs.org (Barry Scott) Date: Mon, 7 Nov 2022 20:48:48 +0000 Subject: How to manage python shebang on mixed systems? In-Reply-To: References: Message-ID: > On 7 Nov 2022, at 09:28, Chris Green wrote: > > Chris Green wrote: >>> 3: with your pseudo "python3" script in place, make all the scripts use >>> the "#!/usr/bin/env python3" shebang suggested above. >>> >> Yes, that sounds a good plan to me, thanks Cameron. >> > Doesn't '#!/usr/bin/env python3' suffer from the same problem as > '#!/usr/bin/python3' in the sense that the env executable might not be > in /usr/bin? env is always available as /usr/bin/env - I think its spec'ed in posix that way. The only reason that things are in /bin are for systems that need a subset of programs to boot the system to point it can mount /usr. env is not going to be needed for that use case. > > Wouldn't '#! env python3' be better? Barry > > -- > Chris Green > ? > -- > https://mail.python.org/mailman/listinfo/python-list From auriocus at gmx.de Mon Nov 7 14:47:46 2022 From: auriocus at gmx.de (Christian Gollwitzer) Date: Mon, 7 Nov 2022 20:47:46 +0100 Subject: How to turn this Matlab code into python In-Reply-To: References: Message-ID: Am 07.11.22 um 18:12 schrieb Dioumacor FAYE: > hi everyone > I wanted to transform this matlab code into python. If anyone can help me > please let me know. > load /media/lpaosf/Dioumss/maman/data/precip_chirps_SEN_1981-2018.mat > prcp = reshape(precip,[140*100,13879]); > dates = datenum(1981,1,1):datenum(2018,12,31); > date = datevec(dates); > ind_mjja=find(date(:,2)>=5 & date(:,2)<=8);% May to Aug (May(31)+ June(30)+ > July(31)+ August(31)= 123 days) > data_mjja=precp(:,ind_mjja); > data_mjja_res=reshape(data_mjja,14000,123,38); which part do you have trouble with? Christian From auriocus at gmx.de Mon Nov 7 14:58:08 2022 From: auriocus at gmx.de (Christian Gollwitzer) Date: Mon, 7 Nov 2022 20:58:08 +0100 Subject: How to manage python shebang on mixed systems? In-Reply-To: References: Message-ID: Am 07.11.22 um 10:28 schrieb Chris Green: > Chris Green wrote: >>> 3: with your pseudo "python3" script in place, make all the scripts use >>> the "#!/usr/bin/env python3" shebang suggested above. >>> >> Yes, that sounds a good plan to me, thanks Cameron. >> > Doesn't '#!/usr/bin/env python3' suffer from the same problem as > '#!/usr/bin/python3' in the sense that the env executable might not be > in /usr/bin? > > Wouldn't '#! env python3' be better? Does this even work? I thought that, since the #! is resolved by the kernel, an absolute path is required, and that the whole purpose of the /usr/bin/env thing is to search the path (because it is universally installed in /usr/bin) and to possibly set other environment variables Christian From cl at isbd.net Mon Nov 7 16:27:26 2022 From: cl at isbd.net (Chris Green) Date: Mon, 7 Nov 2022 21:27:26 +0000 Subject: How to manage python shebang on mixed systems? References: Message-ID: Barry Scott wrote: > > > > On 7 Nov 2022, at 09:28, Chris Green wrote: > > > > Chris Green wrote: > >>> 3: with your pseudo "python3" script in place, make all the scripts use > >>> the "#!/usr/bin/env python3" shebang suggested above. > >>> > >> Yes, that sounds a good plan to me, thanks Cameron. > >> > > Doesn't '#!/usr/bin/env python3' suffer from the same problem as > > '#!/usr/bin/python3' in the sense that the env executable might not be > > in /usr/bin? > > env is always available as /usr/bin/env - I think its spec'ed in posix that way. > > The only reason that things are in /bin are for systems that need a subset of > programs to boot the system to point it can mount /usr. env is not going to be > needed for that use case. > Given that the problem system is running a very old Linux I'm not sure what chance there is that it's fully posix compliant. If using "#!/usr/bin/env python3" is a way of avoiding problems if python3 isn't in /usr/bin then why is it any better depending on env being in /usr/bin. -- Chris Green ? From rosuav at gmail.com Mon Nov 7 16:54:39 2022 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 8 Nov 2022 08:54:39 +1100 Subject: How to manage python shebang on mixed systems? In-Reply-To: References: Message-ID: On Tue, 8 Nov 2022 at 08:44, Chris Green wrote: > > Barry Scott wrote: > > > > > > > On 7 Nov 2022, at 09:28, Chris Green wrote: > > > > > > Chris Green wrote: > > >>> 3: with your pseudo "python3" script in place, make all the scripts use > > >>> the "#!/usr/bin/env python3" shebang suggested above. > > >>> > > >> Yes, that sounds a good plan to me, thanks Cameron. > > >> > > > Doesn't '#!/usr/bin/env python3' suffer from the same problem as > > > '#!/usr/bin/python3' in the sense that the env executable might not be > > > in /usr/bin? > > > > env is always available as /usr/bin/env - I think its spec'ed in posix that way. > > > > The only reason that things are in /bin are for systems that need a subset of > > programs to boot the system to point it can mount /usr. env is not going to be > > needed for that use case. > > > Given that the problem system is running a very old Linux I'm not sure > what chance there is that it's fully posix compliant. > > If using "#!/usr/bin/env python3" is a way of avoiding problems if > python3 isn't in /usr/bin then why is it any better depending on env > being in /usr/bin. > I frequently have python3 in /usr/local/bin instead. Sometimes in other places, depending on how many of them I've installed and from where. Using /usr/bin/env python3 ensures that it does the same as the "python3" command even if there's a venv active. (And yes, sometimes that's good, sometimes bad.) ChrisA From cs at cskk.id.au Mon Nov 7 17:35:07 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Tue, 8 Nov 2022 09:35:07 +1100 Subject: How to manage python shebang on mixed systems? In-Reply-To: References: Message-ID: On 07Nov2022 09:28, Chris Green wrote: >Chris Green wrote: >> > 3: with your pseudo "python3" script in place, make all the scripts use >> > the "#!/usr/bin/env python3" shebang suggested above. >> > >> Yes, that sounds a good plan to me, thanks Cameron. >> >Doesn't '#!/usr/bin/env python3' suffer from the same problem as >'#!/usr/bin/python3' in the sense that the env executable might not be >in /usr/bin? > >Wouldn't '#! env python3' be better? The thing after the shebang needs to be a full path. "env" is in /usr/bin on damn near everything. I think I had to make a symlink on a Solaris system once, but otherwise it has not been a problem for me on many different systems for many years. Cheers, Cameron Simpson From list1 at tompassin.net Mon Nov 7 18:09:33 2022 From: list1 at tompassin.net (Thomas Passin) Date: Mon, 7 Nov 2022 18:09:33 -0500 Subject: How to manage python shebang on mixed systems? In-Reply-To: References: Message-ID: More discussion: https://unix.stackexchange.com/questions/29608/why-is-it-better-to-use-usr-bin-env-name-instead-of-path-to-name-as-my On 11/7/2022 5:35 PM, Cameron Simpson wrote: > On 07Nov2022 09:28, Chris Green wrote: >> Chris Green wrote: >>> > 3: with your pseudo "python3" script in place, make all the scripts >>> use >>> > the "#!/usr/bin/env python3" shebang suggested above. >>> > >>> Yes, that sounds a good plan to me, thanks Cameron. >>> >> Doesn't '#!/usr/bin/env python3' suffer from the same problem as >> '#!/usr/bin/python3' in the sense that the env executable might not be >> in /usr/bin? >> >> Wouldn't '#! env python3' be better? > > The thing after the shebang needs to be a full path. > > "env" is in /usr/bin on damn near everything. I think I had to make a > symlink on a Solaris system once, but otherwise it has not been a > problem for me on many different systems for many years. > > Cheers, > Cameron Simpson From bouncingcats at gmail.com Mon Nov 7 19:05:50 2022 From: bouncingcats at gmail.com (David) Date: Tue, 8 Nov 2022 11:05:50 +1100 Subject: What is the reason from different output generate using logical 'and' and 'or' operator in Python 3.10.8 In-Reply-To: References: Message-ID: On Tue, 8 Nov 2022 at 03:08, ICT Ezy wrote: > Please explain how to generate different output in following logical operations > >>> 0 and True > 0 > >>> 0 or True > True > >>> 1 and True > True > >>> 1 or True > 1 Hi, The exact explanation of how 'and' and 'or' behave can be read here: https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not The "Notes" there explain what you see. From nospam at dfs.com Mon Nov 7 22:48:27 2022 From: nospam at dfs.com (DFS) Date: Mon, 7 Nov 2022 22:48:27 -0500 Subject: What's tkinter doing in \Lib\site-packages\future\moves ? Message-ID: 3.9.13 From rosuav at gmail.com Tue Nov 8 01:19:00 2022 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 8 Nov 2022 17:19:00 +1100 Subject: What's tkinter doing in \Lib\site-packages\future\moves ? In-Reply-To: References: Message-ID: On Tue, 8 Nov 2022 at 15:12, DFS wrote: > > 3.9.13 > My guess? Because you can "import tkinter" in Py3 but "import Tkinter" in Py2. ChrisA From dioumacorfaye at gmail.com Tue Nov 8 03:01:37 2022 From: dioumacorfaye at gmail.com (Dioumacor FAYE) Date: Tue, 8 Nov 2022 08:01:37 +0000 Subject: How to turn this Matlab code into python In-Reply-To: References: Message-ID: >From datenum to data_mjja=precp(:,ind_mjja); Le lun. 7 nov. 2022 ? 21:42, Christian Gollwitzer a ?crit : > Am 07.11.22 um 18:12 schrieb Dioumacor FAYE: > > hi everyone > > I wanted to transform this matlab code into python. If anyone can help me > > please let me know. > > load /media/lpaosf/Dioumss/maman/data/precip_chirps_SEN_1981-2018.mat > > prcp = reshape(precip,[140*100,13879]); > > dates = datenum(1981,1,1):datenum(2018,12,31); > > date = datevec(dates); > > ind_mjja=find(date(:,2)>=5 & date(:,2)<=8);% May to Aug (May(31)+ > June(30)+ > > July(31)+ August(31)= 123 days) > > data_mjja=precp(:,ind_mjja); > > data_mjja_res=reshape(data_mjja,14000,123,38); > > which part do you have trouble with? > > > Christian > -- > https://mail.python.org/mailman/listinfo/python-list > -- Bien ? vous, --------------------- ------------------ ----------------- -------------------- ----------------- Dioumacor FAYE doctorant au LPAOSF/ESP/UCAD/BP 5085 Dakar-Fann, S?n?gal. Tel labo: (00221) 33 825 93 64 Email: d.faye20171634 at zig.univ.sn Tel: +221773475098 +221783484308 Physicien en herbe Pseudo Skype: dioumacorfaye From brisvag at gmail.com Tue Nov 8 06:10:01 2022 From: brisvag at gmail.com (Lorenzo Gaifas) Date: Tue, 8 Nov 2022 12:10:01 +0100 Subject: VisPy 0.12 released Message-ID: Hi all, On behalf of the vispy contributors, I'm happy to announce vispy v0.12! Here are the main highlights: - Better attenuated_mip shader for Volume visuals, which scales automatically based on contrast limits - Instanced rendering in gloo, with some examples showcasing how to use it - Allow setting array to `symbol` in `MarkersVisual` Several bugs were also fixed, and documentation was updated. For a complete changelog, see https://github.com/vispy/vispy/releases/tag/v0.12.0 What is VisPy? -------------- VisPy is a Python library for interactive scientific visualization that is designed to be fast, scalable, and easy to use. VisPy leverages the computational power of modern Graphics Processing Units (GPUs) through the OpenGL library to display very large datasets. Applications of VisPy include: High-quality interactive scientific plots with millions of points. Direct visualization of real-time data. Fast interactive visualization of 3D models (meshes, volume rendering). OpenGL visualization demos. Scientific GUIs with fast, scalable visualization widgets (Qt or Jupyter Notebook via jupyter_rfb). See the Gallery and many other example scripts on the VisPy website ( http://vispy.org/). Upgrading --------- VisPy supports Python 3.x on Linux, Mac OSX, and Windows. VisPy's heavy use of the GPU means that users will need to have modern and up-to-date video drivers for their system. VisPy can use one of many backends, see the documentation for details. We strive to keep backwards compatibility with older versions of VisPy, but interfaces are still being designed to best serve our users. As such, some things may have changed that break your existing usage. See the Release Notes (linked below) for more information on what has changed and contact the VisPy developers for help with any problems you run into. Links ----- GitHub: https://github.com/vispy/vispy Website: http://vispy.org/ Gitter (for chat): https://gitter.im/vispy/vispy Mailing list: https://groups.google.com/forum/#!forum/vispy Release Notes: https://github.com/vispy/vispy/blob/main/CHANGELOG.md Contributing ------------ Help is always welcome. See our Contributor's Guide for information on how you can participate: https://vispy.org/dev_guide/contributor_guide.html Thanks, Lorenzo From nospam at dfs.com Mon Nov 7 23:41:10 2022 From: nospam at dfs.com (DFS) Date: Mon, 7 Nov 2022 23:41:10 -0500 Subject: What's tkinter doing in \Lib\site-packages\future\moves ? In-Reply-To: References: Message-ID: On 11/7/2022 10:48 PM, DFS wrote: > 3.9.13 Never mind. User error - I didn't install it in the first place. From nospam at please.ty Tue Nov 8 03:01:31 2022 From: nospam at please.ty (jak) Date: Tue, 8 Nov 2022 09:01:31 +0100 Subject: How to manage python shebang on mixed systems? References: Message-ID: Il 07/11/2022 20:41, Chris Green ha scritto: > Schachner, Joseph (US) wrote: >> Maybe you can't do this, but I would suggest only running on the Python >> 3 systems. Refuse to jump through hoops for the Python 2 system. It is >> years out of date. > > Exactly! That's why I (OP) have only one system where this is a > problem. The system is my hosting provider's cPanel platform which is > running a very old Linux and, as I've said has only python 2. > > I can ask for python 3 on their system but I suspect that my voice is > a very tiny one and there are higher priority things to get done. > Perhaps this is because you speak to them about the problems of compatibility, try to speak to them about power, speed and performance, instead. ;-D From auriocus at gmx.de Tue Nov 8 03:14:22 2022 From: auriocus at gmx.de (Christian Gollwitzer) Date: Tue, 8 Nov 2022 09:14:22 +0100 Subject: How to turn this Matlab code into python In-Reply-To: References: Message-ID: Am 08.11.22 um 09:01 schrieb Dioumacor FAYE: >>From datenum to data_mjja=precp(:,ind_mjja); I think the code filters data based on calendar dates. I'd guess that you can do that most easily with pandas. https://pandas.pydata.org/docs/user_guide/timeseries.html Christian > > Le lun. 7 nov. 2022 ? 21:42, Christian Gollwitzer a > ?crit : > >> Am 07.11.22 um 18:12 schrieb Dioumacor FAYE: >>> hi everyone >>> I wanted to transform this matlab code into python. If anyone can help me >>> please let me know. >>> load /media/lpaosf/Dioumss/maman/data/precip_chirps_SEN_1981-2018.mat >>> prcp = reshape(precip,[140*100,13879]); >>> dates = datenum(1981,1,1):datenum(2018,12,31); >>> date = datevec(dates); >>> ind_mjja=find(date(:,2)>=5 & date(:,2)<=8);% May to Aug (May(31)+ >> June(30)+ >>> July(31)+ August(31)= 123 days) >>> data_mjja=precp(:,ind_mjja); >>> data_mjja_res=reshape(data_mjja,14000,123,38); >> >> which part do you have trouble with? >> >> >> Christian >> -- >> https://mail.python.org/mailman/listinfo/python-list >> > > From alex.mojaki at gmail.com Tue Nov 8 15:09:44 2022 From: alex.mojaki at gmail.com (Alex Hall) Date: Tue, 8 Nov 2022 12:09:44 -0800 (PST) Subject: What to use for finding as many syntax errors as possible. In-Reply-To: References: Message-ID: <614843f7-d4b1-4014-b417-c55dddbc4a7en@googlegroups.com> On Sunday, October 9, 2022 at 12:09:45 PM UTC+2, Antoon Pardon wrote: > I would like a tool that tries to find as many syntax errors as possible > in a python file. I know there is the risk of false positives when a > tool tries to recover from a syntax error and proceeds but I would > prefer that over the current python strategy of quiting after the first > syntax error. I just want a tool for syntax errors. No style > enforcements. Any recommandations? -- Antoon Pardon Bit late here, coming from the Pycoder's Weekly email newsletter, but I'm surprised that I don't see any mentions of [parso](https://parso.readthedocs.io/en/latest/): > Parso is a Python parser that supports error recovery and round-trip parsing for different Python versions (in multiple Python versions). Parso is also able to list multiple syntax errors in your python file. From dioumacorfaye at gmail.com Tue Nov 8 15:51:00 2022 From: dioumacorfaye at gmail.com (Dioumacor FAYE) Date: Tue, 8 Nov 2022 20:51:00 +0000 Subject: How to turn this Matlab code into python In-Reply-To: References: Message-ID: Merci beaucoup Christian pour le lien. Le mar. 8 nov. 2022 ? 17:08, Christian Gollwitzer a ?crit : > Am 08.11.22 um 09:01 schrieb Dioumacor FAYE: > >>From datenum to data_mjja=precp(:,ind_mjja); > > I think the code filters data based on calendar dates. I'd guess that > you can do that most easily with pandas. > > https://pandas.pydata.org/docs/user_guide/timeseries.html > > Christian > > > > Le lun. 7 nov. 2022 ? 21:42, Christian Gollwitzer a > > ?crit : > > > >> Am 07.11.22 um 18:12 schrieb Dioumacor FAYE: > >>> hi everyone > >>> I wanted to transform this matlab code into python. If anyone can help > me > >>> please let me know. > >>> load /media/lpaosf/Dioumss/maman/data/precip_chirps_SEN_1981-2018.mat > >>> prcp = reshape(precip,[140*100,13879]); > >>> dates = datenum(1981,1,1):datenum(2018,12,31); > >>> date = datevec(dates); > >>> ind_mjja=find(date(:,2)>=5 & date(:,2)<=8);% May to Aug (May(31)+ > >> June(30)+ > >>> July(31)+ August(31)= 123 days) > >>> data_mjja=precp(:,ind_mjja); > >>> data_mjja_res=reshape(data_mjja,14000,123,38); > >> > >> which part do you have trouble with? > >> > >> > >> Christian > >> -- > >> https://mail.python.org/mailman/listinfo/python-list > >> > > > > > > -- > https://mail.python.org/mailman/listinfo/python-list > -- Bien ? vous, --------------------- ------------------ ----------------- -------------------- ----------------- Dioumacor FAYE doctorant au LPAOSF/ESP/UCAD/BP 5085 Dakar-Fann, S?n?gal. Tel labo: (00221) 33 825 93 64 Email: d.faye20171634 at zig.univ.sn Tel: +221773475098 +221783484308 Physicien en herbe Pseudo Skype: dioumacorfaye From hjp-python at hjp.at Wed Nov 9 09:52:51 2022 From: hjp-python at hjp.at (Peter J. Holzer) Date: Wed, 9 Nov 2022 15:52:51 +0100 Subject: How to manage python shebang on mixed systems? In-Reply-To: References: Message-ID: <20221109145251.ticjy25mdf3hrckg@hjp.at> On 2022-11-07 21:27:26 +0000, Chris Green wrote: > Barry Scott wrote: > > env is always available as /usr/bin/env - I think its spec'ed in posix that way. > > > > The only reason that things are in /bin are for systems that need a subset of > > programs to boot the system to point it can mount /usr. env is not going to be > > needed for that use case. > > > Given that the problem system is running a very old Linux I'm not sure > what chance there is that it's fully posix compliant. It doesn't have to be fully posix compliant. Just reasonably posix compliant. > If using "#!/usr/bin/env python3" is a way of avoiding problems if > python3 isn't in /usr/bin then why is it any better depending on env > being in /usr/bin. Because env is a standard unix utility which has been in the same place for 30 years or so and is unlikely to be somewhere else or missing completely. Python3 OTOH is not a standard unix utility. It may not be there at all or it may be installed in /usr/local or /opt or even in the user's home directory. (Yes, of course "standard unix utilities" may be missing, too. For example on an embedded system there might only be the bare minimum to run the application. I even had a redhat system once which didn't have grep installed.) (Personally I avoid using env: I don't want my scripts to depend on the PATH. But that's a different issue.) hp -- _ | Peter J. Holzer | Story must make more sense than reality. |_|_) | | | | | hjp at hjp.at | -- Charles Stross, "Creative writing __/ | http://www.hjp.at/ | challenge!" -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 833 bytes Desc: not available URL: From darkstone at o2online.de Wed Nov 9 19:02:44 2022 From: darkstone at o2online.de (darkstone at o2online.de) Date: Thu, 10 Nov 2022 00:02:44 +0000 Subject: =?utf-8?Q?Re:_Problems_with_IDLE_in_Windows_8.1_and_installer_x86_Version?= =?utf-8?Q?_3.10.8?= In-Reply-To: <202211041414.2A4EE2xL017716@mail264c50.megamailservers.eu> References: <202210311822.29VIMTpw130438@mail92c50.megamailservers.eu> <202210312138.29VLcBUQ008124@mail118c50.megamailservers.eu> <202211011649.2A1GnNrU115152@mail36c50.megamailservers.eu> <202211032129.2A3LTmtc065950@mail193c50.megamailservers.eu>, , <202211041414.2A4EE2xL017716@mail264c50.megamailservers.eu> Message-ID: <202211100003.2AA03LR5098382@mail266c50.megamailservers.eu> Is there no one who can help? Von: darkstone at o2online.de Gesendet: ?Freitag?, ?4?. ?November? ?2022 ?15?:?10 An: Eryk Sun Cc: python-list at python.org Yes, there is always the message ?modified successfull?, ?installed sucessfully?, but IDLE does?t start. I tried it with the newer Version, too. Ist 3.11.0 for 32 bit, but it also doesn?t work. Do you have other suggetions, that it works? Von: Eryk Sun Gesendet: ?Donnerstag?, ?3?. ?November? ?2022 ?22?:?50 An: darkstone at o2online.de Cc: python-list at python.org On 11/3/22, darkstone at o2online.de wrote: > Is there a reason, why it is not installed? Its the same check mark in the > installer like IDLE? Did you try what I suggested? Modify the installation to remove the tkinter/IDLE component. Then modify it again to select the component to be reinstalled. Also, try to repair the installation. This may reset any DLLs or extension modules that were missing or that were the wrong version. Ignore the suggestion from Nithish to install tkinter via pip. tkinter is part of the standard library and cannot be installed via pip. There is no tkinter package on the Python package index (pypi.org). -- https://mail.python.org/mailman/listinfo/python-list From list1 at tompassin.net Wed Nov 9 21:00:04 2022 From: list1 at tompassin.net (Thomas Passin) Date: Wed, 9 Nov 2022 21:00:04 -0500 Subject: Problems with IDLE in Windows 8.1 and installer x86 Version 3.10.8 In-Reply-To: <202211100003.2AA03LR5098382@mail266c50.megamailservers.eu> References: <202210311822.29VIMTpw130438@mail92c50.megamailservers.eu> <202210312138.29VLcBUQ008124@mail118c50.megamailservers.eu> <202211011649.2A1GnNrU115152@mail36c50.megamailservers.eu> <202211032129.2A3LTmtc065950@mail193c50.megamailservers.eu> <202211041414.2A4EE2xL017716@mail264c50.megamailservers.eu> <202211100003.2AA03LR5098382@mail266c50.megamailservers.eu> Message-ID: <59f3470c-fffb-4354-1712-67814f257e66@tompassin.net> On 11/9/2022 7:02 PM, darkstone at o2online.de wrote: > Is there no one who can help? Is there a reason why you tried to install a 32-bit version? Most personal computers are 64-bit ones these days. Also, I don't remember if you are running Windows or not. One problem for getting help from the list is that there have not been many details given. "Doesn't start" is not helpful. Are there error messages displayed on the terminal? How did you try to start it? Does Python run at all? A Python installation normally includes a batch file that launches idle. This batch file may not be on your path for one reason or another. If so, it would not run when you type "idle" at a command line. So the first thing to do is to figure out if you have either the Python program idle.py or idle.pyw, or the batch file idle.bat (for Windows) On Linux Mint, when I typed "idle" at a terminal, I got this message: "Command 'idle' not found, but can be installed with: sudo apt install idle" So that's how you would get it with that flavor of Linux. I'm going to walk through what I would probably do if I had the same problem on Windows (I'm going to assume that you are running Windows). It's a little long to write out, but not really that hard. Basically, there are only a few steps: 1. Find your Python installation; 2. Look in the installation location to see if the idle program is there; 3. If it is, try to run it and note any error messages. First you need to find out where your Python installation is located on your system disk. If you don't know, one way to find out is to run the following command in a console window: where /R %USERPROFILE% python.exe You may be surprised that there more several ones that you didn't expect, such as (on my computer): C:\Users\tom\AppData\Local\Microsoft\WindowsApps\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe\python.exe It seems that Windows has its own Python installation; that's not the one you want. You are looking for one that looks like this (with your own user name, of course, instead of mine): C:\Users\tom\AppData\Local\Programs\Python\Python310\python.exe Appdata\Local\Programs is where Python3 usually gets installed. Now we know that I have Python 3.10 at C:\Users\tom\AppData\Local\Programs\Python. You may be using a different version of Python; if so, just use that version instead. Idle is normally installed in the directory tree under python. Let's call the top of that tree %PYTH0N%. On my system, as we see above, that is C:\Users\tom\AppData\Local\Programs\Python\Python310. Idle should be at %PYTHON%\Lib\idlelib Open Windows explorer, and navigate to that directory. If you have that directory, then you should be able to run idle. If it doesn't exist, That's a problem and needs to be fixed, probably by a fresh install of Python. If it does, you will see the batch file idle.bat. Double-click it, and idle should run. If it does not, see below. That's not a convenient way to run idle time after time. Either you need to get idle on your path, or perhaps it will be available using the windows Start menu. Check that out by tapping the Windows key, then typing "idle" (without the quotes). It may be there. But look closely, for it may be the idle associated with a different version of Python than the one you want to use. For example, on my system I have Idle in the Start Menu, but only for Python 3.7 and not Python 3.10 which is the most recent version I have. If you double-clicked on the idle batch file but it failed to run, then you need to get any error messages. You need to run it from a console so you can see any output. Open a console. you want to run idle using python and not pythonw (because pythonw will not open a window). So in the console, type "python " (without quotes but with the space), then the path to the file. The path to the file is a lot to type, and it's easier to just drag the icon for the file (remember, it's idle.py) into the console window. Press the key and idle should run. If it doesn't, note any error messages. Then come back here and tell us what they were. It's possible that the "where" program didn't find your python installation. That would be because it's installed somewhere outside of your user tree, like Program Files. You can look again in the entire disk (assuming it's on the c: drive, which is almost certainly so): where /R c:\% python.exe > Von: darkstone at o2online.de > Gesendet: ?Freitag?, ?4?. ?November? ?2022 ?15?:?10 > An: Eryk Sun > Cc: python-list at python.org > > > > > > Yes, there is always the message ?modified successfull?, ?installed sucessfully?, but IDLE does?t start. I tried it with the newer Version, too. Ist 3.11.0 for 32 bit, but it also doesn?t work. Do you have other suggetions, that it works? > > > > > > > > Von: Eryk Sun > Gesendet: ?Donnerstag?, ?3?. ?November? ?2022 ?22?:?50 > An: darkstone at o2online.de > Cc: python-list at python.org > > > > > > On 11/3/22, darkstone at o2online.de wrote: >> Is there a reason, why it is not installed? Its the same check mark in the >> installer like IDLE? > > Did you try what I suggested? Modify the installation to remove the > tkinter/IDLE component. Then modify it again to select the component > to be reinstalled. Also, try to repair the installation. This may > reset any DLLs or extension modules that were missing or that were the > wrong version. > > Ignore the suggestion from Nithish to install tkinter via pip. tkinter > is part of the standard library and cannot be installed via pip. There > is no tkinter package on the Python package index (pypi.org). From wlfraed at ix.netcom.com Wed Nov 9 21:19:25 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Wed, 09 Nov 2022 21:19:25 -0500 Subject: Problems with IDLE in Windows 8.1 and installer x86 Version 3.10.8 References: <202211032129.2A3LTmtc065950@mail193c50.megamailservers.eu>, , <202211041414.2A4EE2xL017716@mail264c50.megamailservers.eu> <202211100003.2AA03LR5098382@mail266c50.megamailservers.eu> Message-ID: <9vmomh5pa5dt1698veq5943ak8uv8kc8pa@4ax.com> On Thu, 10 Nov 2022 00:02:44 +0000, declaimed the following: >Is there no one who can help? > Your problem description isn't detailed enough to even guess what you are finding incorrect. If you are on Windows, once you've done an install, shove the installer file off into some archive and don't touch it again unless you need to reinstall or repair the existing install. Do a search for idle.* Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. Try the new cross-platform PowerShell https://aka.ms/pscore6 PS C:\Users\Wulfraed> Get-ChildItem -Path C:\Python38\ -Recurse -Name -Filter "idle.*" Lib\idlelib\idle.bat Lib\idlelib\idle.py Lib\idlelib\idle.pyw Lib\idlelib\Icons\idle.ico Lib\site-packages\pythonwin\pywin\idle Lib\site-packages\pythonwin\pywin\IDLE.cfg PS C:\Users\Wulfraed> type C:\Python38\Lib\idlelib\idle.bat @echo off rem Start IDLE using the appropriate Python interpreter set CURRDIR=%~dp0 start "IDLE" "%CURRDIR%..\..\pythonw.exe" "%CURRDIR%idle.pyw" %1 %2 %3 %4 %5 %6 %7 %8 %9 PS C:\Users\Wulfraed> c:\python38\lib\idlelib\idle.bat ... opens something IDLE related (seems to be an interactive Python shell, but a configuration item allows setting it to open an edit window instead). Interesting -- I could have sworn there was a Python38 entry on the Windows start menu, but I seem to have removed it. I don't use IDLE, and that was the primary item in the Python38 entry. I normally use an old version of PythonWin (fyi: I'm using an old version of the ActiveState Python package). I also have PyCharm installed. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From eryksun at gmail.com Wed Nov 9 22:28:26 2022 From: eryksun at gmail.com (Eryk Sun) Date: Wed, 9 Nov 2022 21:28:26 -0600 Subject: Problems with IDLE in Windows 8.1 and installer x86 Version 3.10.8 In-Reply-To: <202211100003.2AA03LR5098382@mail266c50.megamailservers.eu> References: <202210311822.29VIMTpw130438@mail92c50.megamailservers.eu> <202210312138.29VLcBUQ008124@mail118c50.megamailservers.eu> <202211011649.2A1GnNrU115152@mail36c50.megamailservers.eu> <202211032129.2A3LTmtc065950@mail193c50.megamailservers.eu> <202211041414.2A4EE2xL017716@mail264c50.megamailservers.eu> <202211100003.2AA03LR5098382@mail266c50.megamailservers.eu> Message-ID: On 11/9/22, darkstone at o2online.de wrote: > Is there no one who can help? If you can't run IDLE via `py -3.10-32 -m idlelib`, then something isn't installed properly. You reported an error that IDLE fails to load because importing tkinter fails. Did you try `import tkinter` in the REPL? tkinter depends on the _tkinter extension module. Try `import _tkinter`. If the latter fails because of a missing DLL dependency, check the "DLLs" directory in the installation directory for the TCL/Tk dependencies. They're "tcl86t.dll" and "tk86t.dll" for Python 3.10. The installation directory should also have a "tcl" directory, which should contain "tcl8.6" and "tk8.6" directories among others, with many .tcl files. From list1 at tompassin.net Wed Nov 9 23:05:46 2022 From: list1 at tompassin.net (Thomas Passin) Date: Wed, 9 Nov 2022 23:05:46 -0500 Subject: Problems with IDLE in Windows 8.1 and installer x86 Version 3.10.8 In-Reply-To: <59f3470c-fffb-4354-1712-67814f257e66@tompassin.net> References: <202210311822.29VIMTpw130438@mail92c50.megamailservers.eu> <202210312138.29VLcBUQ008124@mail118c50.megamailservers.eu> <202211011649.2A1GnNrU115152@mail36c50.megamailservers.eu> <202211032129.2A3LTmtc065950@mail193c50.megamailservers.eu> <202211041414.2A4EE2xL017716@mail264c50.megamailservers.eu> <202211100003.2AA03LR5098382@mail266c50.megamailservers.eu> <59f3470c-fffb-4354-1712-67814f257e66@tompassin.net> Message-ID: <0956be32-a4a5-7aa2-e91d-116e94ba70c1@tompassin.net> Sorry about the typo at the end. If you need to search the entire disk, use this command instead of the one I had in my last post: where /R c:\ python.exe On 11/9/2022 9:00 PM, Thomas Passin wrote: > > On 11/9/2022 7:02 PM, darkstone at o2online.de wrote: >> Is there no one who can help? > > Is there a reason why you tried to install a 32-bit version?? Most > personal computers are 64-bit ones these days. Also, I don't remember if > you are running Windows or not. > > One problem for getting help from the list is that there have not been > many details given. "Doesn't start" is not helpful.? Are there error > messages displayed on the terminal?? How did you try to start it?? Does > Python run at all? > > A Python installation normally includes a batch file that launches idle. > ?This batch file may not be on your path for one reason or another.? If > so, it would not run when you type "idle" at a command line. > > So the first thing to do is to figure out if you have either the Python > program idle.py or idle.pyw, or the batch file idle.bat (for Windows) On > Linux Mint, when I typed "idle" at a terminal, I got this message: > > "Command 'idle' not found, but can be installed with: > > sudo apt install idle" > > So that's how you would get it with that flavor of Linux. > > I'm going to walk through what I would probably do if I had the same > problem on Windows (I'm going to assume that you are running Windows). > It's a little long to write out, but not really that hard.? Basically, > there are only a few steps: > > 1. Find your Python installation; > 2. Look in the installation location to see if the idle program is there; > 3.? If it is, try to run it and note any error messages. > > First you need to find out where your Python installation is located on > your system disk. If you don't know, one way to find out is to run the > following command in a console window: > > where /R %USERPROFILE% python.exe > > You may be surprised that there more several ones that you didn't > expect, such as (on my computer): > > C:\Users\tom\AppData\Local\Microsoft\WindowsApps\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe\python.exe > > It seems that Windows has its own Python installation; that's not the > one you want.? You are looking for one that looks like this (with your > own user name, of course, instead of mine): > > C:\Users\tom\AppData\Local\Programs\Python\Python310\python.exe > > Appdata\Local\Programs is where Python3 usually gets installed.? Now we > know that I have Python 3.10 at > C:\Users\tom\AppData\Local\Programs\Python.? You may be using a > different version of Python; if so, just use that version instead. > > Idle is normally installed in the directory tree under python.? Let's > call the top of that tree %PYTH0N%.? On my system, as we see above, that > is C:\Users\tom\AppData\Local\Programs\Python\Python310.? Idle should be at > > %PYTHON%\Lib\idlelib > > Open Windows explorer, and navigate to that directory. If you have that > directory, then you should be able to run idle.? If it doesn't exist, > That's a problem and needs to be fixed, probably by a fresh install of > Python.? If it does, you will see the batch file idle.bat.? Double-click > it, and idle should run.? If it does not, see below. > > That's not a convenient way to run idle time after time.? Either you > need to get idle on your path, or perhaps it will be available using the > windows Start menu.? Check that out by tapping the Windows key, then > typing "idle" (without the quotes).? It may be there.? But look closely, > for it may be the idle associated with a different version of Python > than the one you want to use.? For example, on my system I have Idle in > the Start Menu, but only for Python 3.7 and not Python 3.10 which is the > most recent version I have. > > If you double-clicked on the idle batch file but it failed to run, then > you need to get any error messages.? You need to run it from a console > so you can see any output.? Open a console. you want to run idle using > python and not pythonw (because pythonw will not open a window).? So in > the console, type "python " (without quotes but with the space), then > the path to the file. > > The path to the file is a lot to type, and it's easier to just drag the > icon for the file (remember, it's idle.py) into the console window. > Press the key and idle should run.? If it doesn't, note any > error messages.? Then come back here and tell us what they were. > > It's possible that the "where" program didn't find your python > installation.? That would be because it's installed somewhere outside of > your user tree, like Program Files.? You can look again in the entire > disk (assuming it's on the c: drive, which is almost certainly so): > > where /R c:\% python.exe > >> Von: darkstone at o2online.de >> Gesendet: ?Freitag?, ?4?. ?November? ?2022 ?15?:?10 >> An: Eryk Sun >> Cc: python-list at python.org >> >> >> >> >> >> Yes, there is always the message ?modified successfull?, ?installed >> sucessfully?, but IDLE does?t start. I tried it with the newer >> Version, too. Ist 3.11.0 for 32 bit, but it also doesn?t work. Do you >> have other suggetions, that it works? >> >> >> >> >> >> >> >> Von: Eryk Sun >> Gesendet: ?Donnerstag?, ?3?. ?November? ?2022 ?22?:?50 >> An: darkstone at o2online.de >> Cc: python-list at python.org >> >> >> >> >> >> On 11/3/22, darkstone at o2online.de wrote: >>> Is there a reason, why it is not installed? Its the same check mark >>> in the >>> installer like IDLE? >> >> Did you try what I suggested? Modify the installation to remove the >> tkinter/IDLE component. Then modify it again to select the component >> to be reinstalled. Also, try to repair the installation. This may >> reset any DLLs or extension modules that were missing or that were the >> wrong version. >> >> Ignore the suggestion from Nithish to install tkinter via pip. tkinter >> is part of the standard library and cannot be installed via pip. There >> is no tkinter package on the Python package index (pypi.org). > From PythonList at DancesWithMice.info Fri Nov 11 03:54:26 2022 From: PythonList at DancesWithMice.info (dn) Date: Fri, 11 Nov 2022 21:54:26 +1300 Subject: Argument name should be lowercase Message-ID: <0eba3f9d-c89c-062e-425a-54aea7216b11@DancesWithMice.info> PyCharm is warning against using an identifier of all upper-case letters as a function's parameter, saying "Argument name should be lowercase". (weak, code smell) The application consists of three+ files: - configuration - mainline script - module of workbook functions The mainline reads the configuration parameters to set the application's environment. All of the config/settings are constants. Some of them appear as a dictionary (PRICES_WORKBOOK) defining a workbook's (spreadsheet's) parameters, eg the filename, which work-sheet to use, etc. The mainline calls the relevant functions from within the module, as-needed:- import prices_workbook as pw ... product_prices = pw.build_product_prices_dictionary( PRICES_WORKBOOK ) The module's function definition is: def build_product_prices_dictionary( WORKBOOK_DEFINITIONS:dict )->dict: ... price_array = xl.iget_array( file_name=WORKBOOK_DEFINITIONS[ "file_name" ], ... (the function def is flagged, as above) A quick scan of PEP-008 failed to yield anything relevant. Why is this frowned upon as poor Python, or a matter of style? Yes, a dict is mutable, but the upper-case denoting a constant indicates that none of its values are to be changed by the programmer. As far as the function is concerned, the dict and its contents are constants. (but the dict can't be treated as a global ENV[IRONMENT] object, because it has to cross into the module's namespace) Is passing the dict as an argument/parameter considered to be incompatible with its designation as a constant? Perhaps the style should be more enum-like, ie the dict's name in lower-case, with the key-named in upper case, eg workbook_definitions[ "FILE_NAME" ] Am not particularly concerned by the IDE raising this as a 'problem' - will quite happily ignore and carry-on; but am curious as to the logic behind the analysis - and why it doesn't come readily to mind. Advice, comments, critique welcome! -- Regards, =dn From gweatherby at uchc.edu Fri Nov 11 06:28:53 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Fri, 11 Nov 2022 11:28:53 +0000 Subject: Argument name should be lowercase In-Reply-To: <0eba3f9d-c89c-062e-425a-54aea7216b11@DancesWithMice.info> References: <0eba3f9d-c89c-062e-425a-54aea7216b11@DancesWithMice.info> Message-ID: PEP 8 doesn?t explicitly list a naming convention for function parameters, but every example shows them as lowercase, even though the function doesn?t modify them. See also the Python tutorial ( https://docs.python.org/3/tutorial/controlflow.html#defining-functions ), which also shows all parameters as lowercase. I?d personally find it weird to see an all-cap parameter (Why are you yelling?). I expect ALL_CAPS to be hardcoded values. From: Python-list on behalf of dn Date: Friday, November 11, 2022 at 3:56 AM To: 'Python' Subject: Argument name should be lowercase *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** PyCharm is warning against using an identifier of all upper-case letters as a function's parameter, saying "Argument name should be lowercase". (weak, code smell) The application consists of three+ files: - configuration - mainline script - module of workbook functions The mainline reads the configuration parameters to set the application's environment. All of the config/settings are constants. Some of them appear as a dictionary (PRICES_WORKBOOK) defining a workbook's (spreadsheet's) parameters, eg the filename, which work-sheet to use, etc. The mainline calls the relevant functions from within the module, as-needed:- import prices_workbook as pw ... product_prices = pw.build_product_prices_dictionary( PRICES_WORKBOOK ) The module's function definition is: def build_product_prices_dictionary( WORKBOOK_DEFINITIONS:dict )->dict: ... price_array = xl.iget_array( file_name=WORKBOOK_DEFINITIONS[ "file_name" ], ... (the function def is flagged, as above) A quick scan of PEP-008 failed to yield anything relevant. Why is this frowned upon as poor Python, or a matter of style? Yes, a dict is mutable, but the upper-case denoting a constant indicates that none of its values are to be changed by the programmer. As far as the function is concerned, the dict and its contents are constants. (but the dict can't be treated as a global ENV[IRONMENT] object, because it has to cross into the module's namespace) Is passing the dict as an argument/parameter considered to be incompatible with its designation as a constant? Perhaps the style should be more enum-like, ie the dict's name in lower-case, with the key-named in upper case, eg workbook_definitions[ "FILE_NAME" ] Am not particularly concerned by the IDE raising this as a 'problem' - will quite happily ignore and carry-on; but am curious as to the logic behind the analysis - and why it doesn't come readily to mind. Advice, comments, critique welcome! -- Regards, =dn -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!h56Cia7ERYDmxaCnEo0k9hfXz-mTJrz43UqHjbfhwLjutjhQE1QU975lUXTBf38la5kXAkBHdzyzOY4XAObbAPOa-ebC-HNY$ From list1 at tompassin.net Fri Nov 11 09:09:51 2022 From: list1 at tompassin.net (Thomas Passin) Date: Fri, 11 Nov 2022 09:09:51 -0500 Subject: Argument name should be lowercase In-Reply-To: <0eba3f9d-c89c-062e-425a-54aea7216b11@DancesWithMice.info> References: <0eba3f9d-c89c-062e-425a-54aea7216b11@DancesWithMice.info> Message-ID: This is a matter of convention. Historically, many language practitioners got used to using all-caps for key constants. This makes it easier to tell when you are using (or misusing) one, for one thing. For myself, I also will use all-caps for quasi-constants, ones that are set only once, for example from command-line parameters. In your example,I would not use all-caps for the formal parameter in the function definition. I would have written def build_product_prices_dictionary(workbook_definitions:dict )->dict: ... price_array = xl.iget_array( file_name=workbook_definitions[ "file_name" ], There is no value in making a formal parameter's name be all-caps, since even if it were the same string as an actual global parameter, it would not mean that actual parameter: it is only a placeholder. There could even be a negative consequence, because later you might forget and think that the formal parameter's name meant that the global parameter would be used automatically in the function call, as if it were a default parameter. At a minimum, this could lead to confusion about your intent, at a maximum it could end up being a bug. Perhaps you wrote it that way as a reminder which dict to use. If so, that kind of information would better go into the docstring: def build_product_prices_dictionary(workbook_definitions:dict) -> dict: """Return a dictionary of product prices given their definitions. ARGUMENT workbook_definitions -- a dict of product definitions, typically the global WORKBOOK_DEFINITIONS. """ # ... Alternatively, you could make the global be the default for the argument: def build_product_prices_dictionary(workbook_definitions:dict = WORKBOOK_DEFINITIONS)->dict: This might or might not make sense depending on how you plan to use the function. So basically, PyCharm is suggesting that you use a clearer, less problem-prone style of naming. I'd heed the advice. It would also be in line with what many other programmers are used to reading, and that's a positive advantage. On 11/11/2022 3:54 AM, dn wrote: > PyCharm is warning against using an identifier of all upper-case letters > as a function's parameter, saying "Argument name should be lowercase". > (weak, code smell) > > > The application consists of three+ files: > - configuration > - mainline script > - module of workbook functions > > The mainline reads the configuration parameters to set the application's > environment. All of the config/settings are constants. Some of them > appear as a dictionary (PRICES_WORKBOOK) defining a workbook's > (spreadsheet's) parameters, eg the filename, which work-sheet to use, etc. > > > The mainline calls the relevant functions from within the module, > as-needed:- > > import prices_workbook as pw > ... > product_prices = pw.build_product_prices_dictionary( PRICES_WORKBOOK ) > > > The module's function definition is: > > def build_product_prices_dictionary( WORKBOOK_DEFINITIONS:dict )->dict: > ... > ??? price_array = xl.iget_array( > ??????? file_name=WORKBOOK_DEFINITIONS[ "file_name" ], > ??????? ... > > (the function def is flagged, as above) > > > A quick scan of PEP-008 failed to yield anything relevant. Why is this > frowned upon as poor Python, or a matter of style? > > Yes, a dict is mutable, but the upper-case denoting a constant indicates > that none of its values are to be changed by the programmer. > > As far as the function is concerned, the dict and its contents are > constants. > (but the dict can't be treated as a global ENV[IRONMENT] object, because > it has to cross into the module's namespace) > > > Is passing the dict as an argument/parameter considered to be > incompatible with its designation as a constant? > > Perhaps the style should be more enum-like, ie the dict's name in > lower-case, with the key-named in upper case, eg > > ??? workbook_definitions[ "FILE_NAME" ] > > > Am not particularly concerned by the IDE raising this as a 'problem' - > will quite happily ignore and carry-on; but am curious as to the logic > behind the analysis - and why it doesn't come readily to mind. > > Advice, comments, critique welcome! > From python at mrabarnett.plus.com Fri Nov 11 10:03:32 2022 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 11 Nov 2022 15:03:32 +0000 Subject: Argument name should be lowercase In-Reply-To: <0eba3f9d-c89c-062e-425a-54aea7216b11@DancesWithMice.info> References: <0eba3f9d-c89c-062e-425a-54aea7216b11@DancesWithMice.info> Message-ID: <83024165-bec7-16f5-02d9-b63e978c666c@mrabarnett.plus.com> On 2022-11-11 08:54, dn wrote: [snip] > > The module's function definition is: > > def build_product_prices_dictionary( WORKBOOK_DEFINITIONS:dict )->dict: > ... > price_array = xl.iget_array( > file_name=WORKBOOK_DEFINITIONS[ "file_name" ], > ... > > (the function def is flagged, as above) > > > A quick scan of PEP-008 failed to yield anything relevant. Why is this > frowned upon as poor Python, or a matter of style? > > Yes, a dict is mutable, but the upper-case denoting a constant indicates > that none of its values are to be changed by the programmer. > > As far as the function is concerned, the dict and its contents are > constants. > (but the dict can't be treated as a global ENV[IRONMENT] object, because > it has to cross into the module's namespace) > [snip] I think the problem is that the dict _is_ mutable, so it's not a constant; it's read-only, which is not the same thing. From arequipeno at gmail.com Fri Nov 11 11:21:03 2022 From: arequipeno at gmail.com (Ian Pilcher) Date: Fri, 11 Nov 2022 10:21:03 -0600 Subject: Superclass static method name from subclass Message-ID: Is it possible to access the name of a superclass static method, when defining a subclass attribute, without specifically naming the super- class? Contrived example: class SuperClass(object): @staticmethod def foo(): pass class SubClass(SuperClass): bar = SuperClass.foo ^^^^^^^^^^ Is there a way to do this without specifically naming 'SuperClass'? -- ======================================================================== Google Where SkyNet meets Idiocracy ======================================================================== From gweatherby at uchc.edu Fri Nov 11 11:25:22 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Fri, 11 Nov 2022 16:25:22 +0000 Subject: Argument name should be lowercase In-Reply-To: <0eba3f9d-c89c-062e-425a-54aea7216b11@DancesWithMice.info> References: <0eba3f9d-c89c-062e-425a-54aea7216b11@DancesWithMice.info> Message-ID: If you wanted to document/enforce the input argument is immutable, you could do one of the following. You?d get a type warning in PyCharm with bad_func or equivalent, and bad_func2 will fail at runtime. def bad_func(x: typing.Mapping): """Get type warning if x modified""" x[3] = 7 def bad_func2(x: types.MappingProxyType): """Get runtime error if x modified""" if not isinstance(x, types.MappingProxyType): x = types.MappingProxyType(x) x[3] = 8 From: Python-list on behalf of dn Date: Friday, November 11, 2022 at 3:56 AM To: 'Python' Subject: Argument name should be lowercase *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** PyCharm is warning against using an identifier of all upper-case letters as a function's parameter, saying "Argument name should be lowercase". (weak, code smell) The application consists of three+ files: - configuration - mainline script - module of workbook functions The mainline reads the configuration parameters to set the application's environment. All of the config/settings are constants. Some of them appear as a dictionary (PRICES_WORKBOOK) defining a workbook's (spreadsheet's) parameters, eg the filename, which work-sheet to use, etc. The mainline calls the relevant functions from within the module, as-needed:- import prices_workbook as pw ... product_prices = pw.build_product_prices_dictionary( PRICES_WORKBOOK ) The module's function definition is: def build_product_prices_dictionary( WORKBOOK_DEFINITIONS:dict )->dict: ... price_array = xl.iget_array( file_name=WORKBOOK_DEFINITIONS[ "file_name" ], ... (the function def is flagged, as above) A quick scan of PEP-008 failed to yield anything relevant. Why is this frowned upon as poor Python, or a matter of style? Yes, a dict is mutable, but the upper-case denoting a constant indicates that none of its values are to be changed by the programmer. As far as the function is concerned, the dict and its contents are constants. (but the dict can't be treated as a global ENV[IRONMENT] object, because it has to cross into the module's namespace) Is passing the dict as an argument/parameter considered to be incompatible with its designation as a constant? Perhaps the style should be more enum-like, ie the dict's name in lower-case, with the key-named in upper case, eg workbook_definitions[ "FILE_NAME" ] Am not particularly concerned by the IDE raising this as a 'problem' - will quite happily ignore and carry-on; but am curious as to the logic behind the analysis - and why it doesn't come readily to mind. Advice, comments, critique welcome! -- Regards, =dn -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!h56Cia7ERYDmxaCnEo0k9hfXz-mTJrz43UqHjbfhwLjutjhQE1QU975lUXTBf38la5kXAkBHdzyzOY4XAObbAPOa-ebC-HNY$ From lal at solute.de Fri Nov 11 11:46:46 2022 From: lal at solute.de (Lars Liedtke) Date: Fri, 11 Nov 2022 17:46:46 +0100 Subject: Superclass static method name from subclass In-Reply-To: References: Message-ID: <824437f1-a65d-1819-512e-d024d0bbfa1f@solute.de> yes, just use SubClass.foo at least this works for me: class SuperClass: @staticmethod def test(): print("yay") class SubClass(SuperClass): def __init__(self): super().__init__() SubClass.test() subclass = SubClass() Output: python3.11 test.py yay Cheers Lars Lars Liedtke Software Entwickler [Tel.] +49 721 98993- [Fax] +49 721 98993- [E-Mail] lal at solute.de solute GmbH Zeppelinstra?e 15 76185 Karlsruhe Germany [Logo Solute] Marken der solute GmbH | brands of solute GmbH [Marken] [Advertising Partner] Gesch?ftsf?hrer | Managing Director: Dr. Thilo Gans, Bernd Vermaaten Webseite | www.solute.de Sitz | Registered Office: Karlsruhe Registergericht | Register Court: Amtsgericht Mannheim Registernummer | Register No.: HRB 110579 USt-ID | VAT ID: DE234663798 Informationen zum Datenschutz | Information about privacy policy https://www.solute.de/ger/datenschutz/grundsaetze-der-datenverarbeitung.php Am 11.11.22 um 17:21 schrieb Ian Pilcher: Is it possible to access the name of a superclass static method, when defining a subclass attribute, without specifically naming the super- class? Contrived example: class SuperClass(object): @staticmethod def foo(): pass class SubClass(SuperClass): bar = SuperClass.foo ^^^^^^^^^^ Is there a way to do this without specifically naming 'SuperClass'? From list1 at tompassin.net Fri Nov 11 12:02:37 2022 From: list1 at tompassin.net (Thomas Passin) Date: Fri, 11 Nov 2022 12:02:37 -0500 Subject: Superclass static method name from subclass In-Reply-To: References: Message-ID: <1686043e-1dbb-e284-9f76-f8be1c0e63b4@tompassin.net> You can define a classmethod in SubClass that seems to do the job: class SuperClass(object): @staticmethod def spam(): # "spam" and "eggs" are a Python tradition print('spam from SuperClass') class SubClass(SuperClass): @classmethod def eggs(self): super().spam() SubClass.eggs() # Prints "spam from SuperClass" If you try to make it a @staticmethod, though, you would need to provide a class argument to super(), but a staticmethod does not pass one in. On 11/11/2022 11:21 AM, Ian Pilcher wrote: > Is it possible to access the name of a superclass static method, when > defining a subclass attribute, without specifically naming the super- > class? > > Contrived example: > > ? class SuperClass(object): > ????? @staticmethod > ????? def foo(): > ????????? pass > > ? class SubClass(SuperClass): > ????? bar = SuperClass.foo > ??????????? ^^^^^^^^^^ > > Is there a way to do this without specifically naming 'SuperClass'? > From dieter at handshake.de Fri Nov 11 12:29:35 2022 From: dieter at handshake.de (Dieter Maurer) Date: Fri, 11 Nov 2022 18:29:35 +0100 Subject: Superclass static method name from subclass In-Reply-To: References: Message-ID: <25454.34431.496697.98206@ixdm.fritz.box> Ian Pilcher wrote at 2022-11-11 10:21 -0600: >Is it possible to access the name of a superclass static method, when >defining a subclass attribute, without specifically naming the super- >class? > >Contrived example: > > class SuperClass(object): > @staticmethod > def foo(): > pass > > class SubClass(SuperClass): > bar = SuperClass.foo > ^^^^^^^^^^ > >Is there a way to do this without specifically naming 'SuperClass'? Unless you overrode it, you can use `self.foo` or `SubClass.foo`; if you overrode it (and you are using either Python 3 or Python 2 and a so called "new style class"), you can use `super`. When you use `super` outside a method definition, you must call it with parameters. From 12jessicasmith34 at gmail.com Thu Nov 10 19:14:15 2022 From: 12jessicasmith34 at gmail.com (Jessica Smith) Date: Thu, 10 Nov 2022 18:14:15 -0600 Subject: Strange UnicodeEncodeError in Windows image on Azure DevOps and Github Message-ID: Hello, Weird issue I've found on Windows images in Azure Devops Pipelines and Github actions. Printing Unicode characters fails on these images because, for some reason, the encoding is mapped to cp1252. What is particularly weird about the code page being set to 1252 is that if you execute "chcp" it shows that the code page is 65001. At the end of this email are the cleaned up logs from GH actions. The actions are very simple - print out unicode characters using echo to prove the characters can be printed to the console. The rest of the commands are in Python, and they include printing out the "encoding" variable of sys.stdout, as well as printing sys.flags and sys.getfilesystemencoding. Then print the same unicode character using print, which causes a UnicodEncodeError because the character isn't in the cp1252 charmap. I've also uploaded the logs to pastebin here: https://pastebin.com/ExzGRHav I also uploaded a screenshot to imgur, since the logs are not the easiest to read. https://imgur.com/a/dhvLWOJ I'm trying to determine why this issue only happens on these images - I can replicate it on multiple versions of Python (from 3.9 to 3.7 at least, haven't tried more), but I can't replicate this on my own machines. There are a few issues on GH regarding this issue but they seem to stay open since they are hard to replicate. Here are the ones I have stumbled upon while researching this. https://github.com/databrickslabs/dbx/issues/455 https://github.com/PrefectHQ/prefect/issues/5754 https://github.com/pallets/click/issues/2121 Any insight or ideas on how to test and validate the cause would be great. I'm pulling my hair out trying to find the root cause of this - not because it really matters to any of my processes but because it is weird and broken. Thanks for any help, Jessica Begin Logs: 2022-11-10T23:54:51.7272453Z Requested labels: windows-latest 2022-11-10T23:54:51.7272494Z Job defined at: NodeJSmith/wsl_home/.github/workflows/blank.yml at refs/heads/main 2022-11-10T23:54:51.7272514Z Waiting for a runner to pick up this job... 2022-11-10T23:54:52.3387510Z Job is waiting for a hosted runner to come online. 2022-11-10T23:55:04.8574435Z Job is about to start running on the hosted runner: Hosted Agent (hosted) 2022-11-10T23:55:15.8332600Z Current runner version: '2.298.2' 2022-11-10T23:55:15.8366947Z ##[group]Operating System 2022-11-10T23:55:15.8367650Z Microsoft Windows Server 2022 2022-11-10T23:55:15.8367954Z 10.0.20348 2022-11-10T23:55:15.8368389Z Datacenter 2022-11-10T23:55:15.8368696Z ##[endgroup] 2022-11-10T23:55:15.8369023Z ##[group]Runner Image 2022-11-10T23:55:15.8369654Z Image: windows-2022 2022-11-10T23:55:15.8369931Z Version: 20221027.1 2022-11-10T23:55:15.8370539Z Included Software: https://github.com/actions/runner-images/blob/win22/20221027.1/images/win/Windows2022-Readme.md 2022-11-10T23:55:15.8371174Z Image Release: https://github.com/actions/runner-images/releases/tag/win22%2F20221027.1 2022-11-10T23:55:15.8371622Z ##[endgroup] 2022-11-10T23:55:15.8371955Z ##[group]Runner Image Provisioner 2022-11-10T23:55:15.8372277Z 2.0.91.1 2022-11-10T23:55:15.8372514Z ##[endgroup] 2022-11-10T23:55:16.3619998Z ##[group]Run echo " ??? ID:" 2022-11-10T23:55:16.3620626Z echo " ??? ID:" 2022-11-10T23:55:16.3927292Z shell: C:\Program Files\PowerShell\7\pwsh.EXE -command ". '{0}'" 2022-11-10T23:55:16.3927894Z ##[endgroup] 2022-11-10T23:55:32.9958751Z ??? ID: 2022-11-10T23:55:34.0835652Z ##[group]Run chcp 2022-11-10T23:55:34.0836104Z chcp 2022-11-10T23:55:34.0878901Z shell: C:\Program Files\PowerShell\7\pwsh.EXE -command ". '{0}'" 2022-11-10T23:55:34.0879350Z ##[endgroup] 2022-11-10T23:55:34.4878247Z Active code page: 65001 2022-11-10T23:55:34.7917219Z ##[group]Run python -c "import sys; print('sys.stdout.encoding', sys.stdout.encoding); print('sys.flags',sys.flags);print('sys.getfilesystemencoding',sys.getfilesystemencoding())" 2022-11-10T23:55:34.7918148Z python -c "import sys; print('sys.stdout.encoding', sys.stdout.encoding); print('sys.flags',sys.flags);print('sys.getfilesystemencoding',sys.getfilesystemencoding())" 2022-11-10T23:55:34.7960873Z shell: C:\Program Files\PowerShell\7\pwsh.EXE -command ". '{0}'" 2022-11-10T23:55:34.7961202Z ##[endgroup] 2022-11-10T23:55:36.2324642Z sys.stdout.encoding cp1252 2022-11-10T23:55:36.2325910Z sys.flags sys.flags(debug=0, inspect=0, interactive=0, optimize=0, dont_write_bytecode=0, no_user_site=0, no_site=0, ignore_environment=0, verbose=0, bytes_warning=0, quiet=0, hash_randomization=1, isolated=0, dev_mode=False, utf8_mode=0) 2022-11-10T23:55:36.2327055Z sys.getfilesystemencoding utf-8 2022-11-10T23:55:36.4553957Z ##[group]Run python -c "print('??? ID:')" 2022-11-10T23:55:36.4554395Z python -c "print('??? ID:')" 2022-11-10T23:55:36.4595413Z shell: C:\Program Files\PowerShell\7\pwsh.EXE -command ". '{0}'" 2022-11-10T23:55:36.4595740Z ##[endgroup] 2022-11-10T23:55:36.8739309Z Traceback (most recent call last): 2022-11-10T23:55:37.1316425Z File "", line 1, in 2022-11-10T23:55:37.1317452Z File "C:\hostedtoolcache\windows\Python\3.9.13\x64\lib\encodings\cp1252.py", line 19, in encode 2022-11-10T23:55:37.1324632Z return codecs.charmap_encode(input,self.errors,encoding_table)[0] 2022-11-10T23:55:37.1325913Z UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-2: character maps to From examguidepub at gmail.com Thu Nov 10 10:23:42 2022 From: examguidepub at gmail.com (Exam Guide Publishers) Date: Thu, 10 Nov 2022 07:23:42 -0800 (PST) Subject: What is the reason from different output generate using logical 'and' and 'or' operator in Python 3.10.8 In-Reply-To: References: Message-ID: <06dec521-a7c8-4c3f-9960-08d3f8f8aacbn@googlegroups.com> On Tuesday, 8 November 2022 at 05:36:49 UTC+5:30, David wrote: > On Tue, 8 Nov 2022 at 03:08, ICT Ezy wrote: > > > Please explain how to generate different output in following logical operations > > > >>> 0 and True > > 0 > > >>> 0 or True > > True > > >>> 1 and True > > True > > >>> 1 or True > > 1 > Hi, > > The exact explanation of how 'and' and 'or' behave can be read here: > https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not > The "Notes" there explain what you see. Thank you very much, I understood Cleary. Before I have doubt, but now clear. From nospam at dfs.com Fri Nov 11 02:22:34 2022 From: nospam at dfs.com (DFS) Date: Fri, 11 Nov 2022 02:22:34 -0500 Subject: Need max values in list of tuples, based on position Message-ID: [(0,11), (1,1), (2,1), (0,1) , (1,41), (2,2), (0,9) , (1,3), (2,12)] The set of values in elements[0] is {0,1,2} I want the set of max values in elements[1]: {11,41,12} From Pancho.Jones at proton.me Fri Nov 11 05:02:34 2022 From: Pancho.Jones at proton.me (Pancho) Date: Fri, 11 Nov 2022 10:02:34 +0000 Subject: Need max values in list of tuples, based on position In-Reply-To: References: Message-ID: On 11/11/2022 07:22, DFS wrote: > > [(0,11), (1,1),? (2,1), > ?(0,1) , (1,41), (2,2), > ?(0,9) , (1,3),? (2,12)] > > The set of values in elements[0] is {0,1,2} > > I want the set of max values in elements[1]: {11,41,12} > > > def build_max_dict( tups): dict = {} for (a,b) in tups: if (a in dict): if (b>dict[a]): dict[a]=b else: dict[a]=b return(sorted(dict.values())) From wlfraed at ix.netcom.com Fri Nov 11 12:49:37 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 11 Nov 2022 12:49:37 -0500 Subject: Need max values in list of tuples, based on position References: Message-ID: <6n2tmhdq21nqd4lqnb6mo7srkullne1not@4ax.com> On Fri, 11 Nov 2022 02:22:34 -0500, DFS declaimed the following: > >[(0,11), (1,1), (2,1), > (0,1) , (1,41), (2,2), > (0,9) , (1,3), (2,12)] > >The set of values in elements[0] is {0,1,2} > >I want the set of max values in elements[1]: {11,41,12} Do they have to be IN THAT ORDER? >>> data = [(0,11), (1,1), (2,1), (0,1) , (1,41), (2,2), (0,9) , (1,3), (2,12)] >>> reshape = list(zip(*data)) >>> result = sorted(reshape[1])[-3:] >>> result [11, 12, 41] -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From nospam at dfs.com Fri Nov 11 13:53:44 2022 From: nospam at dfs.com (DFS) Date: Fri, 11 Nov 2022 13:53:44 -0500 Subject: Need max values in list of tuples, based on position In-Reply-To: <6n2tmhdq21nqd4lqnb6mo7srkullne1not@4ax.com> References: <6n2tmhdq21nqd4lqnb6mo7srkullne1not@4ax.com> Message-ID: On 11/11/2022 12:49 PM, Dennis Lee Bieber wrote: > On Fri, 11 Nov 2022 02:22:34 -0500, DFS declaimed the > following: > >> >> [(0,11), (1,1), (2,1), >> (0,1) , (1,41), (2,2), >> (0,9) , (1,3), (2,12)] >> >> The set of values in elements[0] is {0,1,2} >> >> I want the set of max values in elements[1]: {11,41,12} > > Do they have to be IN THAT ORDER? Yes. >>>> data = [(0,11), (1,1), (2,1), (0,1) , (1,41), (2,2), (0,9) , (1,3), (2,12)] >>>> reshape = list(zip(*data)) >>>> result = sorted(reshape[1])[-3:] >>>> result > [11, 12, 41] > > > From Pancho.Jones at proton.me Fri Nov 11 14:22:04 2022 From: Pancho.Jones at proton.me (Pancho) Date: Fri, 11 Nov 2022 19:22:04 +0000 Subject: Need max values in list of tuples, based on position In-Reply-To: References: <6n2tmhdq21nqd4lqnb6mo7srkullne1not@4ax.com> Message-ID: On 11/11/2022 18:53, DFS wrote: > On 11/11/2022 12:49 PM, Dennis Lee Bieber wrote: >> On Fri, 11 Nov 2022 02:22:34 -0500, DFS declaimed the >> following: >> >>> >>> [(0,11), (1,1),? (2,1), >>> ? (0,1) , (1,41), (2,2), >>> ? (0,9) , (1,3),? (2,12)] >>> >>> The set of values in elements[0] is {0,1,2} >>> >>> I want the set of max values in elements[1]: {11,41,12} >> >> ????Do they have to be IN THAT ORDER? > > Yes. > Sets aren't ordered, which is why I gave my answer as a list. A wrongly ordered list, but I thought it rude to point out my own error, as no one else had. :-) Assuming you want numeric order of element[0], rather than first occurrence order of the element[0] in the original tuple list. In this example, they are both the same. Here is a corrected version from collections import OrderedDict def build_max_dict( tups): dict = OrderedDict() for (a,b) in tups: if (a in dict): if (b>dict[a]): dict[a]=b else: dict[a]=b return(dict.values()) This solution giving the answer as type odict_values. I'm not quite sure what this type is, but it seems to be a sequence/iterable/enumerable type, whatever the word is in Python. Caveat: I know very little about Python. From nospam at dfs.com Fri Nov 11 14:56:41 2022 From: nospam at dfs.com (DFS) Date: Fri, 11 Nov 2022 14:56:41 -0500 Subject: Need max values in list of tuples, based on position In-Reply-To: References: Message-ID: On 11/11/2022 7:50 AM, Stefan Ram wrote: > Pancho writes: >> def build_max_dict( tups): >> dict = {} >> for (a,b) in tups: >> if (a in dict): >> if (b>dict[a]): >> dict[a]=b >> else: >> dict[a]=b >> return(sorted(dict.values())) > > Or, > > import itertools > import operator > > def build_max_dict( tups ): > key = operator.itemgetter( 0 ) > groups = itertools.groupby( sorted( tups, key=key ), key ) > return set( map( lambda x: max( x[ 1 ])[ 1 ], groups )) FYI, neither of those solutions work: Pancho: 11, 12, 41 You : 41, 11, 12 The answer I'm looking for is 11,41,12 Maybe a tuple with the same info presented differently would be easier to tackle: orig: [(0, 11), (1, 1), (2, 1), (0, 1), (1, 41), (2, 2), (0, 9), (1, 3), (2, 12)] new: [(11,1,1), (1,41,2), (9,3,12)] I'm still looking for the max value in each position across all elements of the tuple, so the answer is still 11,41,12. Edit: found a solution online: ----------------------------------------------------------------- x = [(11,1,1),(1,41,2),(9,3,12)] maxvals = [0]*len(x[0]) for e in x: maxvals = [max(w,int(c)) for w,c in zip(maxvals,e)] print(maxvals) [11,41,12] ----------------------------------------------------------------- So now the challenge is making it a one-liner! Thanks From rosuav at gmail.com Fri Nov 11 15:20:58 2022 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 12 Nov 2022 07:20:58 +1100 Subject: Argument name should be lowercase In-Reply-To: References: <0eba3f9d-c89c-062e-425a-54aea7216b11@DancesWithMice.info> Message-ID: On Sat, 12 Nov 2022 at 06:42, Stefan Ram wrote: > > "Weatherby,Gerard" writes: > >I'd personally find it weird to see an all-cap parameter > > In the source code of the standard library, all-caps > notation is used for a parameter name sometimes > if that parameter name is "URL" or sometimes > when it is being initialized from an all-caps name as in: > > |def __del__(self, _warn=warnings.warn, RUN=RUN): > | if self._state == RUN: > ... > from "pool.py". > > ("RUN=RUN" makes RUN have the value "RUN" had > at the time of the definition of the function.) > There are a few reasons to do that "snapshot" trick. The most common is performance, but in this case, my guess is that (since it's a __del__ method) it's to ensure that the objects are still referenced when this function is called - to stop them getting disposed of prematurely. Very rare, but important occasionally. ChrisA From arequipeno at gmail.com Fri Nov 11 16:29:13 2022 From: arequipeno at gmail.com (Ian Pilcher) Date: Fri, 11 Nov 2022 15:29:13 -0600 Subject: Dealing with non-callable classmethod objects Message-ID: I am trying to figure out a way to gracefully deal with uncallable classmethod objects. The class hierarchy below illustrates the issue. (Unfortunately, I haven't been able to come up with a shorter example.) import datetime class DUID(object): _subclasses = {} def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) cls._subclasses[cls.duid_type] = cls def __init__(self, d): for attr, factory in self._attrs.items(): setattr(self, attr, factory(d[attr])) @classmethod def from_dict(cls, d): subcls = cls._subclasses[d['duid_type']] return subcls(d) class DuidLL(DUID): @staticmethod def _parse_l2addr(addr): return bytes.fromhex(addr.replace(':', '')) duid_type = 'DUID-LL' _attrs = { 'layer2_addr': _parse_l2addr } class DuidLLT(DuidLL): @classmethod def _parse_l2addr(cls, addr): return super()._parse_l2addr(addr) duid_type = 'DUID-LLT' _attrs = { 'layer2_addr': _parse_l2addr, 'time': datetime.datetime.fromisoformat } A bit of context on why I want to do this ... This is a simplified subset of a larger body of code that parses a somewhat complex configuration. The configuration is a YAML document, that pyyaml parses into a dictionary (which contains other dictionaries, lists, etc., etc.). My code then parses that dictionary into an object graph that represents the configuration. Rather than embedding parsing logic into each of my object classes, I have "lifted" it into the parent class (DUID in the example). A subclasses need only provide a few attributes that identifies its required and optional attributes, default values, etc. (simplified to DuidLL._attrs and DuidLLT._attrs in the example). The parent class factory function (DUID.from_dict) uses the information in the subclass's _attrs attribute to control how it parses the configuration dictionary. Importantly, a subclass's _attrs attribute maps attribute names to "factories" that are used to parse the values into various types of objects. Thus, DuidLL's 'layer2_addr' attribute is parsed with its _parse_l2addr() static method, and DuidLLT's 'time' attribute is parsed with datetime.datetime.fromisoformat(). A factory can be any callable object that takes a dictionary as its only argument. This works with static methods (as well as normal functions and object types that have an appropriate constructor): >>> duid_ll = DUID.from_dict({ 'duid_type': 'DUID-LL', 'layer2_addr': 'de:ad:be:ef:00:00' }) >>> type(duid_ll) >>> duid_ll.duid_type 'DUID-LL' >>> duid_ll.layer2_addr b'\xde\xad\xbe\xef\x00\x00' It doesn't work with a class method, such as DuidLLT._parse_l2addr(): >>> duid_llt = DUID.from_dict({ 'duid_type': 'DUID-LLT', 'layer2_addr': 'de:ad:be:ef:00:00', 'time': '2015-09-04T07:53:04-05:00' }) Traceback (most recent call last): File "", line 1, in File "/home/pilcher/subservient/wtf/wtf.py", line 19, in from_dict return subcls(d) File "/home/pilcher/subservient/wtf/wtf.py", line 14, in __init__ setattr(self, attr, factory(d[attr])) TypeError: 'classmethod' object is not callable In searching, I've found a few articles that discuss the fact that classmethod objects aren't callable, but the situation actually seems to be more complicated. >>> type(DuidLLT._parse_l2addr) >>> callable(DuidLLT._parse_l2addr) True The method itself is callable, which makes sense. The factory function doesn't access it directly, however, it gets it out of the _attrs dictionary. >>> type(DuidLLT._attrs['layer2_addr']) >>> callable(DuidLLT._attrs['layer2_addr']) False I'm not 100% sure, but I believe that this is happening because the class (DuidLLT) doesn't exist at the time that its _attrs dictionary is defined. Thus, there is no class to which the method can be bound at that time and the dictionary ends up containing the "unbound version." Fortunately, I do know the class in the context from which I actually need to call the method, so I am able to call it with its __func__ attribute. A modified version of DUID.__init__() appears to work: def __init__(self, d): for attr, factory in self._attrs.items(): if callable(factory): # <============= ???! value = factory(d[attr]) else: value = factory.__func__(type(self), d[attr]) setattr(self, attr, value) A couple of questions (finally!): * Is my analysis of why this is happening correct? * Can I improve the 'if callable(factory):' test above? This treats all non-callable objects as classmethods, which is obviously not correct. Ideally, I would check specifically for a classmethod, but there doesn't seem to be any literal against which I could check the factory's type. Note: I am aware that there are any number of workarounds for this issue. I just want to make sure that I understand what is going on, and determine if there's a better way to test for a classmethod object. Thanks! -- ======================================================================== Google Where SkyNet meets Idiocracy ======================================================================== From list1 at tompassin.net Fri Nov 11 15:58:03 2022 From: list1 at tompassin.net (Thomas Passin) Date: Fri, 11 Nov 2022 15:58:03 -0500 Subject: Need max values in list of tuples, based on position In-Reply-To: References: <6n2tmhdq21nqd4lqnb6mo7srkullne1not@4ax.com> Message-ID: <395e3c0a-b11b-bfd9-cc1f-ba0388ce258d@tompassin.net> On 11/11/2022 2:22 PM, Pancho via Python-list wrote: > On 11/11/2022 18:53, DFS wrote: >> On 11/11/2022 12:49 PM, Dennis Lee Bieber wrote: >>> On Fri, 11 Nov 2022 02:22:34 -0500, DFS declaimed the >>> following: >>> >>>> >>>> [(0,11), (1,1),? (2,1), >>>> ? (0,1) , (1,41), (2,2), >>>> ? (0,9) , (1,3),? (2,12)] >>>> >>>> The set of values in elements[0] is {0,1,2} >>>> >>>> I want the set of max values in elements[1]: {11,41,12} >>> >>> ????Do they have to be IN THAT ORDER? >> >> Yes. >> > Sets aren't ordered, which is why I gave my answer as a list. A wrongly > ordered list, but I thought it rude to point out my own error, as no one > else had. :-) > > Assuming you want numeric order of element[0], rather than first > occurrence order of the element[0] in the original tuple list. In this > example, they are both the same. > > Here is a corrected version > > from collections import OrderedDict > def build_max_dict( tups): > ??? dict =? OrderedDict() > ??? for (a,b) in tups: > ??????? if (a in dict): > ??????????? if (b>dict[a]): > ??????????????? dict[a]=b > ??????? else: > ??????????? dict[a]=b > ??? return(dict.values()) > > This solution giving the answer as type odict_values. I'm not quite sure > what this type is, but it seems to be a sequence/iterable/enumerable > type, whatever the word is in Python. > > Caveat: I know very little about Python. Kindly do not use "dict" as a variable name, since that shadows the system's built-in name for a dictionary type. From arequipeno at gmail.com Fri Nov 11 17:04:34 2022 From: arequipeno at gmail.com (Ian Pilcher) Date: Fri, 11 Nov 2022 16:04:34 -0600 Subject: Superclass static method name from subclass In-Reply-To: <25454.34431.496697.98206@ixdm.fritz.box> References: <25454.34431.496697.98206@ixdm.fritz.box> Message-ID: <59e10137-f80f-3da6-0da4-ac624339d87b@gmail.com> On 11/11/22 11:29, Dieter Maurer wrote: > Ian Pilcher wrote at 2022-11-11 10:21 -0600: >> >> class SuperClass(object): >> @staticmethod >> def foo(): >> pass >> >> class SubClass(SuperClass): >> bar = SuperClass.foo >> ^^^^^^^^^^ >> >> Is there a way to do this without specifically naming 'SuperClass'? > > Unless you overrode it, you can use `self.foo` or `SubClass.foo`; > if you overrode it (and you are using either Python 3 or > Python 2 and a so called "new style class"), you can use `super`. > When you use `super` outside a method definition, you must > call it with parameters. SubClass.foo doesn't work, because 'SubClass' doesn't actually exist until the class is defined. >>> class SubClass(SuperClass): ... bar = SubClass.foo ... Traceback (most recent call last): File "", line 1, in File "", line 2, in SubClass NameError: name 'SubClass' is not defined. Did you mean: 'SuperClass'? Similarly, self.foo doesn't work, because self isn't defined: >>> class SubClass(SuperClass): ... bar = self.foo ... Traceback (most recent call last): File "", line 1, in File "", line 2, in SubClass NameError: name 'self' is not defined -- ======================================================================== Google Where SkyNet meets Idiocracy ======================================================================== From arequipeno at gmail.com Fri Nov 11 17:07:08 2022 From: arequipeno at gmail.com (Ian Pilcher) Date: Fri, 11 Nov 2022 16:07:08 -0600 Subject: Superclass static method name from subclass In-Reply-To: <1686043e-1dbb-e284-9f76-f8be1c0e63b4@tompassin.net> References: <1686043e-1dbb-e284-9f76-f8be1c0e63b4@tompassin.net> Message-ID: On 11/11/22 11:02, Thomas Passin wrote: > You can define a classmethod in SubClass that seems to do the job: > > class SuperClass(object): > ????? @staticmethod > ????? def spam():? # "spam" and "eggs" are a Python tradition > ????????? print('spam from SuperClass') > > class SubClass(SuperClass): > ??? @classmethod > ??? def eggs(self): > ??????? super().spam() > > SubClass.eggs()? # Prints "spam from SuperClass" That did it! Thanks! -- ======================================================================== Google Where SkyNet meets Idiocracy ======================================================================== From PythonList at DancesWithMice.info Fri Nov 11 17:07:31 2022 From: PythonList at DancesWithMice.info (dn) Date: Sat, 12 Nov 2022 11:07:31 +1300 Subject: Argument name should be lowercase In-Reply-To: <0eba3f9d-c89c-062e-425a-54aea7216b11@DancesWithMice.info> References: <0eba3f9d-c89c-062e-425a-54aea7216b11@DancesWithMice.info> Message-ID: Thanks for the thoughts! On 11/11/2022 21.54, dn wrote: > PyCharm is warning against using an identifier of all upper-case letters > as a function's parameter, saying "Argument name should be lowercase". > (weak, code smell) > ... PEP-008: makes no mention, and is but a guide anyway. (that said, if one 'breaks a rule', then a good reason should be required!) YELLING is an email-interpretation. Does it apply to code? Particularly as we are talking Python, where an identifier using all upper-case letters is a convention (not a language-structure, as stated in contributions 'here') that is widely used. Accordingly, the purpose of the UPPER_CASE is to communicate the read-only nature of the data-item to the programmer. Combine this with "we're all adults here", and if someone is foolish-enough to modify a 'constant', then Python will comply - but (s)he can expect push-back during a Code Review! So, yes, ?weird to see an all-cap parameter? (I thought so too) but isn't that effect the purpose of the convention in the first place? There are several aspects of Python where the 'we're all adults' thinking must be applied, eg 'private attributes'. Given that understanding, it doesn't seem necessary to force constant-behavior on the parameter - although when one does, there are a couple of mechanisms and more than several projects working on this and other aspects of enforcing data-types and their characteristics! That said, and with @Stefan's observations, there are many reasons why this code is piling-up trouble - and thus, should be avoided... > def build_product_prices_dictionary( WORKBOOK_DEFINITIONS:dict )->dict: > ... > ??? price_array = xl.iget_array( > ??????? file_name=WORKBOOK_DEFINITIONS[ "file_name" ], > ??????? ... > > (the function def is flagged, as above) > As far as the function is concerned, the dict and its contents are > constants. > (but the dict can't be treated as a global ENV[IRONMENT] object, because > it has to cross into the module's namespace) By way of background, in recent times, have the habit/standardised code 'template' for config/environment-setting, which instantiates a class from (at least) JSON/YAML files. Accordingly, the instance is named in lower-case, and particular groups of parameters (as here) can be passed as an extract-function/property (as a general style, I avoid long parameter/argument lists, preferring a data-collection - which landed me in this...). Which re-raises the question the other way around: how does the object's name indicate its constant/read-only nature to the reader? "Ouch" says idealism! Back to this case, which part of a tutorial comparing different methods to access prices in a product-catalog[ue] (eg hard-coded dict, flat-file, workbook, database, etc). Some members of the group are either anti-OOP or OOP-untrained. Hence avoiding my personal 'good, old, stand-by'. (plus it was Veterans'/Remembrance/Liberation Day, which we don't observe (much) here (ANZAC Day instead) and I was using some creative-coding time to [try to] take my mind off it) The particular @Rob and I both find it peculiar (in the same sense) but as-above, that's (ultimately) the point of the upper-casing. The idea of moving the workbook-definitions into that module appears to make sense and could easily be achieved - but in the singular context of this example. However, as a matter of style, all of an application's environment-setting would best be done in one place - with cmdLN, config-file(s), etc, all being combined, and with the output of a single 'authority' as its objective. I could try to 'get away with it', but if some Apprentice takes the idea and later uses it as a 'template', a general grumpiness will result... (no it's not a learning-objective, but sometimes people take-away unintended 'side effects', maybe like this). However, in that spirit, am contemplating use of a DataClass. It will be as easy to read as any config file, even to non-OOP-ers; has no learning side-effect down-side (that I've spotted, as-yet); and can be 'seen' as a instance by the workbook module (instance named using lower-case). This, hopefully also measuring-up to @Thomas' observations of risk that the current code's intentions be misconstrued later. I'll admit to (idealists look away now!) not being 'above' the use of globals, particularly?if only an ENVIRONMENT class - IIRC this irresponsible behavior being when the environment is fairly trivial (cf multi-layered or large numbers of 'tunable factors'). Because the ENVIRONMENT is returned to the mainline, which subsequently uses those parameters to call the 'action' functions/methods (and know which to call), it is not available within the import-ed module's namespace. Hence the fall-back to passing it/the Workbook sub-set of parameters, as an argument. (see above for normal/traditional 'solution' to traversing namespaces) > Is passing the dict as an argument/parameter considered to be > incompatible with its designation as a constant? There's an argument to be made, particularly by those from other languages, relating to pass-by-reference, pass-by-value; which suggests that the WORKBOOK_DEFINITIONS parameter is effectively being used on the LHS of an assignment... Probably 'nuff said'! > Perhaps the style should be more enum-like, ie the dict's name in > lower-case, with the key-named in upper case, eg > > ??? workbook_definitions[ "FILE_NAME" ] Like @MRAB, I'm thinking that getting tangled-up in the conventions of constant identification, cf wanting to convey the read-only nature of the construct is unhelpful (and an unneeded headache from over-thinking). Changing the dict-keys to upper-case encourages the 'constant/read-only' interpretation, and might cause least distraction to the learning/discussion/comparison objectives... > Advice, comments, critique welcome! -- Regards, =dn From cs at cskk.id.au Fri Nov 11 17:17:26 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Sat, 12 Nov 2022 09:17:26 +1100 Subject: Superclass static method name from subclass In-Reply-To: References: Message-ID: On 11Nov2022 10:21, Ian Pilcher wrote: >Is it possible to access the name of a superclass static method, when >defining a subclass attribute, without specifically naming the super- >class? > >Contrived example: > > class SuperClass(object): > @staticmethod > def foo(): > pass > > class SubClass(SuperClass): > bar = SuperClass.foo > ^^^^^^^^^^ > >Is there a way to do this without specifically naming 'SuperClass'? I think not. All the posts so far run from inside methods, which execute after you've got an instance of `SubClass`. However, during the class definition the code under `class SubClass` is running in a standalone namespace - not even inside a completed class. When that code finished, that namespace is used to create the class definition. So you have no access to the `SuperClass` part of `class SubClass(SuperClass):` in the class definition execution. Generally it is better to name where something like this comes from anyway, most of the time. However, if you really want to plain "inherit" the class attribute (which I can imagine valid use cases for), maybe write a property? @property def bar(self): return super().foo That would still require an instance to make use of it, so you can't write explicitly `SubClass.bar`. Possibly a metaclass would let you write a "class property", or to define `bar` as a class attribute directly. Cheers, Cameron Simpson From eryksun at gmail.com Fri Nov 11 17:21:35 2022 From: eryksun at gmail.com (Eryk Sun) Date: Fri, 11 Nov 2022 16:21:35 -0600 Subject: Problems with IDLE in Windows 8.1 and installer x86 Version 3.10.8 In-Reply-To: <202211112017.2ABKH2nC027172@mail265c50.megamailservers.eu> References: <202210311822.29VIMTpw130438@mail92c50.megamailservers.eu> <202210312138.29VLcBUQ008124@mail118c50.megamailservers.eu> <202211011649.2A1GnNrU115152@mail36c50.megamailservers.eu> <202211032129.2A3LTmtc065950@mail193c50.megamailservers.eu> <202211041414.2A4EE2xL017716@mail264c50.megamailservers.eu> <202211100003.2AA03LR5098382@mail266c50.megamailservers.eu> <202211112017.2ABKH2nC027172@mail265c50.megamailservers.eu> Message-ID: On 11/11/22, darkstone at o2online.de wrote: > > What can I do for the next step to find, why IDLE isn?t working? The question is why tkinter isn't working. IDLE not working is just a symptom of the underlying problem. In the command prompt, run 32-bit Python 3.10 via `py -3.10-32`. In Python's interactive shell, run `import _tkinter`. Please paste any resulting traceback and error message in your reply to this message. From cs at cskk.id.au Fri Nov 11 17:36:16 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Sat, 12 Nov 2022 09:36:16 +1100 Subject: Superclass static method name from subclass In-Reply-To: References: Message-ID: On 12Nov2022 09:17, Cameron Simpson wrote: >On 11Nov2022 10:21, Ian Pilcher wrote: >> class SubClass(SuperClass): >> bar = SuperClass.foo >> ^^^^^^^^^^ >> >>Is there a way to do this without specifically naming 'SuperClass'? > >I think not. Then I saw your "Dealing with non-callable classmethod objects" post which mentions `__init_subclass__`. Which feels like I've read about that before, but had entirely slipped my mind. Maybe: class SubClass(SuperClass): @classmethod def __init__subclass__(cls): cls.bar = super().foo would do the trick. Looks clean, but I haven't tried it yet. Cheers, Cameron Simpson From cs at cskk.id.au Fri Nov 11 17:47:57 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Sat, 12 Nov 2022 09:47:57 +1100 Subject: Dealing with non-callable classmethod objects In-Reply-To: References: Message-ID: On 11Nov2022 15:29, Ian Pilcher wrote: >I am trying to figure out a way to gracefully deal with uncallable >classmethod objects. I'm just going to trim your example below a bit for reference purposes: >class DUID(object): > def __init__(self, d): > for attr, factory in self._attrs.items(): > setattr(self, attr, factory(d[attr])) > @classmethod > def from_dict(cls, d): > subcls = cls._subclasses[d['duid_type']] > return subcls(d) > >class DuidLL(DUID): > @staticmethod > def _parse_l2addr(addr): > return bytes.fromhex(addr.replace(':', '')) > _attrs = { 'layer2_addr': _parse_l2addr } > >class DuidLLT(DuidLL): > @classmethod > def _parse_l2addr(cls, addr): > return super()._parse_l2addr(addr) > _attrs = { > 'layer2_addr': _parse_l2addr, > } So what you've got is that `for attr, factory in self._attrs.items():` loop, where the factory comes from the subclass `_attrs` mapping. For `DuidLL` you get the static method `_parse_l2addr` object and for `DuidLLT` you get the class method object. [...] >This works with static methods (as well as normal functions and object >types that have an appropriate constructor): [...] [...] > >It doesn't work with a class method, such as DuidLLT._parse_l2addr(): > >>>>duid_llt = DUID.from_dict({ 'duid_type': 'DUID-LLT', 'layer2_addr': 'de:ad:be:ef:00:00', 'time': '2015-09-04T07:53:04-05:00' }) >Traceback (most recent call last): > File "", line 1, in > File "/home/pilcher/subservient/wtf/wtf.py", line 19, in from_dict > return subcls(d) > File "/home/pilcher/subservient/wtf/wtf.py", line 14, in __init__ > setattr(self, attr, factory(d[attr])) >TypeError: 'classmethod' object is not callable > >In searching, I've found a few articles that discuss the fact that >classmethod objects aren't callable, but the situation actually seems to >be more complicated. > >>>> type(DuidLLT._parse_l2addr) > >>>> callable(DuidLLT._parse_l2addr) >True > >The method itself is callable, which makes sense. The factory function >doesn't access it directly, however, it gets it out of the _attrs >dictionary. > >>>> type(DuidLLT._attrs['layer2_addr']) > >>>> callable(DuidLLT._attrs['layer2_addr']) >False > >I'm not 100% sure, but I believe that this is happening because the >class (DuidLLT) doesn't exist at the time that its _attrs dictionary is >defined. Thus, there is no class to which the method can be bound at >that time and the dictionary ends up containing the "unbound version." Yes. When you define the dictionary `_parse_l2addr` is an unbound class method object. That doesn't change. >Fortunately, I do know the class in the context from which I actually >need to call the method, so I am able to call it with its __func__ >attribute. A modified version of DUID.__init__() appears to work: > > def __init__(self, d): > for attr, factory in self._attrs.items(): > if callable(factory): # <============= ???! > value = factory(d[attr]) > else: > value = factory.__func__(type(self), d[attr]) > setattr(self, attr, value) Neat! >A couple of questions (finally!): >* Is my analysis of why this is happening correct? It seems so to me. Although I only learned some of these nuances recently. >* Can I improve the 'if callable(factory):' test above? This treats > all non-callable objects as classmethods, which is obviously not > correct. Ideally, I would check specifically for a classmethod, but > there doesn't seem to be any literal against which I could check the > factory's type. Yeah, it does feel a bit touchy feely. You could see if the `inspect` module tells you more precise things about the `factory`. The other suggestion I have is to put the method name in `_attrs`; if that's a `str` you could special case it as a well known type for the factory and look it up with `getattr(cls,factory)`. Cheers, Cameron Simpson From list1 at tompassin.net Fri Nov 11 16:43:10 2022 From: list1 at tompassin.net (Thomas Passin) Date: Fri, 11 Nov 2022 16:43:10 -0500 Subject: Need max values in list of tuples, based on position In-Reply-To: References: Message-ID: On 11/11/2022 2:22 AM, DFS wrote: > > [(0,11), (1,1),? (2,1), > ?(0,1) , (1,41), (2,2), > ?(0,9) , (1,3),? (2,12)] > > The set of values in elements[0] is {0,1,2} > > I want the set of max values in elements[1]: {11,41,12} This request is ambiguous. Do you want to get the maximum value for each row, and present it in the order of those rows? Your data list does not distinguish the rows from the tuples, so that information must come from somewhere else. Could it sometimes be different from 3? How are we supposed to know? Also, as has already been noted in this thread, the result cannot literally be a set because sets are not ordered but you insisted that the order is important. This code allows for different length of rows, and tries to be as clear as possible: data = [(0,11), (1,1), (2,1), (0,1), (1,41), (2,2), (0,9), (1,3), (2,12)] span = 3 # Change for other row lengths d1 = [y for x, y in data] # pick out the 2nd member of each tuple # d1: [11, 1, 1, 1, 41, 2, 9, 3, 12] groups = [] for i in range(0, len(d1), span): group = [] for s in range(span): group.append(d1[i + s]) groups.append(group) # groups: [[11, 1, 1], [1, 41, 2], [9, 3, 12]] maxes = [max(t) for t in groups] # maxes: [11, 41, 12] This could be condensed, but I recommend keeping it as clear as possible. Tricky, condensed code becomes harder to understand as time goes by. From ohinseok at gmail.com Fri Nov 11 16:44:22 2022 From: ohinseok at gmail.com (ohinseok at gmail.com) Date: Fri, 11 Nov 2022 16:44:22 -0500 Subject: Create a Python Launcher on Desktop Message-ID: <002401d8f616$c342fbd0$49c8f370$@gmail.com> Hello, I am real a beginner of Python. Not able to create a Python launcher (shortcut) on Desktop after the installation. Would you kindly instruct how to do it? Windows 11-Home, 64 bits, HP desktop Thanks, Dan From nospam at dfs.com Fri Nov 11 15:03:49 2022 From: nospam at dfs.com (DFS) Date: Fri, 11 Nov 2022 15:03:49 -0500 Subject: Need max values in list of tuples, based on position In-Reply-To: References: <6n2tmhdq21nqd4lqnb6mo7srkullne1not@4ax.com> Message-ID: On 11/11/2022 2:22 PM, Pancho wrote: > On 11/11/2022 18:53, DFS wrote: >> On 11/11/2022 12:49 PM, Dennis Lee Bieber wrote: >>> On Fri, 11 Nov 2022 02:22:34 -0500, DFS declaimed the >>> following: >>> >>>> >>>> [(0,11), (1,1),? (2,1), >>>> ? (0,1) , (1,41), (2,2), >>>> ? (0,9) , (1,3),? (2,12)] >>>> >>>> The set of values in elements[0] is {0,1,2} >>>> >>>> I want the set of max values in elements[1]: {11,41,12} >>> >>> ????Do they have to be IN THAT ORDER? >> >> Yes. >> > Sets aren't ordered, which is why I gave my answer as a list. A wrongly > ordered list, but I thought it rude to point out my own error, as no one > else had. :-) > > Assuming you want numeric order of element[0], rather than first > occurrence order of the element[0] in the original tuple list. In this > example, they are both the same. > > Here is a corrected version > > from collections import OrderedDict > def build_max_dict( tups): > ??? dict =? OrderedDict() > ??? for (a,b) in tups: > ??????? if (a in dict): > ??????????? if (b>dict[a]): > ??????????????? dict[a]=b > ??????? else: > ??????????? dict[a]=b > ??? return(dict.values()) > > This solution giving the answer as type odict_values. I'm not quite sure > what this type is, but it seems to be a sequence/iterable/enumerable > type, whatever the word is in Python. > > Caveat: I know very little about Python. Thanks for looking at it. I'm trying to determine the maximum length of each column result in a SQL query. Normally you can use the 3rd value of the cursor.description object (see the DB-API spec), but apparently not with my dbms (SQLite). The 'display_size' column is None with SQLite. So I had to resort to another way. From Pancho.Jones at proton.me Fri Nov 11 16:58:17 2022 From: Pancho.Jones at proton.me (Pancho) Date: Fri, 11 Nov 2022 21:58:17 +0000 Subject: Need max values in list of tuples, based on position In-Reply-To: References: <6n2tmhdq21nqd4lqnb6mo7srkullne1not@4ax.com> <395e3c0a-b11b-bfd9-cc1f-ba0388ce258d@tompassin.net> Message-ID: On 11/11/2022 20:58, Thomas Passin wrote: > On 11/11/2022 2:22 PM, Pancho via Python-list wrote: >> On 11/11/2022 18:53, DFS wrote: >>> On 11/11/2022 12:49 PM, Dennis Lee Bieber wrote: >>>> On Fri, 11 Nov 2022 02:22:34 -0500, DFS declaimed the >>>> following: >>>> >>>>> >>>>> [(0,11), (1,1),? (2,1), >>>>> ? (0,1) , (1,41), (2,2), >>>>> ? (0,9) , (1,3),? (2,12)] >>>>> >>>>> The set of values in elements[0] is {0,1,2} >>>>> >>>>> I want the set of max values in elements[1]: {11,41,12} >>>> >>>> ????Do they have to be IN THAT ORDER? >>> >>> Yes. >>> >> Sets aren't ordered, which is why I gave my answer as a list. A >> wrongly ordered list, but I thought it rude to point out my own error, >> as no one else had. :-) >> >> Assuming you want numeric order of element[0], rather than first >> occurrence order of the element[0] in the original tuple list. In this >> example, they are both the same. >> >> Here is a corrected version >> >> from collections import OrderedDict >> def build_max_dict( tups): >> ???? dict =? OrderedDict() >> ???? for (a,b) in tups: >> ???????? if (a in dict): >> ???????????? if (b>dict[a]): >> ???????????????? dict[a]=b >> ???????? else: >> ???????????? dict[a]=b >> ???? return(dict.values()) >> >> This solution giving the answer as type odict_values. I'm not quite >> sure what this type is, but it seems to be a >> sequence/iterable/enumerable type, whatever the word is in Python. >> >> Caveat: I know very little about Python. > > Kindly do not use "dict" as a variable name, since that shadows the > system's built-in name for a dictionary type. > Yes, I half suspected it might cause subtle problems, I changed it to d, and then I changed it back, senility I guess :-). That was one of the things I didn't like about Python. Lack of types and subsequent loss of intellisense is the thing I find hardest to deal with. From eryksun at gmail.com Fri Nov 11 19:10:47 2022 From: eryksun at gmail.com (Eryk Sun) Date: Fri, 11 Nov 2022 18:10:47 -0600 Subject: Strange UnicodeEncodeError in Windows image on Azure DevOps and Github In-Reply-To: References: Message-ID: On 11/10/22, Jessica Smith <12jessicasmith34 at gmail.com> wrote: > > Weird issue I've found on Windows images in Azure Devops Pipelines and > Github actions. Printing Unicode characters fails on these images because, > for some reason, the encoding is mapped to cp1252. What is particularly > weird about the code page being set to 1252 is that if you execute "chcp" > it shows that the code page is 65001. If stdout isn't a console (e.g. a pipe), it defaults to using the process code page (i.e. CP_ACP), such as legacy code page 1252 (extended Latin-1). You can override just sys.std* to UTF-8 by setting the environment variable `PYTHONIOENCODING=UTF-8`. You can override all I/O to use UTF-8 by setting `PYTHONUTF8=1`, or by passing the command-line option `-X utf8`. Background The locale system in Windows supports a common system locale, plus a separate locale for each user. By default the process code page is based on the system locale, and the thread code page (i.e. CP_THREAD_ACP) is based on the user locale. The default locale of the Universal C runtime combines the user locale with the process code page. (This combination may be inconsistent.) In Windows 10 and later, the default process and thread code pages can be configured to use CP_UTF8 (65001). Applications can also override them to UTF-8 in their manifest via the "ActiveCodePage" setting. In either case, if the process code page is UTF-8, the C runtime will use UTF-8 for its default locale encoding (e.g. "en_uk.utf8"). Unlike some frameworks, Python has never used the console input code page or output code page as a locale encoding. Personally, I wouldn't want Python to default to that old MS-DOS behavior. However, I'd be in favor of supporting a "console" encoding that's based on the console input code page that's returned by GetConsoleCP(). If the process doesn't have a console session, the "console" encoding would fall back on the process code page from GetACP(). From wlfraed at ix.netcom.com Fri Nov 11 19:04:25 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 11 Nov 2022 19:04:25 -0500 Subject: Need max values in list of tuples, based on position References: <6n2tmhdq21nqd4lqnb6mo7srkullne1not@4ax.com> Message-ID: On Fri, 11 Nov 2022 15:03:49 -0500, DFS declaimed the following: >Thanks for looking at it. I'm trying to determine the maximum length of >each column result in a SQL query. Normally you can use the 3rd value >of the cursor.description object (see the DB-API spec), but apparently >not with my dbms (SQLite). The 'display_size' column is None with >SQLite. So I had to resort to another way. Not really a surprise. SQLite doesn't really have column widths -- since any column can store data of any type; affinities just drive it into what may be the optimal storage for the column... That is, if a column is "INT", SQLite will attempt to convert whatever the data is into an integer -- but if the data is not representable as an integer, it will be stored as the next best form. 123 => stored as integer "123" => converted and stored as integer 123.0 => probably converted to integer 123.5 => likely stored as numeric/double "one two three" => can't convert, store it as a string We've not seen the SQL query in question, but it might suffice to use a second (first?) SQL query with aggregate (untested) max(length(colname)) for each column in the main SQL query. """ length(X) For a string value X, the length(X) function returns the number of characters (not bytes) in X prior to the first NUL character. Since SQLite strings do not normally contain NUL characters, the length(X) function will usually return the total number of characters in the string X. For a blob value X, length(X) returns the number of bytes in the blob. If X is NULL then length(X) is NULL. If X is numeric then length(X) returns the length of a string representation of X. """ Note the last sentence for numerics. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From list1 at tompassin.net Fri Nov 11 19:33:41 2022 From: list1 at tompassin.net (Thomas Passin) Date: Fri, 11 Nov 2022 19:33:41 -0500 Subject: Create a Python Launcher on Desktop In-Reply-To: <002401d8f616$c342fbd0$49c8f370$@gmail.com> References: <002401d8f616$c342fbd0$49c8f370$@gmail.com> Message-ID: On 11/11/2022 4:44 PM, ohinseok at gmail.com wrote: > Hello, > > > > I am real a beginner of Python. Not able to create a Python launcher > (shortcut) on Desktop after the installation. > > Would you kindly instruct how to do it? > > > > Windows 11-Home, 64 bits, HP desktop > If you get an offer of Python when you open the start menu and type "Python" (no quotes, please) then it's easy. I'm working with Windows 10, but it's probably much the same in Windows 11. When the Start menu offers "Python", choose the version of Python you want (if there are more than one), right click on it, and choose "Open File Location". This will open a Windows Explorer window with some Python-related shortcuts. Make sure the Explorer window does not cover the whole screen - you need to have some of the desktop visible around it. Choose the shortcut for Python, and drag it to the desktop **while holding down both the and keys**. Presto, a Python launcher on your desktop. If you don't see your version of Python when you tap the Windows key and type "Python", then you will need to find where the Python directory is, find the file called "python.exe", and then do the dragging operation on it. If you do not know how to find where Python is located, then please see my message on this list titled "Re: Problems with IDLE in Windows 8.1 and installer x86 Version 3.10.8", dated 11/9/2022. From list1 at tompassin.net Fri Nov 11 19:07:03 2022 From: list1 at tompassin.net (Thomas Passin) Date: Fri, 11 Nov 2022 19:07:03 -0500 Subject: Superclass static method name from subclass In-Reply-To: References: <1686043e-1dbb-e284-9f76-f8be1c0e63b4@tompassin.net> Message-ID: <2c97a527-2c46-e65f-0e19-bf53c8d994b2@tompassin.net> On 11/11/2022 5:07 PM, Ian Pilcher wrote: > On 11/11/22 11:02, Thomas Passin wrote: >> You can define a classmethod in SubClass that seems to do the job: >> >> class SuperClass(object): >> ?????? @staticmethod >> ?????? def spam():? # "spam" and "eggs" are a Python tradition >> ?????????? print('spam from SuperClass') >> >> class SubClass(SuperClass): >> ???? @classmethod >> ???? def eggs(self): >> ???????? super().spam() >> >> SubClass.eggs()? # Prints "spam from SuperClass" > > > That did it!? Thanks! Glad I could help. I probably should have written def eggs(clas): # instead of "self" but it's not actually used anyway. From eryksun at gmail.com Fri Nov 11 20:17:01 2022 From: eryksun at gmail.com (Eryk Sun) Date: Fri, 11 Nov 2022 19:17:01 -0600 Subject: Create a Python Launcher on Desktop In-Reply-To: <002401d8f616$c342fbd0$49c8f370$@gmail.com> References: <002401d8f616$c342fbd0$49c8f370$@gmail.com> Message-ID: On 11/11/22, ohinseok at gmail.com wrote: > > I am real a beginner of Python. Not able to create a Python launcher > (shortcut) on Desktop after the installation. Did you already install Python? If not, open the Store, and install the Python 3.11 app that's published by the Python Software Foundation. After Python is installed, you'll have shortcuts in the start menu that run Python in a terminal or that run the IDLE development environment. On the context menu of a shortcut, there's an action to pin it to the top-level start menu, which is more convenient than having to click on "all apps" to find it. Also, the context menu of a pinned shortcut has an action to pin it to the taskbar, for even more convenient access. The running application icon on the taskbar also lets you pin the app. If you really want a shortcut on your desktop, it depends on which distribution you installed. If you installed the app version of 3.11, then you have "python3.11.exe" to run Python in a terminal and "idle3.11.exe" to IDLE. To create a shortcut, right click the desktop; select the action to create a new shortcut; and enter one of the latter executable names. After creating the shortcut, on its context menu select the "properties" action, and then modify the "start in" folder to your preferred working directory. If you installed the standard distribution from python.org, then you already have normal file shortcuts (as opposed to app shortcuts) in the start menu, which you can copy to the desktop. The context menu of the start-menu shortcut has an action to open the file location. This opens an Explorer window. Right click the shortcut in that window and drag it to the desktop. Release the mouse button and select the action "copy here". From 12jessicasmith34 at gmail.com Fri Nov 11 20:20:17 2022 From: 12jessicasmith34 at gmail.com (12Jessicasmith34) Date: Fri, 11 Nov 2022 19:20:17 -0600 Subject: Strange UnicodeEncodeError in Windows image on Azure DevOps and Github In-Reply-To: References: Message-ID: <959da7c4-cd04-46ba-8510-33cd1df4fb28@iPhone> > If stdout isn't a console (e.g. a pipe), it defaults to using the process code page (i.e. CP_ACP), such as legacy code page 1252 (extended Latin-1). First off, really helpful information, thank you. That was the exact background I was missing. Two questions: any idea why this would be happening in this situation? AFAIK, stdout *is* a console when these images are running the python process. Second - is there a way I can check the locale and code page values that you mentioned? I assume I could call GetACP using ctypes, but maybe there is a simpler way? From eryksun at gmail.com Fri Nov 11 21:16:01 2022 From: eryksun at gmail.com (Eryk Sun) Date: Fri, 11 Nov 2022 20:16:01 -0600 Subject: Strange UnicodeEncodeError in Windows image on Azure DevOps and Github In-Reply-To: <959da7c4-cd04-46ba-8510-33cd1df4fb28@iPhone> References: <959da7c4-cd04-46ba-8510-33cd1df4fb28@iPhone> Message-ID: On 11/11/22, 12Jessicasmith34 <12jessicasmith34 at gmail.com> wrote: > > any idea why this would be happening in this situation? AFAIK, stdout > *is* a console when these images are running the python process. If sys.std* are console files, then in Python 3.6+, sys.std*.buffer.raw will be _io._WindowsConsoleIO. The latter presents itself to Python code as a UTF-8 file stream, but internally it uses UTF-16LE with the wide-character API functions ReadConsoleW() and WriteConsoleW(). > is there a way I can check the locale and code page values that you > mentioned? I assume I could call GetACP using ctypes, but maybe > there is a simpler way? io.TextIOWrapper uses locale.getpreferredencoding(False) as the default encoding. Actually, in 3.11+ it uses locale.getencoding() unless UTF-8 mode is enabled, which is effectively the same as locale.getpreferredencoding(False). On Windows this calls GetACP() and formats the result as "cp%u" (e.g. "cp1252"). From nospam at dfs.com Fri Nov 11 21:20:10 2022 From: nospam at dfs.com (DFS) Date: Fri, 11 Nov 2022 21:20:10 -0500 Subject: Need max values in list of tuples, based on position In-Reply-To: References: <6n2tmhdq21nqd4lqnb6mo7srkullne1not@4ax.com> Message-ID: On 11/11/2022 7:04 PM, Dennis Lee Bieber wrote: > On Fri, 11 Nov 2022 15:03:49 -0500, DFS declaimed the > following: > > >> Thanks for looking at it. I'm trying to determine the maximum length of >> each column result in a SQL query. Normally you can use the 3rd value >> of the cursor.description object (see the DB-API spec), but apparently >> not with my dbms (SQLite). The 'display_size' column is None with >> SQLite. So I had to resort to another way. > > Not really a surprise. SQLite doesn't really have column widths -- As I understand it, the cursor.description doesn't look at the column type - it goes by the data in the cursor. > since any column can store data of any type; affinities just drive it into > what may be the optimal storage for the column... That is, if a column is > "INT", SQLite will attempt to convert whatever the data is into an integer > -- but if the data is not representable as an integer, it will be stored as > the next best form. Yeah, I don't know why cursor.description doesn't work with SQLite; all their columns are basically varchars. > 123 => stored as integer > "123" => converted and stored as integer > 123.0 => probably converted to integer > 123.5 => likely stored as numeric/double > "one two three" => can't convert, store it as a string > > We've not seen the SQL query in question, The query is literally any SELECT, any type of data, including SELECT *. The reason it works with SELECT * is the cursor.description against SQLite DOES give the column names: select * from timezone; print(cur.description) ( ('TIMEZONE', None, None, None, None, None, None), ('TIMEZONEDESC', None, None, None, None, None, None), ('UTC_OFFSET', None, None, None, None, None, None) ) (I lined up the data) Anyway, I got it working nicely, with the help of the solution I found online and posted here earlier: ----------------------------------------------------------------- x = [(11,1,1),(1,41,2),(9,3,12)] maxvals = [0]*len(x[0]) for e in x: #clp example using only ints maxvals = [max(w,int(c)) for w,c in zip(maxvals,e)] #clp example #real world - get the length of the data string, even if all numeric maxvals = [max(w,len(str(c))) for w,c in zip(maxvals,e)] print(maxvals) [11,41,12] ----------------------------------------------------------------- Applied to real data, the iterations might look like this: [4, 40, 9] [4, 40, 9] [4, 40, 9] [4, 40, 18] [4, 40, 18] [4, 40, 18] [5, 40, 18] [5, 40, 18] [5, 40, 18] [5, 69, 18] [5, 69, 18] [5, 69, 18] The last row contains the max width of the data in each column. Then I compare those datawidths to the column name widths, and take the wider of the two, so [5,69,18] might change to [8,69,18] if the column label is wider than the widest bit of data in the column convert those final widths into a print format string, and everything fits well: Each column is perfectly sized and it all looks pleasing to the eye (and no external libs like tabulate used either). https://imgur.com/UzO3Yhp The 'downside' is you have to fully iterate the data twice: once to get the widths, then again to print it. If I get a wild hair I might create a PostgreSQL clone of my db and see if the cursor.description works with it. It would also have to iterate the data to determine that 'display_size' value. https://peps.python.org/pep-0249/#cursor-attributes > but it might suffice to use a > second (first?) SQL query with aggregate (untested) > > max(length(colname)) > > for each column in the main SQL query. Might be a pain to code dynamically. > """ > length(X) > > For a string value X, the length(X) function returns the number of > characters (not bytes) in X prior to the first NUL character. Since SQLite > strings do not normally contain NUL characters, the length(X) function will > usually return the total number of characters in the string X. For a blob > value X, length(X) returns the number of bytes in the blob. If X is NULL > then length(X) is NULL. If X is numeric then length(X) returns the length > of a string representation of X. > """ > > Note the last sentence for numerics. Thanks for looking at it. From songofacandy at gmail.com Fri Nov 11 21:53:42 2022 From: songofacandy at gmail.com (Inada Naoki) Date: Sat, 12 Nov 2022 11:53:42 +0900 Subject: Strange UnicodeEncodeError in Windows image on Azure DevOps and Github In-Reply-To: <959da7c4-cd04-46ba-8510-33cd1df4fb28@iPhone> References: <959da7c4-cd04-46ba-8510-33cd1df4fb28@iPhone> Message-ID: On Sat, Nov 12, 2022 at 10:21 AM 12Jessicasmith34 <12jessicasmith34 at gmail.com> wrote: > > > Two questions: any idea why this would be happening in this situation? AFAIK, stdout *is* a console when these images are running the python process. Second - is there a way I can check the locale and code page values that you mentioned? I assume I could call GetACP using ctypes, but maybe there is a simpler way? > Maybe, python doesn't write to console in this case. python -(pipe)-> PowerShell -> Console In this case, python uses ACP for writing to pipe. And PowerShell uses OutputEncoding for reading from pipe. If you want to use UTF-8 on PowerShell in Windows, * Set PYTHONUTF8=1 (Python uses UTF-8 for writing into pipe). * Set `$OutputEncoding = [System.Text.Encoding]::GetEncoding('utf-8')` in PowerShell profile. Regards, -- Inada Naoki From songofacandy at gmail.com Fri Nov 11 22:23:39 2022 From: songofacandy at gmail.com (Inada Naoki) Date: Sat, 12 Nov 2022 12:23:39 +0900 Subject: Strange UnicodeEncodeError in Windows image on Azure DevOps and Github In-Reply-To: References: <959da7c4-cd04-46ba-8510-33cd1df4fb28@iPhone> Message-ID: On Sat, Nov 12, 2022 at 11:53 AM Inada Naoki wrote: > > On Sat, Nov 12, 2022 at 10:21 AM 12Jessicasmith34 > <12jessicasmith34 at gmail.com> wrote: > > > > > > Two questions: any idea why this would be happening in this situation? AFAIK, stdout *is* a console when these images are running the python process. Second - is there a way I can check the locale and code page values that you mentioned? I assume I could call GetACP using ctypes, but maybe there is a simpler way? > > > > Maybe, python doesn't write to console in this case. > > python -(pipe)-> PowerShell -> Console > > In this case, python uses ACP for writing to pipe. > And PowerShell uses OutputEncoding for reading from pipe. > > If you want to use UTF-8 on PowerShell in Windows, > > * Set PYTHONUTF8=1 (Python uses UTF-8 for writing into pipe). > * Set `$OutputEncoding = > [System.Text.Encoding]::GetEncoding('utf-8')` in PowerShell profile. > I forgot [Console]::OutputEncoding. This is what PowerShell uses when reading from pipe. So PowerShell profile should be: $OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 -- Inada Naoki From dieter at handshake.de Sat Nov 12 01:07:53 2022 From: dieter at handshake.de (Dieter Maurer) Date: Sat, 12 Nov 2022 07:07:53 +0100 Subject: Dealing with non-callable classmethod objects In-Reply-To: References: Message-ID: <25455.14393.432411.722314@ixdm.fritz.box> Ian Pilcher wrote at 2022-11-11 15:29 -0600: > ... >In searching, I've found a few articles that discuss the fact that >classmethod objects aren't callable, but the situation actually seems to >be more complicated. > > >>> type(DuidLLT._parse_l2addr) > > >>> callable(DuidLLT._parse_l2addr) >True > >The method itself is callable, which makes sense. The factory function >doesn't access it directly, however, it gets it out of the _attrs >dictionary. > > >>> type(DuidLLT._attrs['layer2_addr']) > > >>> callable(DuidLLT._attrs['layer2_addr']) >False Accessing an object via a `dict` does not change its type, nor does putting it into a `dict`. Thus, you did not put `DuidLLT._parse_l2addr` (of type `method`) into your `_attrs` `dict` but something else (of type `classmethod`). This narrows down the space for your investigation: why was the object you have put into `_attr` was not what you have expected. From list1 at tompassin.net Sat Nov 12 08:42:27 2022 From: list1 at tompassin.net (Thomas Passin) Date: Sat, 12 Nov 2022 08:42:27 -0500 Subject: Problems with IDLE in Windows 8.1 and installer x86 Version 3.10.8 In-Reply-To: <202211121242.2ACCgcuL102426@mail265c50.megamailservers.eu> References: <202210311822.29VIMTpw130438@mail92c50.megamailservers.eu> <202210312138.29VLcBUQ008124@mail118c50.megamailservers.eu> <202211011649.2A1GnNrU115152@mail36c50.megamailservers.eu> <202211032129.2A3LTmtc065950@mail193c50.megamailservers.eu> <202211041414.2A4EE2xL017716@mail264c50.megamailservers.eu> <202211100003.2AA03LR5098382@mail266c50.megamailservers.eu> <59f3470c-fffb-4354-1712-67814f257e66@tompassin.net> <202211121242.2ACCgcuL102426@mail265c50.megamailservers.eu> Message-ID: All right, now let's verify that tk is not there (otherwise it might be there but corrupted or not loadable for some reason). Open Windows Explorer and navigate it to the Python directory as I described in my last message. The navigate to the subdirectory named "DLLs". If tkinter is installed, there will be a file named "_tkinter.pyd". If that file is missing, then definitely tk isn't there. If it is, then it's been installed but something is wrong with the install. Probably it won't be there, but it's a good idea to check anyway. If it's not there, I would suggest installing a different version of Python. There might be something wrong with the packaging of that particular version, who knows? And I would try a release with a lower version if possible, just in case a later one accidentally used some instruction not compatible with your version of Windows 8 (unlikely, but just in case it could happen). For example, if you currently have Python 3.9.10, try Python 3.8.9. The available releases are all here: https://www.python.org/downloads/windows/ If this works, wonderful! If it does not, I'm out of ideas for the moment. On 11/11/2022 4:18 PM, darkstone at o2online.de wrote: > Hello, > > yes, its a Windows 8.1 with 32 bit. I have found my Installation ordner. > > If I type python > > ** IDLE can't import Tkinter. > Your Python may not configured for TK. ** > > So I tried this: > > >>> import _tkinter > Traceback (most recent call last): > ? File "", line 1, in > ImportError: DLL load failed while importing _tkinter: Das angegebene > Modul wurd > e nicht gefunden. > > So I it is a tkinter Problem and I tried this: > > >>> import _tkinter > Traceback (most recent call last): > ? File "", line 1, in > ImportError: DLL load failed while importing _tkinter: Das angegebene > Modul wurd > e nicht gefunden. > > How can I go gon, to make it work? > > > > > > *Von:* Thomas Passin > *Gesendet:*??Donnerstag?, ?10?. ?November? ?2022 ?03?:?00 > *An:* python-list at python.org > > > On 11/9/2022 7:02 PM, darkstone at o2online.de wrote: > > Is there no one who can help? > > Is there a reason why you tried to install a 32-bit version?? Most > personal computers are 64-bit ones these days. Also, I don't remember if > you are running Windows or not. > > One problem for getting help from the list is that there have not been > many details given. "Doesn't start" is not helpful.? Are there error > messages displayed on the terminal?? How did you try to start it?? Does > Python run at all? > > A Python installation normally includes a batch file that launches idle. > ? This batch file may not be on your path for one reason or another.? If > so, it would not run when you type "idle" at a command line. > > So the first thing to do is to figure out if you have either the Python > program idle.py or idle.pyw, or the batch file idle.bat (for Windows) > On Linux Mint, when I typed "idle" at a terminal, I got this message: > > "Command 'idle' not found, but can be installed with: > > sudo apt install idle" > > So that's how you would get it with that flavor of Linux. > > I'm going to walk through what I would probably do if I had the same > problem on Windows (I'm going to assume that you are running Windows). > It's a little long to write out, but not really that hard.? Basically, > there are only a few steps: > > 1. Find your Python installation; > 2. Look in the installation location to see if the idle program is there; > 3.? If it is, try to run it and note any error messages. > > First you need to find out where your Python installation is located on > your system disk. If you don't know, one way to find out is to run the > following command in a console window: > > where /R %USERPROFILE% python.exe > > You may be surprised that there more several ones that you didn't > expect, such as (on my computer): > > C:\Users\tom\AppData\Local\Microsoft\WindowsApps\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe\python.exe > > It seems that Windows has its own Python installation; that's not the > one you want.? You are looking for one that looks like this (with your > own user name, of course, instead of mine): > > C:\Users\tom\AppData\Local\Programs\Python\Python310\python.exe > > Appdata\Local\Programs is where Python3 usually gets installed.? Now we > know that I have Python 3.10 at > C:\Users\tom\AppData\Local\Programs\Python.? You may be using a > different version of Python; if so, just use that version instead. > > Idle is normally installed in the directory tree under python.? Let's > call the top of that tree %PYTH0N%.? On my system, as we see above, that > is C:\Users\tom\AppData\Local\Programs\Python\Python310.? Idle should be at > > %PYTHON%\Lib\idlelib > > Open Windows explorer, and navigate to that directory. If you have that > directory, then you should be able to run idle.? If it doesn't exist, > That's a problem and needs to be fixed, probably by a fresh install of > Python.? If it does, you will see the batch file idle.bat.? Double-click > it, and idle should run.? If it does not, see below. > > That's not a convenient way to run idle time after time.? Either you > need to get idle on your path, or perhaps it will be available using the > windows Start menu.? Check that out by tapping the Windows key, then > typing "idle" (without the quotes).? It may be there.? But look closely, > for it may be the idle associated with a different version of Python > than the one you want to use.? For example, on my system I have Idle in > the Start Menu, but only for Python 3.7 and not Python 3.10 which is the > most recent version I have. > > If you double-clicked on the idle batch file but it failed to run, then > you need to get any error messages.? You need to run it from a console > so you can see any output.? Open a console. you want to run idle using > python and not pythonw (because pythonw will not open a window).? So in > the console, type "python " (without quotes but with the space), then > the path to the file. > > The path to the file is a lot to type, and it's easier to just drag the > icon for the file (remember, it's idle.py) into the console window. > Press the key and idle should run.? If it doesn't, note any > error messages.? Then come back here and tell us what they were. > > It's possible that the "where" program didn't find your python > installation.? That would be because it's installed somewhere outside of > your user tree, like Program Files.? You can look again in the entire > disk (assuming it's on the c: drive, which is almost certainly so): > > where /R c:\% python.exe > > > Von: darkstone at o2online.de > > Gesendet: ?Freitag?, ?4?. ?November? ?2022 ?15?:?10 > > An: Eryk Sun > > Cc: python-list at python.org > > > > > > > > > > > > Yes, there is always the message ?modified successfull?, ?installed > sucessfully?, but IDLE does?t start. I tried it with the newer Version, > too. Ist 3.11.0 for 32 bit, but it also doesn?t work. Do you have other > suggetions, that it works? > > > > > > > > > > > > > > > > Von: Eryk Sun > > Gesendet: ?Donnerstag?, ?3?. ?November? ?2022 ?22?:?50 > > An: darkstone at o2online.de > > Cc: python-list at python.org > > > > > > > > > > > > On 11/3/22, darkstone at o2online.de wrote: > >> Is there a reason, why it is not installed? Its the same check mark > in the > >> installer like IDLE? > > > > Did you try what I suggested? Modify the installation to remove the > > tkinter/IDLE component. Then modify it again to select the component > > to be reinstalled. Also, try to repair the installation. This may > > reset any DLLs or extension modules that were missing or that were the > > wrong version. > > > > Ignore the suggestion from Nithish to install tkinter via pip. tkinter > > is part of the standard library and cannot be installed via pip. There > > is no tkinter package on the Python package index (pypi.org). > > -- > https://mail.python.org/mailman/listinfo/python-list > From gweatherby at uchc.edu Sat Nov 12 10:03:10 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Sat, 12 Nov 2022 15:03:10 +0000 Subject: Need max values in list of tuples, based on position In-Reply-To: References: <6n2tmhdq21nqd4lqnb6mo7srkullne1not@4ax.com> <395e3c0a-b11b-bfd9-cc1f-ba0388ce258d@tompassin.net> Message-ID: Types are available if you want to use them. https://www.pythontutorial.net/python-basics/python-type-hints/ From: Python-list on behalf of Pancho via Python-list Date: Friday, November 11, 2022 at 6:28 PM To: python-list at python.org Subject: Re: Need max values in list of tuples, based on position That was one of the things I didn't like about Python. Lack of types and subsequent loss of intellisense is the thing I find hardest to deal with. -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!jAUMq5gqI7J7UJIYw7lfpUMAy-BZPyyY8uWLJLVdVLWCaVMSBzVE6uX4RWQ-YZ0c3gvnIYn1u0r0BOmdCvEVAhyK6g$ From gweatherby at uchc.edu Sat Nov 12 09:40:56 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Sat, 12 Nov 2022 14:40:56 +0000 Subject: Argument name should be lowercase In-Reply-To: References: <0eba3f9d-c89c-062e-425a-54aea7216b11@DancesWithMice.info> Message-ID: RUN is a global constant, and the method is documented, explaining why the parameter is there: # Copy globals as function locals to make sure that they are available # during Python shutdown when the Pool is destroyed. def __del__(self, _warn=warnings.warn, RUN=RUN): From: Python-list on behalf of Stefan Ram Date: Friday, November 11, 2022 at 2:42 PM To: python-list at python.org Subject: Re: Argument name should be lowercase *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** "Weatherby,Gerard" writes: >I'd personally find it weird to see an all-cap parameter In the source code of the standard library, all-caps notation is used for a parameter name sometimes if that parameter name is "URL" or sometimes when it is being initialized from an all-caps name as in: |def __del__(self, _warn=warnings.warn, RUN=RUN): | if self._state == RUN: ... from "pool.py". ("RUN=RUN" makes RUN have the value "RUN" had at the time of the definition of the function.) -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!kI1c1EIpXCtnz0SBHvQmJokWXPBo0rCY9MQ-IwXOZU4RyHqqKho9wMu6Ekj6GMXA0EbReT8_4GOxvoldiOsL3W8$ From 2QdxY4RzWzUUiLuE at potatochowder.com Sat Nov 12 11:09:28 2022 From: 2QdxY4RzWzUUiLuE at potatochowder.com (2QdxY4RzWzUUiLuE at potatochowder.com) Date: Sat, 12 Nov 2022 11:09:28 -0500 Subject: Need max values in list of tuples, based on position In-Reply-To: References: <6n2tmhdq21nqd4lqnb6mo7srkullne1not@4ax.com> <395e3c0a-b11b-bfd9-cc1f-ba0388ce258d@tompassin.net> Message-ID: On 2022-11-12 at 15:03:10 +0000, "Weatherby,Gerard" wrote: > Types are available if you want to use > them. https://www.pythontutorial.net/python-basics/python-type-hints/ Python has always been a strongly typed language. Recent changes have given it some level of static type checking in addition to the dyunamic typing. > From: Python-list on behalf of Pancho via Python-list > Date: Friday, November 11, 2022 at 6:28 PM > To: python-list at python.org > Subject: Re: Need max values in list of tuples, based on position > > That was one of the things I didn't like about Python. Lack of types and > subsequent loss of intellisense is the thing I find hardest to deal with. -- I can eat glass, it does not hurt me. Dan Sommers, http://www.tombstonezero.net/dan From arequipeno at gmail.com Sat Nov 12 11:34:24 2022 From: arequipeno at gmail.com (Ian Pilcher) Date: Sat, 12 Nov 2022 10:34:24 -0600 Subject: Dealing with non-callable classmethod objects In-Reply-To: References: Message-ID: On 11/11/22 16:47, Cameron Simpson wrote: > On 11Nov2022 15:29, Ian Pilcher wrote: >> * Can I improve the 'if callable(factory):' test above?? This treats >> ?all non-callable objects as classmethods, which is obviously not >> ?correct.? Ideally, I would check specifically for a classmethod, but >> ?there doesn't seem to be any literal against which I could check the >> ?factory's type. > > Yeah, it does feel a bit touchy feely. > > You could see if the `inspect` module tells you more precise things > about the `factory`. > > The other suggestion I have is to put the method name in `_attrs`; if > that's a `str` you could special case it as a well known type for the > factory and look it up with `getattr(cls,factory)`. So I've done this. class _HasUnboundClassMethod(object): @classmethod def _classmethod(cls): pass # pragma: no cover _methods = [ _classmethod ] _ClassMethodType = type(_HasUnboundClassMethod._methods[0]) Which allows me to do this: def __init__(self, d): for attr, factory in self._attrs.items(): if callable(factory): value = factory(d[attr]) else: assert type(factory) is self._ClassMethodType value = factory.__func__(type(self), d[attr]) setattr(self, attr, value) It's a bit cleaner, although I'm not thrilled about having a throwaway class, just to define a literal that ought to be provided by the runtime. -- ======================================================================== Google Where SkyNet meets Idiocracy ======================================================================== From list1 at tompassin.net Sat Nov 12 13:01:11 2022 From: list1 at tompassin.net (Thomas Passin) Date: Sat, 12 Nov 2022 13:01:11 -0500 Subject: Problems with IDLE in Windows 8.1 and installer x86 Version 3.10.8 In-Reply-To: <202211121650.2ACGokE8103881@mail193c50.megamailservers.eu> References: <202210311822.29VIMTpw130438@mail92c50.megamailservers.eu> <202210312138.29VLcBUQ008124@mail118c50.megamailservers.eu> <202211011649.2A1GnNrU115152@mail36c50.megamailservers.eu> <202211032129.2A3LTmtc065950@mail193c50.megamailservers.eu> <202211041414.2A4EE2xL017716@mail264c50.megamailservers.eu> <202211100003.2AA03LR5098382@mail266c50.megamailservers.eu> <59f3470c-fffb-4354-1712-67814f257e66@tompassin.net> <202211121242.2ACCgcuL102426@mail265c50.megamailservers.eu> <202211121650.2ACGokE8103881@mail193c50.megamailservers.eu> Message-ID: <1ffce7ef-829f-798f-cf11-e8e433989ee8@tompassin.net> On 11/12/2022 11:48 AM, darkstone at o2online.de wrote: > Hello Thomas, > > there is a??_tkinter.pyd? in the *.dll Directory. Is there something > more, I can check? Yes, look in the "Lib" (NOT "libs") subdirectory of the Python tree and see if it has a subdirectory named "tkinter". That's where it is in my own Python installations. If it's there check to see if it actually has anything in it. Probably it will be populated. The next thing would to see if we can work out what's going wrong. As long as you are in the LIB directory, check and see if it has a subdirectory named "idlelib". If it does, try to run its self-tests**. In a console window, type the following command: python -m idlelib.idle_test.htest If it works, there it will put up a succession of little Tk dialogs and windows. If you get any of them, you can cancel out of it, since you won't need to run dozens of little self-tests. NOTE - on your system, the command "python" might run Python 2.7 instead of Python 3.x. So use the right name for your version of Python - or use "py" (no quotes), which recent Python installers set up so you probably have it. BTW, what version(s) of Python do you have installed? If you said in a previous post, I don't recall. You can check what version is running when you use the name "python" by using this command line (Note the upper-case "V"): python -V ** I found out about this self-test command line because I noticed a file README.txt in the idlelib\idle_test subdirectory, and read it. It pays to be curious and nosy when trying to work out computer problems. > *Von:* Thomas Passin > *Gesendet:*??Samstag?, ?12?. ?November? ?2022 ?14?:?42 > *An:* darkstone at o2online.de > *Cc:* python-list at python.org > > All right, now let's verify that tk is not there (otherwise it might be > there but corrupted or not loadable for some reason). > > Open Windows Explorer and navigate it to the Python directory as I > described in my last message. The navigate to the subdirectory named > "DLLs".? If tkinter is installed, there will be a file named > "_tkinter.pyd".? If that file is missing, then definitely tk isn't > there.? If it is, then it's been installed but something is wrong with > the install. > > Probably it won't be there, but it's a good idea to check anyway. > > If it's not there, I would suggest installing a different version of > Python.? There might be something wrong with the packaging of that > particular version, who knows?? And I would try a release with a lower > version if possible, just in case a later one accidentally used some > instruction not compatible with your version of Windows 8 (unlikely, but > just in case it could happen).? For example, if you currently have > Python 3.9.10, try Python 3.8.9.? The available releases are all here: > > https://www.python.org/downloads/windows/ > > If this works, wonderful!? If it does not, I'm out of ideas for the moment. > > On 11/11/2022 4:18 PM, darkstone at o2online.de wrote: > > Hello, > > > > yes, its a Windows 8.1 with 32 bit. I have found my Installation ordner. > > > > If I type python > > > > ** IDLE can't import Tkinter. > > Your Python may not configured for TK. ** > > > > So I tried this: > > > >? >>> import _tkinter > > Traceback (most recent call last): > >? ? File "", line 1, in > > ImportError: DLL load failed while importing _tkinter: Das angegebene > > Modul wurd > > e nicht gefunden. > > > > So I it is a tkinter Problem and I tried this: > > > >? >>> import _tkinter > > Traceback (most recent call last): > >? ? File "", line 1, in > > ImportError: DLL load failed while importing _tkinter: Das angegebene > > Modul wurd > > e nicht gefunden. > > > > How can I go gon, to make it work? > > > > > > > > > > > > *Von:* Thomas Passin > > *Gesendet:*??Donnerstag?, ?10?. ?November? ?2022 ?03?:?00 > > *An:* python-list at python.org > > > > > > On 11/9/2022 7:02 PM, darkstone at o2online.de wrote: > >? > Is there no one who can help? > > > > Is there a reason why you tried to install a 32-bit version?? Most > > personal computers are 64-bit ones these days. Also, I don't remember if > > you are running Windows or not. > > > > One problem for getting help from the list is that there have not been > > many details given. "Doesn't start" is not helpful.? Are there error > > messages displayed on the terminal?? How did you try to start it?? Does > > Python run at all? > > > > A Python installation normally includes a batch file that launches idle. > >? ? This batch file may not be on your path for one reason or another.? If > > so, it would not run when you type "idle" at a command line. > > > > So the first thing to do is to figure out if you have either the Python > > program idle.py or idle.pyw, or the batch file idle.bat (for Windows) > > On Linux Mint, when I typed "idle" at a terminal, I got this message: > > > > "Command 'idle' not found, but can be installed with: > > > > sudo apt install idle" > > > > So that's how you would get it with that flavor of Linux. > > > > I'm going to walk through what I would probably do if I had the same > > problem on Windows (I'm going to assume that you are running Windows). > > It's a little long to write out, but not really that hard.? Basically, > > there are only a few steps: > > > > 1. Find your Python installation; > > 2. Look in the installation location to see if the idle program is there; > > 3.? If it is, try to run it and note any error messages. > > > > First you need to find out where your Python installation is located on > > your system disk. If you don't know, one way to find out is to run the > > following command in a console window: > > > > where /R %USERPROFILE% python.exe > > > > You may be surprised that there more several ones that you didn't > > expect, such as (on my computer): > > > > > C:\Users\tom\AppData\Local\Microsoft\WindowsApps\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe\python.exe > > > > It seems that Windows has its own Python installation; that's not the > > one you want.? You are looking for one that looks like this (with your > > own user name, of course, instead of mine): > > > > C:\Users\tom\AppData\Local\Programs\Python\Python310\python.exe > > > > Appdata\Local\Programs is where Python3 usually gets installed.? Now we > > know that I have Python 3.10 at > > C:\Users\tom\AppData\Local\Programs\Python.? You may be using a > > different version of Python; if so, just use that version instead. > > > > Idle is normally installed in the directory tree under python.? Let's > > call the top of that tree %PYTH0N%.? On my system, as we see above, that > > is C:\Users\tom\AppData\Local\Programs\Python\Python310.? Idle should > be at > > > > %PYTHON%\Lib\idlelib > > > > Open Windows explorer, and navigate to that directory. If you have that > > directory, then you should be able to run idle.? If it doesn't exist, > > That's a problem and needs to be fixed, probably by a fresh install of > > Python.? If it does, you will see the batch file idle.bat.? Double-click > > it, and idle should run.? If it does not, see below. > > > > That's not a convenient way to run idle time after time.? Either you > > need to get idle on your path, or perhaps it will be available using the > > windows Start menu.? Check that out by tapping the Windows key, then > > typing "idle" (without the quotes).? It may be there.? But look closely, > > for it may be the idle associated with a different version of Python > > than the one you want to use.? For example, on my system I have Idle in > > the Start Menu, but only for Python 3.7 and not Python 3.10 which is the > > most recent version I have. > > > > If you double-clicked on the idle batch file but it failed to run, then > > you need to get any error messages.? You need to run it from a console > > so you can see any output.? Open a console. you want to run idle using > > python and not pythonw (because pythonw will not open a window).? So in > > the console, type "python " (without quotes but with the space), then > > the path to the file. > > > > The path to the file is a lot to type, and it's easier to just drag the > > icon for the file (remember, it's idle.py) into the console window. > > Press the key and idle should run.? If it doesn't, note any > > error messages.? Then come back here and tell us what they were. > > > > It's possible that the "where" program didn't find your python > > installation.? That would be because it's installed somewhere outside of > > your user tree, like Program Files.? You can look again in the entire > > disk (assuming it's on the c: drive, which is almost certainly so): > > > > where /R c:\% python.exe > > > >? > Von: darkstone at o2online.de > >? > Gesendet: ?Freitag?, ?4?. ?November? ?2022 ?15?:?10 > >? > An: Eryk Sun > >? > Cc: python-list at python.org > >? > > >? > > >? > > >? > > >? > > >? > Yes, there is always the message ?modified successfull?, ?installed > > sucessfully?, but IDLE does?t start. I tried it with the newer Version, > > too. Ist 3.11.0 for 32 bit, but it also doesn?t work. Do you have other > > suggetions, that it works? > >? > > >? > > >? > > >? > > >? > > >? > > >? > > >? > Von: Eryk Sun > >? > Gesendet: ?Donnerstag?, ?3?. ?November? ?2022 ?22?:?50 > >? > An: darkstone at o2online.de > >? > Cc: python-list at python.org > >? > > >? > > >? > > >? > > >? > > >? > On 11/3/22, darkstone at o2online.de wrote: > >? >> Is there a reason, why it is not installed? Its the same check mark > > in the > >? >> installer like IDLE? > >? > > >? > Did you try what I suggested? Modify the installation to remove the > >? > tkinter/IDLE component. Then modify it again to select the component > >? > to be reinstalled. Also, try to repair the installation. This may > >? > reset any DLLs or extension modules that were missing or that were the > >? > wrong version. > >? > > >? > Ignore the suggestion from Nithish to install tkinter via pip. tkinter > >? > is part of the standard library and cannot be installed via pip. There > >? > is no tkinter package on the Python package index (pypi.org). > > > > -- > > https://mail.python.org/mailman/listinfo/python-list > > > From wharris1 at protonmail.com Sat Nov 12 10:56:25 2022 From: wharris1 at protonmail.com (Wayne Harris) Date: Sat, 12 Nov 2022 12:56:25 -0300 Subject: Persisting functions typed into the shell References: Message-ID: On 12/11/2022 10:01, Stefan Ram wrote: > Many readers here know interactive Python sessions with > prompts like ">>>". But a "session" could be something else. > One could imagine that when starting a new session, one > still sees all the variables and constants defined in > preceding sessions. > > I have implemented something like a "restore()" and a "save()" > call. "restore()" will restore the names from the last "save()". > "save()" will look for user-defined names (it excludes certain > standard names and certain other names from my software) and > save them using the "shelve" package from the standard library. > > I you know "shelve" or have read the subject line, you can > guess what comes now: > > I cannot save user-defined functions this way! > > When a user types into the console: > > |>>> def f(): > |... print( "example" ) > |... > > he gives source code to shell and hopes that the shell will > cherish the memory of that function. But instead it acts as > if from now on it does not know the source code of "f"! > > So, there seems to be no way now to persist this function > to a file? as if by "save( f )" or something similar? > If not the source code, then maybe some other form? > > So much for the topic of "In Python, /everything/ is an > object"! There seem to be first and second-class objects: > Shelveable and non-shelveable objects. Wow. Could the dis module help at all? Say by getting the bytes of the compiled function and then saving them to a file, then reading them off later and rebuilding the function with dis again? From wlfraed at ix.netcom.com Sat Nov 12 13:24:37 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sat, 12 Nov 2022 13:24:37 -0500 Subject: Need max values in list of tuples, based on position References: <6n2tmhdq21nqd4lqnb6mo7srkullne1not@4ax.com> Message-ID: On Fri, 11 Nov 2022 21:20:10 -0500, DFS declaimed the following: >Yeah, I don't know why cursor.description doesn't work with SQLite; all >their columns are basically varchars. > If you read PEP 249 (the general DB-API), everything except column name and data type code are optional. And the documentation for the sqlite3 module explicitly states that it only provides the column name, not even type code. > >The query is literally any SELECT, any type of data, including SELECT *. > The reason it works with SELECT * is the cursor.description against >SQLite DOES give the column names: > >select * from timezone; >print(cur.description) >( >('TIMEZONE', None, None, None, None, None, None), >('TIMEZONEDESC', None, None, None, None, None, None), >('UTC_OFFSET', None, None, None, None, None, None) >) > >(I lined up the data) > > Consider (table definition first) CREATE TABLE Game ( ID INTEGER PRIMARY KEY NOT NULL, Variant VARCHAR(64) NOT NULL, Num_of_Decks INTEGER DEFAULT 1 NOT NULL, Cards_in_Deck INTEGER DEFAULT 52 NOT NULL, Num_Tableau_Cards INTEGER NOT NULL, Num_Reserve_Cards INTEGER GENERATED ALWAYS AS ((Num_of_Decks * Cards_in_Deck) - Num_Tableau_Cards) STORED, Foundation_Value INTEGER DEFAULT 1 NOT NULL, Tableau_Value INTEGER DEFAULT -1 NOT NULL, Reserve_Value INTEGER DEFAULT -2 NOT NULL ); CREATE UNIQUE INDEX idx_Variant ON Game (Variant); followed by a session retrieving three columns... >>> import sqlite3 as db >>> con = db.connect("c:/users/wulfraed/documents/.localdatabases/solitaire-sqlite/solitaire.db") >>> cur = con.cursor() >>> cur.execute("""select max(length(variant)), max(length(cards_in_deck)), ... max(length(num_reserve_cards)) from Game""") >>> widths = cur.fetchall() >>> widths [(16, 2, 2)] >>> >>> widths[0] (16, 2, 2) >>> pformat = [f'%{w}s' for w in widths[0] ] >>> pformat ['%16s', '%2s', '%2s'] >>> pformat = "\t".join(pformat) >>> pformat '%16s\t%2s\t%2s' >>> for row in cur.fetchall(): ... print(pformat % row) ... Klondike draw-3 52 24 Perpetual Motion 52 52 Klondike draw-1 52 24 >>> Granted, this will NOT work with "select *" unless one does the select */fetchall first, AND extracts the names from the cursor description -- then run a loop to create the select max(length(col)), ... statement (which is why I state the fetchall step, as unless one creates a second cursor, the latter select will wipe out any unfetched data from the first). It lets SQLite do the work of determining the max width occupied by each column, rather than some complicated Python loop. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From PythonList at DancesWithMice.info Sat Nov 12 14:02:31 2022 From: PythonList at DancesWithMice.info (dn) Date: Sun, 13 Nov 2022 08:02:31 +1300 Subject: Persisting functions typed into the shell In-Reply-To: References: Message-ID: On 13/11/2022 05.05, Stefan Ram wrote: > Wayne Harris writes: >> Wow. Could the dis module help at all? > > Thank you for this idea! I think this should work, but only > under CPython and not necessarily across different Python > versions. Still, I might use dis. Was constructing a two-part tutorial. When it came to the preparing for the second meeting, was surprised to discover that PyCharm retained code and values in its Python Console (its REPL tab/window) - I'm presuming, within its 'project' structure. Was more interested in ensuring all-parties would be able to re-create the ending/re-starting position, regardless of IDE. Accordingly, never looked any further. Depending upon the full range of criteria, may be worth a look... Disclaimer: JetBrains sponsor our local PUG with a one-year 'pro' license, as a monthly 'door prize'. Apart from using the product, have no other connection! Similarly, have not looked at such within VS-Codium or other editors/IDEs... -- Regards, =dn From gweatherby at uchc.edu Sat Nov 12 13:44:32 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Sat, 12 Nov 2022 18:44:32 +0000 Subject: Dealing with non-callable classmethod objects In-Reply-To: References: Message-ID: Use the inspect module as Cameron suggested. import inspect def analyze_class(clzz): """Analyze a class proof of concept""" assert inspect.isclass(clzz) for k, v in inspect.getmembers(clzz, lambda v: inspect.isfunction(v) or inspect.ismethod(v)): if inspect.ismethod(v): print(f"{v.__qualname__} -> class method ") if inspect.isfunction(v): sig = inspect.signature(v) names = [n for n, _ in sig.parameters.items()] if len(names) > 0 and str(names[0]) == 'self': print(f"{v.__qualname__}-> probably a bound method ") else: print(f"{v.__qualname__}-> probably a static method ") class Demo: @classmethod def us(cls): print(cls.__name__) @staticmethod def double(x): return x + x def triple(self, y): return 3 * y analyze_class(Demo) output: Demo.double-> probably a static method Demo.triple-> probably a bound method Demo.us -> class method From: Python-list on behalf of Ian Pilcher Date: Saturday, November 12, 2022 at 11:36 AM To: python-list at python.org Subject: Re: Dealing with non-callable classmethod objects *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** On 11/11/22 16:47, Cameron Simpson wrote: > On 11Nov2022 15:29, Ian Pilcher wrote: >> * Can I improve the 'if callable(factory):' test above? This treats >> all non-callable objects as classmethods, which is obviously not >> correct. Ideally, I would check specifically for a classmethod, but >> there doesn't seem to be any literal against which I could check the >> factory's type. > > Yeah, it does feel a bit touchy feely. > > You could see if the `inspect` module tells you more precise things > about the `factory`. > > The other suggestion I have is to put the method name in `_attrs`; if > that's a `str` you could special case it as a well known type for the > factory and look it up with `getattr(cls,factory)`. So I've done this. class _HasUnboundClassMethod(object): @classmethod def _classmethod(cls): pass # pragma: no cover _methods = [ _classmethod ] _ClassMethodType = type(_HasUnboundClassMethod._methods[0]) Which allows me to do this: def __init__(self, d): for attr, factory in self._attrs.items(): if callable(factory): value = factory(d[attr]) else: assert type(factory) is self._ClassMethodType value = factory.__func__(type(self), d[attr]) setattr(self, attr, value) It's a bit cleaner, although I'm not thrilled about having a throwaway class, just to define a literal that ought to be provided by the runtime. -- ======================================================================== Google Where SkyNet meets Idiocracy ======================================================================== -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!nx6jxVGHt4Gj1WplLAV4uuhaMyS7Ry0qTCGvZm7jLCj9GbK4vto49sfmP12TTgcAT6Akjz5hJWw9JoylO_FrgQ$ From gweatherby at uchc.edu Sat Nov 12 14:33:20 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Sat, 12 Nov 2022 19:33:20 +0000 Subject: Persisting functions typed into the shell In-Reply-To: References: Message-ID: Sounds like Jupyter Notebooks: https://jupyter.org From: Python-list on behalf of Stefan Ram Date: Saturday, November 12, 2022 at 1:48 PM To: python-list at python.org Subject: Persisting functions typed into the shell *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** Many readers here know interactive Python sessions with prompts like ">>>". But a "session" could be something else. One could imagine that when starting a new session, one still sees all the variables and constants defined in preceding sessions. I have implemented something like a "restore()" and a "save()" call. "restore()" will restore the names from the last "save()". "save()" will look for user-defined names (it excludes certain standard names and certain other names from my software) and save them using the "shelve" package from the standard library. I you know "shelve" or have read the subject line, you can guess what comes now: I cannot save user-defined functions this way! When a user types into the console: |>>> def f(): |... print( "example" ) |... he gives source code to shell and hopes that the shell will cherish the memory of that function. But instead it acts as if from now on it does not know the source code of "f"! So, there seems to be no way now to persist this function to a file? as if by "save( f )" or something similar? If not the source code, then maybe some other form? So much for the topic of "In Python, /everything/ is an object"! There seem to be first and second-class objects: Shelveable and non-shelveable objects. -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!kVssvGre00pk5iMVIWUbuGXUwcZ8veRBEuSiX-VLlkRVlJoQ96fl6CZG9zQ72Hky8qqofZhhhA5qZpkneyEz4-4$ From wlfraed at ix.netcom.com Sat Nov 12 13:51:36 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sat, 12 Nov 2022 13:51:36 -0500 Subject: Need max values in list of tuples, based on position References: <6n2tmhdq21nqd4lqnb6mo7srkullne1not@4ax.com> Message-ID: <4aqvmhtbb3crvn2mkase4f6u20s4t28boa@4ax.com> On Sat, 12 Nov 2022 13:24:37 -0500, Dennis Lee Bieber declaimed the following: > Granted, this will NOT work with "select *" unless one does the select >*/fetchall first, AND extracts the names from the cursor description -- >then run a loop to create the select max(length(col)), ... statement (which >is why I state the fetchall step, as unless one creates a second cursor, >the latter select will wipe out any unfetched data from the first). > Okay, a follow-up... >>> import sqlite3 as db >>> con = db.connect("c:/users/wulfraed/documents/.localdatabases/solitaire-sqlite/solitaire.db") >>> cur = con.cursor() >>> cur.execute("select * from game") >>> columns = [ "max(length(%s))" % col[0] for col in cur.description ] >>> columns ['max(length(ID))', 'max(length(Variant))', 'max(length(Num_of_Decks))', 'max(length(Cards_in_Deck))', 'max(length(Num_Tableau_Cards))', 'max(length(Num_Reserve_Cards))', 'max(length(Foundation_Value))', 'max(length(Tableau_Value))', 'max(length(Reserve_Value))'] >>> sql = "select %s from game" % ", ".join(columns) >>> data = cur.fetchall() >>> cur.execute(sql) >>> widths = cur.fetchone() >>> widths (1, 16, 1, 2, 2, 2, 1, 2, 2) >>> pformat = [ f'%{w}s' for w in widths ] >>> pformat ['%1s', '%16s', '%1s', '%2s', '%2s', '%2s', '%1s', '%2s', '%2s'] >>> pformat = " | ".join(pformat) >>> for row in data: ... print(pformat % row) ... 1 | Klondike draw-3 | 1 | 52 | 28 | 24 | 1 | -1 | -2 2 | Perpetual Motion | 1 | 52 | 0 | 52 | 1 | -1 | -1 3 | Klondike draw-1 | 1 | 52 | 28 | 24 | 1 | -1 | -2 I used " | " rather than "\t" as column separators. View with a fixed width font. It could be a tad shorter -- the list-comps for columns and widths (pformat) could be embedded IN the .join() calls. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From eryksun at gmail.com Sat Nov 12 14:47:00 2022 From: eryksun at gmail.com (Eryk Sun) Date: Sat, 12 Nov 2022 13:47:00 -0600 Subject: Problems with IDLE in Windows 8.1 and installer x86 Version 3.10.8 In-Reply-To: <202211121235.2ACCZlWQ020269@mail193c50.megamailservers.eu> References: <202210311822.29VIMTpw130438@mail92c50.megamailservers.eu> <202210312138.29VLcBUQ008124@mail118c50.megamailservers.eu> <202211011649.2A1GnNrU115152@mail36c50.megamailservers.eu> <202211032129.2A3LTmtc065950@mail193c50.megamailservers.eu> <202211041414.2A4EE2xL017716@mail264c50.megamailservers.eu> <202211100003.2AA03LR5098382@mail266c50.megamailservers.eu> <202211112017.2ABKH2nC027172@mail265c50.megamailservers.eu> <202211121235.2ACCZlWQ020269@mail193c50.megamailservers.eu> Message-ID: On 11/12/22, darkstone at o2online.de wrote: > >>>> import _tkinter > Traceback (most recent call last): > File "", line 1, in > ImportError: DLL load failed while importing _tkinter: Das angegebene Modul > wurd > e nicht gefunden. Loading the extension module "_tkinter.pyd" tries to load two TCL/Tk DLL files that should be in the same directory: "tcl86t.dll" and "tk86t.dll". Previously I asked you to look for these two files, and you said they were there, but maybe one is corrupt. Please try the following in the interactive shell: import os, sys, ctypes tcl86 = os.path.join(sys.prefix, 'DLLs', 'tcl86t.dll') tk86 = os.path.join(sys.prefix, 'DLLs', 'tk86t.dll') Run the following two statements one after the other in the shell: ctypes.CDLL(tcl86) ctypes.CDLL(tk86) Either or both will fail if the DLL or one of its dependencies can't be found or loaded. From cs at cskk.id.au Sat Nov 12 15:52:52 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 13 Nov 2022 07:52:52 +1100 Subject: Dealing with non-callable classmethod objects In-Reply-To: References: Message-ID: On 12Nov2022 18:44, Weatherby,Gerard wrote: >Use the inspect module as Cameron suggested. My suggestions was not for the post-construction class attributes but for the comtents of the "_attrs" mapping. Post construction the class method is callable. But the classmethod object stashed in "_attrs" is not. However, it _is_ of type "classmethod", which means it can be identified without using "inspect". Here's an alternative demo programme: class Demo: @classmethod def us(cls): print(cls.__name__) @staticmethod def double(x): return x + x def triple(self, y): return 3 * y _attrs = { "double": double, "triple": triple, "us": us, } for name, attr in Demo._attrs.items(): print(name, "->", attr, type(attr)) print(" is class method =", type(attr) is classmethod) print(" is callable =", callable(attr)) if inspect.ismethod(attr): print(" ismethod") if inspect.isfunction(attr): print(" isfunction") breakpoint() I stuck a breakpoint in so that I could inspect things after the run. The run looks like this: py3 demo1.py double -> is class method = False is callable = False triple -> is class method = False is callable = True isfunction us -> is class method = True is callable = False so just testing "type(attr) is classmethod" identifies the unpromoted class method. I need to real Ian's other post to see what he did to turn that into a callable factory function. Cheers, Cameron Simpson From cs at cskk.id.au Sat Nov 12 15:57:16 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 13 Nov 2022 07:57:16 +1100 Subject: Dealing with non-callable classmethod objects In-Reply-To: References: Message-ID: On 12Nov2022 10:34, Ian Pilcher wrote: >So I've done this. > > class _HasUnboundClassMethod(object): > @classmethod > def _classmethod(cls): > pass # pragma: no cover > _methods = [ _classmethod ] > > _ClassMethodType = type(_HasUnboundClassMethod._methods[0]) > >Which allows me to do this: > > def __init__(self, d): > for attr, factory in self._attrs.items(): > if callable(factory): > value = factory(d[attr]) > else: > assert type(factory) is self._ClassMethodType > value = factory.__func__(type(self), d[attr]) > setattr(self, attr, value) > >It's a bit cleaner, although I'm not thrilled about having a throwaway >class, just to define a literal that ought to be provided by the >runtime. Ah, nice again. You shouldn't need a throwaway class, just use the name "classmethod" directly - it's the type! if not callable(factory): if type(factory) is classmethod: # replace fctory with a function calling factory.__func__ factory = lambda arg: factory.__func__(classmethod, arg) else: raise TypeError("unhandled factory type %s:%r" % (type(factory), factory) value = factory(d[attr]) Cheers, Cameron Simpson From rosuav at gmail.com Sat Nov 12 16:15:05 2022 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 13 Nov 2022 08:15:05 +1100 Subject: Persisting functions typed into the shell In-Reply-To: References: Message-ID: On Sun, 13 Nov 2022 at 05:48, Stefan Ram wrote: > So much for the topic of "In Python, /everything/ is an > object"! There seem to be first and second-class objects: > Shelveable and non-shelveable objects. > That's a bit unfair. Everything IS an object, but not all objects can be treated the same way. Complex numbers can't be compared for greater-than/less-than, but they are still first-class objects. Is it acceptable to you if the reconstituted function doesn't have source code (which will affect tracebacks and such), as long as it behaves the same way? If so, save the __code__.co_code attribute, and build a new function from that. ChrisA From arequipeno at gmail.com Sat Nov 12 17:46:39 2022 From: arequipeno at gmail.com (Ian Pilcher) Date: Sat, 12 Nov 2022 16:46:39 -0600 Subject: Dealing with non-callable classmethod objects In-Reply-To: References: Message-ID: <2789055e-1ca1-49bd-ffea-66ff4eec0ab6@gmail.com> On 11/12/22 14:57, Cameron Simpson wrote: > You shouldn't need a throwaway class, just use the name "classmethod" > directly - it's the type! > > ??? if not callable(factory): > ??????? if type(factory) is classmethod: > ??????????? # replace fctory with a function calling factory.__func__ > ??????????? factory = lambda arg: factory.__func__(classmethod, arg) > ??????? else: > ??????????? raise TypeError("unhandled factory type %s:%r" % > (type(factory), factory) > ??? value = factory(d[attr]) Or I could use the C++ version: face << palm; Thanks! -- ======================================================================== Google Where SkyNet meets Idiocracy ======================================================================== From cs at cskk.id.au Sat Nov 12 18:08:15 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 13 Nov 2022 10:08:15 +1100 Subject: Dealing with non-callable classmethod objects In-Reply-To: References: Message-ID: On 13Nov2022 07:57, Cameron Simpson wrote: > # replace fctory with a function calling factory.__func__ > factory = lambda arg: factory.__func__(classmethod, arg) It just occurred to me that you might need to grab the value of factory.__func__ first: factory0 = factory factory = lambda arg: factory0.__func__(classmethod, arg) Otherwise the closure might introduce a recursion. Cheers, Cameron Simpson From cs at cskk.id.au Sat Nov 12 19:12:46 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 13 Nov 2022 11:12:46 +1100 Subject: Dealing with non-callable classmethod objects In-Reply-To: References: Message-ID: On 13Nov2022 10:08, Cameron Simpson wrote: >On 13Nov2022 07:57, Cameron Simpson wrote: >> # replace fctory with a function calling factory.__func__ >> factory = lambda arg: factory.__func__(classmethod, arg) > >It just occurred to me that you might need to grab the value of >factory.__func__ first: > > factory0 = factory > factory = lambda arg: factory0.__func__(classmethod, arg) > >Otherwise the closure might introduce a recursion. Or avoid the closure: from functools import partial ...... factory = partial(factory.__func__, classmethod) to produces a partially filled in function. Cheers, Cameron Simpson From axy at declassed.art Sun Nov 13 07:27:42 2022 From: axy at declassed.art (Axy) Date: Sun, 13 Nov 2022 12:27:42 +0000 Subject: Superclass static method name from subclass In-Reply-To: References: Message-ID: <4f83091d-951e-eb3e-a3ad-670ecd894d97@declassed.art> On 11/11/2022 16:21, Ian Pilcher wrote: > Is it possible to access the name of a superclass static method, when > defining a subclass attribute, without specifically naming the super- > class? > > Contrived example: > > ? class SuperClass(object): > ????? @staticmethod > ????? def foo(): > ????????? pass > > ? class SubClass(SuperClass): > ????? bar = SuperClass.foo > ??????????? ^^^^^^^^^^ > > Is there a way to do this without specifically naming 'SuperClass'? > There is, but it's weird. I constructed classes from yaml config so I did not even know the name of super class but I wanted similar things for my clabate templates and I implemented superattr() which works for me: class BasePage: ??? body = '

Hello

' class MySpecificPage(BasePage): ??? body = superattr() + '

World

' Actually, it's suboptimally elegant code. Artistic code, to be clear, as if you looked at modern art and thought: WTF? Also, it's specific for templates only and supports only __add__. But I think the approach can be extended to a general superclass() if you log __getattr__ calls and apply them in __get__ method same way. I realize this reply is not an immediate help and probably won't help, but there's always a way out. Axy. Here's the code: class superattr: ''' This is a descriptor that allows extending attributes in a simple and elegant way: my_attr = superattr() + some_addition_to_my_attr ''' def __init__(self): self.additions = [] def __set_name__(self, owner, name): print('__set_name__', name) self.attr_name = name def __get__(self, obj, objtype=None): for cls in obj.__class__.__mro__[1:]: try: value = getattr(cls, self.attr_name) except AttributeError: continue for a in self.additions: value = value + a return value raise AttributeError(self.attr_name) def __add__(self, other): print('__add__:', other) self.additions.append(other) return self Full article: https://declassed.art/en/blog/2022/07/02/a-note-on-multiple-inheritance-in-python From 12jessicasmith34 at gmail.com Sun Nov 13 09:49:40 2022 From: 12jessicasmith34 at gmail.com (Jessica Smith) Date: Sun, 13 Nov 2022 08:49:40 -0600 Subject: Python 3.7+ cannot print unicode characters when output is redirected to file - is this a bug? Message-ID: Consider the following code ran in Powershell or cmd.exe: $ python -c "print('?')" ? $ python -c "print('?')" > test_file.txt Traceback (most recent call last): File "", line 1, in File "C:\Program Files\Python38\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u2514' in position 0: character maps to Is this a known limitation of Windows + Unicode? I understand that using -x utf8 would fix this, or modifying various environment variables. But is this expected for a standard Python installation on Windows? Jessica From barry at barrys-emacs.org Sun Nov 13 10:37:39 2022 From: barry at barrys-emacs.org (Barry) Date: Sun, 13 Nov 2022 15:37:39 +0000 Subject: Python 3.7+ cannot print unicode characters when output is redirected to file - is this a bug? In-Reply-To: References: Message-ID: <608AF608-BD83-47BD-AC85-5197608EAA76@barrys-emacs.org> > On 13 Nov 2022, at 14:52, Jessica Smith <12jessicasmith34 at gmail.com> wrote: > > ?Consider the following code ran in Powershell or cmd.exe: > > $ python -c "print('?')" > ? > > $ python -c "print('?')" > test_file.txt > Traceback (most recent call last): > File "", line 1, in > File "C:\Program Files\Python38\lib\encodings\cp1252.py", line 19, in encode > return codecs.charmap_encode(input,self.errors,encoding_table)[0] > UnicodeEncodeError: 'charmap' codec can't encode character '\u2514' in > position 0: character maps to > > Is this a known limitation of Windows + Unicode? I understand that > using -x utf8 would fix this, or modifying various environment > variables. But is this expected for a standard Python installation on > Windows? Your other thread has a reply that explained this. It is a problem with windows and character sets. You have to set things up to allow Unicode to work. Barry > > Jessica > -- > https://mail.python.org/mailman/listinfo/python-list From list1 at tompassin.net Sun Nov 13 10:45:57 2022 From: list1 at tompassin.net (Thomas Passin) Date: Sun, 13 Nov 2022 10:45:57 -0500 Subject: Python 3.7+ cannot print unicode characters when output is redirected to file - is this a bug? In-Reply-To: References: Message-ID: <1f1f291d-06af-58c2-185e-99f98b6b693f@tompassin.net> On 11/13/2022 9:49 AM, Jessica Smith wrote: > Consider the following code ran in Powershell or cmd.exe: > > $ python -c "print('?')" > ? > > $ python -c "print('?')" > test_file.txt > Traceback (most recent call last): > File "", line 1, in > File "C:\Program Files\Python38\lib\encodings\cp1252.py", line 19, in encode > return codecs.charmap_encode(input,self.errors,encoding_table)[0] > UnicodeEncodeError: 'charmap' codec can't encode character '\u2514' in > position 0: character maps to > > Is this a known limitation of Windows + Unicode? I understand that > using -x utf8 would fix this, or modifying various environment > variables. But is this expected for a standard Python installation on > Windows? > > Jessica This also fails with the same error: $ python -c "print('?')" |clip From 12jessicasmith34 at gmail.com Sun Nov 13 14:35:07 2022 From: 12jessicasmith34 at gmail.com (Jessica Smith) Date: Sun, 13 Nov 2022 13:35:07 -0600 Subject: Strange UnicodeEncodeError in Windows image on Azure DevOps and Github In-Reply-To: References: <959da7c4-cd04-46ba-8510-33cd1df4fb28@iPhone> Message-ID: On Fri, Nov 11, 2022 at 8:16 PM Eryk Sun wrote: > If sys.std* are console files, then in Python 3.6+, sys.std*.buffer.raw will be _io._WindowsConsoleIO > io.TextIOWrapper uses locale.getpreferredencoding(False) as the default encoding Thank you for your replies - checking the sys.stdout.buffer.raw value is what finally helped me understand. Turns out, the Windows agent is redirecting the output of all python commands to a file, so sys.stdout is a file using the locale encoding of cp1252, instead of being a stream using encoding utf8. I wrote up a gist with my findings to hopefully help out some other poor soul in the future: https://gist.github.com/NodeJSmith/e7e37f2d3f162456869f015f842bcf15 From Pancho.Jones at proton.me Sun Nov 13 07:37:10 2022 From: Pancho.Jones at proton.me (Pancho) Date: Sun, 13 Nov 2022 12:37:10 +0000 Subject: Need max values in list of tuples, based on position In-Reply-To: References: Message-ID: On 11/11/2022 19:56, DFS wrote: > Edit: found a solution online: > ----------------------------------------------------------------- > x = [(11,1,1),(1,41,2),(9,3,12)] > maxvals = [0]*len(x[0]) > for e in x: > ????maxvals = [max(w,int(c)) for w,c in zip(maxvals,e)] > print(maxvals) > [11,41,12] > ----------------------------------------------------------------- > > So now the challenge is making it a one-liner! > x = [(11,1,1),(1,41,2),(9,3,12)] print(functools.reduce( lambda a,b : [max(w,c) for w,c in zip(a,b)], x, [0]*len(x[0]))) From nospam at dfs.com Sun Nov 13 11:24:31 2022 From: nospam at dfs.com (DFS) Date: Sun, 13 Nov 2022 11:24:31 -0500 Subject: Need max values in list of tuples, based on position In-Reply-To: References: Message-ID: <3T8cL.81583$1449.29815@fx14.iad> On 11/13/2022 7:37 AM, Pancho wrote: > On 11/11/2022 19:56, DFS wrote: > >> Edit: found a solution online: >> ----------------------------------------------------------------- >> x = [(11,1,1),(1,41,2),(9,3,12)] >> maxvals = [0]*len(x[0]) >> for e in x: >> ?????maxvals = [max(w,int(c)) for w,c in zip(maxvals,e)] >> print(maxvals) >> [11,41,12] >> ----------------------------------------------------------------- >> >> So now the challenge is making it a one-liner! >> > > ?x = [(11,1,1),(1,41,2),(9,3,12)] > ?print(functools.reduce( lambda a,b : [max(w,c) for w,c in zip(a,b)], > ??????? x, [0]*len(x[0]))) noice! From eryksun at gmail.com Sun Nov 13 17:39:55 2022 From: eryksun at gmail.com (Eryk Sun) Date: Sun, 13 Nov 2022 16:39:55 -0600 Subject: Python 3.7+ cannot print unicode characters when output is redirected to file - is this a bug? In-Reply-To: References: Message-ID: On 11/13/22, Jessica Smith <12jessicasmith34 at gmail.com> wrote: > Consider the following code ran in Powershell or cmd.exe: > > $ python -c "print('?')" > ? > > $ python -c "print('?')" > test_file.txt > Traceback (most recent call last): > File "", line 1, in > File "C:\Program Files\Python38\lib\encodings\cp1252.py", line 19, in > encode > return codecs.charmap_encode(input,self.errors,encoding_table)[0] > UnicodeEncodeError: 'charmap' codec can't encode character '\u2514' in > position 0: character maps to If your applications and existing data files are compatible with using UTF-8, then in Windows 10+ you can modify the administrative regional settings in the control panel to force using UTF-8. In this case, GetACP() and GetOEMCP() will return CP_UTF8 (65001), and the reserved code page constants CP_ACP (0), CP_OEMCP (1), CP_MACCP (2), and CP_THREAD_ACP (3) will use CP_UTF8. You can override this on a per-application basis via the ActiveCodePage setting in the manifest: https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests#activecodepage In Windows 10, this setting only supports "UTF-8". In Windows 11, it also supports "legacy" to allow old applications to run on a system that's configured to use UTF-8. Setting an explicit locale is also supported in Windows 11, such as "en-US", with fallback to UTF-8 if the given locale has no legacy code page. Note that setting the system to use UTF-8 also affects the host process for console sessions (i.e. conhost.exe or openconsole.exe), since it defaults to using the OEM code page (UTF-8 in this case). Unfortunately, a legacy read from the console host does not support reading non-ASCII text as UTF-8. For example: >>> os.read(0, 6) SP?M b'SP\x00M\r\n' This is a trivial bug in the console host, which stems from the fact that UTF-8 is a multibyte encoding (1-4 bytes per code), but for some reason the console team at Microsoft still hasn't fixed it. You can use chcp.com to set the console's input and output code pages to something other than UTF-8 if you have to read non-ASCII input in a legacy console app. By default, this problem doesn't affect Python's sys.stdin, which internally uses wide-character ReadConsoleW() with the system's native text encoding, UTF-16LE. From nospam at dfs.com Sun Nov 13 16:28:39 2022 From: nospam at dfs.com (DFS) Date: Sun, 13 Nov 2022 16:28:39 -0500 Subject: In code, list.clear doesn't throw error - it's just ignored Message-ID: 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 From jon+usenet at unequivocal.eu Sun Nov 13 17:20:23 2022 From: jon+usenet at unequivocal.eu (Jon Ribbens) Date: Sun, 13 Nov 2022 22:20:23 -0000 (UTC) Subject: In code, list.clear doesn't throw error - it's just ignored References: Message-ID: 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) From nospam at dfs.com Sun Nov 13 18:12:33 2022 From: nospam at dfs.com (DFS) Date: Sun, 13 Nov 2022 18:12:33 -0500 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: Message-ID: 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! From jon+usenet at unequivocal.eu Sun Nov 13 19:31:39 2022 From: jon+usenet at unequivocal.eu (Jon Ribbens) Date: Mon, 14 Nov 2022 00:31:39 -0000 (UTC) Subject: In code, list.clear doesn't throw error - it's just ignored References: Message-ID: On 2022-11-13, 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? Because it's an expression, and you're allowed to execute expressions. From greg.ewing at canterbury.ac.nz Sun Nov 13 19:55:28 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Mon, 14 Nov 2022 13:55:28 +1300 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: Message-ID: On 14/11/22 1:31 pm, Jon Ribbens wrote: > On 2022-11-13, DFS wrote: >> But why is it allowed in the first place? > > Because it's an expression, and you're allowed to execute expressions. To put it a bit more clearly, you're allowed to evaluate an expression and ignore the result. -- Greg From rosuav at gmail.com Sun Nov 13 21:11:11 2022 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 14 Nov 2022 13:11:11 +1100 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: Message-ID: 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: >>> 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. ChrisA From python at mrabarnett.plus.com Sun Nov 13 21:13:34 2022 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 14 Nov 2022 02:13:34 +0000 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: Message-ID: <0b97e354-49a3-f7bb-a3bb-3f2f6024ae68@mrabarnett.plus.com> On 2022-11-14 00:55, Greg Ewing wrote: > On 14/11/22 1:31 pm, Jon Ribbens wrote: >> On 2022-11-13, DFS wrote: >>> But why is it allowed in the first place? >> >> Because it's an expression, and you're allowed to execute expressions. > > To put it a bit more clearly, you're allowed to evaluate > an expression and ignore the result. > But if it's an expression where it's expecting a statement and it's not a call, then it's probably a bug. From rosuav at gmail.com Sun Nov 13 21:22:31 2022 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 14 Nov 2022 13:22:31 +1100 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: <0b97e354-49a3-f7bb-a3bb-3f2f6024ae68@mrabarnett.plus.com> References: <0b97e354-49a3-f7bb-a3bb-3f2f6024ae68@mrabarnett.plus.com> Message-ID: On Mon, 14 Nov 2022 at 13:18, MRAB wrote: > > On 2022-11-14 00:55, Greg Ewing wrote: > > On 14/11/22 1:31 pm, Jon Ribbens wrote: > >> On 2022-11-13, DFS wrote: > >>> But why is it allowed in the first place? > >> > >> Because it's an expression, and you're allowed to execute expressions. > > > > To put it a bit more clearly, you're allowed to evaluate > > an expression and ignore the result. > > > But if it's an expression where it's expecting a statement and it's not > a call, then it's probably a bug. Maybe, but I'd be dubious of making it that simplistic. For instance, which of these is more likely to be useless? spam or ham() spam() or ham Syntactically, both of them are 'or' expressions, but one of them is almost certainly unnecessary, while the other is just an oddly-written conditional statement and most definitely useful. In any case, this is the job of linters, NOT the language itself. ChrisA From jon+usenet at unequivocal.eu Sun Nov 13 20:21:57 2022 From: jon+usenet at unequivocal.eu (Jon Ribbens) Date: Mon, 14 Nov 2022 01:21:57 -0000 (UTC) Subject: In code, list.clear doesn't throw error - it's just ignored References: Message-ID: On 2022-11-14, Greg Ewing wrote: > On 14/11/22 1:31 pm, Jon Ribbens wrote: >> On 2022-11-13, DFS wrote: >>> But why is it allowed in the first place? >> >> Because it's an expression, and you're allowed to execute expressions. > > To put it a bit more clearly, you're allowed to evaluate > an expression and ignore the result. ... because it may have side effects, and it's not possible to determine whether it will or not in advance. From nospam at dfs.com Sun Nov 13 22:23:09 2022 From: nospam at dfs.com (DFS) Date: Sun, 13 Nov 2022 22:23:09 -0500 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: Message-ID: 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 at 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. From knomenet at gmail.com Sun Nov 13 23:53:08 2022 From: knomenet at gmail.com (Michael Speer) Date: Sun, 13 Nov 2022 23:53:08 -0500 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: Message-ID: 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 at 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 > From greg.ewing at canterbury.ac.nz Mon Nov 14 00:12:23 2022 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Mon, 14 Nov 2022 18:12:23 +1300 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: <0b97e354-49a3-f7bb-a3bb-3f2f6024ae68@mrabarnett.plus.com> Message-ID: On 14/11/22 3:13 pm, MRAB wrote: > But if it's an expression where it's expecting a statement and it's not > a call, then it's probably a bug. The key word there is "probably". If there's any chance it could be not a bug, it can't be an error. At most it should be a warning, and that's what linters are for. I wouldn't like the core interpreter to be producing a bunch of warnings for things like this. -- Greg From rosuav at gmail.com Mon Nov 14 02:08:38 2022 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 14 Nov 2022 18:08:38 +1100 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: <0b97e354-49a3-f7bb-a3bb-3f2f6024ae68@mrabarnett.plus.com> Message-ID: On Mon, 14 Nov 2022 at 18:00, Greg Ewing wrote: > > On 14/11/22 3:13 pm, MRAB wrote: > > But if it's an expression where it's expecting a statement and it's not > > a call, then it's probably a bug. > > The key word there is "probably". If there's any chance it > could be not a bug, it can't be an error. At most it should > be a warning, and that's what linters are for. I wouldn't > like the core interpreter to be producing a bunch of warnings > for things like this. > Notably, linters can be taught about more complex idioms, like: try: raw_input except NameError: raw_input = input which is an easy way to make polyglot Py2/Py3 code that handles the presence/absence of a particular name. Or, similarly: try: os.sendfile except AttributeError: ... # cope with sendfile not being available When os.sendfile exists, it's a completely useless expression. When it doesn't, it's an error. But the difference between those two is crucial. ChrisA From PythonList at DancesWithMice.info Mon Nov 14 02:25:30 2022 From: PythonList at DancesWithMice.info (dn) Date: Mon, 14 Nov 2022 20:25:30 +1300 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: Message-ID: On 14/11/2022 12.12, 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! It looks 'right' because it is 'right'! However, compared with what was intended, it was 'wrong'! ? I really hate this d***umb machine, I wish that they would sell it. It never does quite what I want, but only what I tell it! ? Lifting some text from a recent PUG-meeting: ?Distinguishing functions and their names: Please remind yourself that is_odd is the name of a function, whereas is_odd() calls the function and could thus be considered a 'label' for the returned-value ? either approach could be used in different situations. ? In this case, the subject is a method, and accordingly has a slightly different flavor. Rather than a return-value, the impact is an effect within the scope and/or to the state of the object. However, not materially-different from the OP's question. It is assumed that there is no difficulty related to calling the function, eg len( x ). So, why would we use the function/method by name instead of its asking for its return-value? (please remember that a Python function is a "first class" object) The (above) Challenge to PUG-members was to use code which produces the Fibonacci Sequence, and out of the first 16 values, return the number of Fibonacci-values which are also odd-numbers. We started with straight-line code which mixed-up these various steps in the process. As the challenge continued, such tangling made it very difficult to enable any variations. To illustrate the SRP and DIP (Single Responsibility and Dependency Inversion Principles of SOLID Architecture), we refactored and refactored, ending-up with: values_counted = sm.sequence_select_and_project( fg.fibonacci_generator, is_odd, limit, ) sequence_select_and_project is a for-loop spanning two if-statements which count or break fibonacci_generator is self-explanatory (hopefully) is_odd returns boolean advice limit is 16 Note how the first two arguments are [generator-]function names, cf function-calls! Now for 'the magic' of a dependency-inverted plug-in architecture:- If the 16 is changed to 32, we'll be comfortable with the idea that twice as many values will be generated and considered. So, think about changing the generator to produce (say) prime numbers. Alternately, alter the program to count only values divisible by two (perhaps using "is_even" as function-name). By 'plugging-in' a different function-name, the above control-routine can be used with any suitably-lengthy sequence as its data-source, and/or selection-criteria function! Accordingly, using the name of a function can be as useful as using the result of a function-call - even if the latter is far more common. -- -- Regards, =dn From roel at roelschroeven.net Mon Nov 14 04:09:44 2022 From: roel at roelschroeven.net (Roel Schroeven) Date: Mon, 14 Nov 2022 10:09:44 +0100 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: Message-ID: <77f0cd80-5ff2-8b02-ab9f-9b65e2d679bc@roelschroeven.net> Op 14/11/2022 om 4:23 schreef DFS: > 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 >>>>> >>> 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. It's not invalid. In the REPL for example, it does something useful: >>> x = [1, 2, 3] >>> x.clear Others have shown instances where writing a method or function without calling it are useful in a script too. There are languages that handle this differently. Ruby, for example, calls the function/method even when you don't write the parens, if I'm not mistaken. Personally I don't like that; I much prefer Python's explicitness in making the difference between the value of a function and calling that function. Still, there's something to be said for warnings. I agree with others that such warnings are more the job for a linter than for the language. FWIW I've been bitten by this in C++ once. I wanted to write something like if (some_condition()) ??? foo(); But I forgot the parens after some_condition, so C++ evaluated the function pointer (which was non-NULL so evaluated is true in a boolean context) instead of the return value, and therefore foo() got called unconditionally. -- "Don't Panic." -- Douglas Adams, The Hitchhiker's Guide to the Galaxy From Karsten.Hilbert at gmx.net Mon Nov 14 05:46:14 2022 From: Karsten.Hilbert at gmx.net (Karsten Hilbert) Date: Mon, 14 Nov 2022 11:46:14 +0100 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: <0b97e354-49a3-f7bb-a3bb-3f2f6024ae68@mrabarnett.plus.com> References: <0b97e354-49a3-f7bb-a3bb-3f2f6024ae68@mrabarnett.plus.com> Message-ID: Am Mon, Nov 14, 2022 at 02:13:34AM +0000 schrieb MRAB: > But if it's an expression where it's expecting a statement and it's not a call, then > it's probably a bug. That "probably" makes it suitable for a linter, as was pointed out. Karsten -- GPG 40BE 5B0E C98E 1713 AFA6 5BC0 3BEA AC80 7D4F C89B From gweatherby at uchc.edu Mon Nov 14 06:35:26 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Mon, 14 Nov 2022 11:35:26 +0000 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: Message-ID: The terminal told you what x.clear was. The Python documentation tells you how to call it: https://docs.python.org/3/tutorial/datastructures.html list.clear() Remove all items from the list. Equivalent to del a[:]. An IDE (e.g. PyCharm) will try to autocomplete the parentheses and warn you if you don?t: ?Statement seems to have no effect and can be replaced with a function call to have effect? From: Python-list on behalf of DFS Date: Sunday, November 13, 2022 at 7:46 PM To: python-list at python.org Subject: In code, list.clear doesn't throw error - it's just ignored *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** 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 -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!jRrjG0fRo46VyY0jLfD1Z5C6tXDiphZy8zi2AqN_N5BB1_OwBe_wxmsBWmIVOFQDdZnvbRq1JNeGnPg$ From darkstone at o2online.de Mon Nov 14 07:31:32 2022 From: darkstone at o2online.de (darkstone at o2online.de) Date: Mon, 14 Nov 2022 12:31:32 +0000 Subject: =?utf-8?Q?Re:_Problems_with_IDLE_in_Windows_8.1_and_installer_x86_Version?= =?utf-8?Q?_3.10.8?= In-Reply-To: References: <202210311822.29VIMTpw130438@mail92c50.megamailservers.eu> <202211011649.2A1GnNrU115152@mail36c50.megamailservers.eu> <202211032129.2A3LTmtc065950@mail193c50.megamailservers.eu> <202211041414.2A4EE2xL017716@mail264c50.megamailservers.eu> <202211100003.2AA03LR5098382@mail266c50.megamailservers.eu> <59f3470c-fffb-4354-1712-67814f257e66@tompassin.net> <202211121242.2ACCgcuL102426@mail265c50.megamailservers.eu> <202211121650.2ACGokE8103881@mail193c50.megamailservers.eu> <1ffce7ef-829f-798f-cf11-e8e433989ee8@tompassin.net> <202211131348.2ADDmDWi100177@mail56c50.megamailservers.eu> <92a11c3d-120d-ba3a-fd84-7420c3dcb6e8@tompassin.net>, Message-ID: <202211141240.2AECeY30018401@mail92c50.megamailservers.eu> Dear list, >>So please check that you are running the right version of Python when >>you type "python". If i type ?python?, it is C:\>python -V Python 3.11.0 Von: Thomas Passin Gesendet: ?Sonntag?, ?13?. ?November? ?2022 ?16?:?18 An: darkstone at o2online.de On 11/13/2022 9:32 AM, Thomas Passin wrote: > When you ran "python -V", the current directory was the top-level Python > directory. So the Python version would automatically have been the same > as that directory's Python, that is, 3.11. > > When you ran the idlelib self test, you may have been in a different > directory, and so a different version of Python might possible have > been running. To illustrate this point, on my system: C:\Users\tom>python -V Python 3.9.9 but C:\Users\tom>py -V Python 3.10.4 With the "py" script, I can run 3.9x this way: py -3.9 -V Python 3.9.9 and also: C:\Users\tom>py -3.7 -V Python 3.7.9 So please check that you are running the right version of Python when you type "python". From stephen_tucker at sil.org Mon Nov 14 12:14:05 2022 From: stephen_tucker at sil.org (Stephen Tucker) Date: Mon, 14 Nov 2022 17:14:05 +0000 Subject: Are these good ideas? Message-ID: Hi, I have two related issues I'd like comments on. Issue 1 - Global Values Some years ago, I had a situation where (a) I could supply low-level functions that carry out tasks, (b) I needed those functions to communicate with each other, but (c) I had no access to the module that invoked my functions. In order to achieve this, I hit on the idea that I also supply a module that I describe as a "global values" module. This module ? (i) ? defines the values that the functions use to communicate with each other; (ii) ? is the subject of an import statement in each of my functions; (iii) ? initialises its values at the start of each run (since the import only carries out an actual import once per session); (iv) ? acts as a repository for the values thereafter. This solution works well. Given that I am not particularly concerned about efficiency, (1) Is this a reasonable way to achieve this goal? (2) Do you know of any better ways? Issue 2 - Passed Parameters I am now facing another situation where I am wanting to pass 6 or 7 parameters down through several layers of logic (function A calling function B calling ... ) and for results to be passed back. Having had the idea described above, I am considering using it again to save all the parameter-and-results passing. I see nothing wrong with doing that, but I may well be missing something! Comments, please! Stephen Tucker. From pbryan at anode.ca Mon Nov 14 12:30:13 2022 From: pbryan at anode.ca (Paul Bryan) Date: Mon, 14 Nov 2022 09:30:13 -0800 Subject: Are these good ideas? In-Reply-To: References: Message-ID: Seems like this is a use case for context managers and/or context variables: https://docs.python.org/3/library/contextlib.html https://docs.python.org/3/library/contextvars.html On Mon, 2022-11-14 at 17:14 +0000, Stephen Tucker wrote: > Hi, > > I have two related issues I'd like comments on. > > Issue 1 - Global Values > > Some years ago, I had a situation where > (a) I could supply low-level functions that carry out tasks, > (b) I needed those functions to communicate with each other, but > (c) I had no access to the module that invoked my functions. > > In order to achieve this, I hit on the idea that I also supply a > module > that I describe as a "global values" module. This module ? > (i) ? defines the values that the functions use to communicate with > each > other; > (ii) ? is the subject of an import statement in each of my functions; > (iii) ? initialises its values at the start of each run (since the > import > only carries out an actual import once per session); > (iv) ? acts as a repository for the values thereafter. > > This solution works well. > > Given that I am not particularly concerned about efficiency, > (1) Is this a reasonable way to achieve this goal? > (2) Do you know of any better ways? > > Issue 2 - Passed Parameters > > I am now facing another situation where I am wanting to pass 6 or 7 > parameters down through several layers of logic (function A calling > function B calling ... ) and for results to be passed back. > > Having had the idea described above, I am considering using it again > to > save all the parameter-and-results passing. > > I see nothing wrong with doing that, but I may well be missing > something! > > Comments, please! > > Stephen Tucker. From Karsten.Hilbert at gmx.net Mon Nov 14 12:39:03 2022 From: Karsten.Hilbert at gmx.net (Karsten Hilbert) Date: Mon, 14 Nov 2022 18:39:03 +0100 Subject: Are these good ideas? In-Reply-To: References: Message-ID: Am Mon, Nov 14, 2022 at 05:14:05PM +0000 schrieb Stephen Tucker: > Issue 2 - Passed Parameters > > I am now facing another situation where I am wanting to pass 6 or 7 > parameters down through several layers of logic (function A calling > function B calling ... ) and for results to be passed back. > > Having had the idea described above, I am considering using it again to > save all the parameter-and-results passing. > > I see nothing wrong with doing that, but I may well be missing something! Maybe pass and return a class ? Maybe even a data class ? Karsten -- GPG 40BE 5B0E C98E 1713 AFA6 5BC0 3BEA AC80 7D4F C89B From gweatherby at uchc.edu Mon Nov 14 12:42:45 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Mon, 14 Nov 2022 17:42:45 +0000 Subject: Are these good ideas? In-Reply-To: References: Message-ID: Issue 1. Depends very much on your operating system and application environment. Issue 2. I usually make myself a data class to pass around. Then when I figure out I forgot something, I just update the dataclass and the creator and consumer of it. @dataclass class CallParameter: first : int second: str etc. I use context specific names, not ?first? et. al. From: Python-list on behalf of Stephen Tucker Date: Monday, November 14, 2022 at 12:16 PM To: Python Subject: Are these good ideas? *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** Hi, I have two related issues I'd like comments on. Issue 1 - Global Values Some years ago, I had a situation where (a) I could supply low-level functions that carry out tasks, (b) I needed those functions to communicate with each other, but (c) I had no access to the module that invoked my functions. In order to achieve this, I hit on the idea that I also supply a module that I describe as a "global values" module. This module ? (i) ? defines the values that the functions use to communicate with each other; (ii) ? is the subject of an import statement in each of my functions; (iii) ? initialises its values at the start of each run (since the import only carries out an actual import once per session); (iv) ? acts as a repository for the values thereafter. This solution works well. Given that I am not particularly concerned about efficiency, (1) Is this a reasonable way to achieve this goal? (2) Do you know of any better ways? Issue 2 - Passed Parameters I am now facing another situation where I am wanting to pass 6 or 7 parameters down through several layers of logic (function A calling function B calling ... ) and for results to be passed back. Having had the idea described above, I am considering using it again to save all the parameter-and-results passing. I see nothing wrong with doing that, but I may well be missing something! Comments, please! Stephen Tucker. -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!hb_4MXkjG1NsyGoNsLJNDTOruPzfPWJKD-6vj0_2N1yqqtvz8oDZH3cT0EVkFbPTzSC19cAOgXlQdkDp7FZjwbyOjw$ From jon+usenet at unequivocal.eu Mon Nov 14 09:18:25 2022 From: jon+usenet at unequivocal.eu (Jon Ribbens) Date: Mon, 14 Nov 2022 14:18:25 -0000 (UTC) Subject: In code, list.clear doesn't throw error - it's just ignored References: Message-ID: On 2022-11-14, Stefan Ram wrote: > Jon Ribbens writes: >>"""Create an array and print its length""" >>array = [1, 2, 3] >>array.clear > > BTW: Above, there are /two/ expression statements > with no effect; the other one is > > """Create an array and print its length""" > > . Apparently, linters know this and will not create > a warning for such string literals. Not only do they know this, pylint will complain if you *don't* include that line, which is why I included it ;-) From jenkris at tutanota.com Mon Nov 14 13:59:14 2022 From: jenkris at tutanota.com (Jen Kris) Date: Mon, 14 Nov 2022 19:59:14 +0100 (CET) Subject: Debugging Python C extensions with GDB Message-ID: In September 2021, Victor Stinner wrote ?Debugging Python C extensions with GDB? (https://developers.redhat.com/articles/2021/09/08/debugging-python-c-extensions-gdb#getting_started_with_python_3_9).? My question is:? with Python 3.9+, can I debug into a C extension written in pure C and called from ctypes? -- that is not written using the C_API?? Thanks.? Jen From rosuav at gmail.com Mon Nov 14 14:14:02 2022 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 15 Nov 2022 06:14:02 +1100 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: Message-ID: On Tue, 15 Nov 2022 at 05:57, Stefan Ram wrote: > > Michael Speer writes: > >Python doesn't care what an expression returns. > > In my English, functions return values, > expression are being evaluated to a value. > The evaluation of a function yields or > produces a value. Expressions do not return, > because they are not functions. > Well, you can dispute the terminology all you like, but there's no real difference between function calls and other types of expression. They're all just expressions and they can be combined arbitrarily. ChrisA From axy at declassed.art Mon Nov 14 14:32:25 2022 From: axy at declassed.art (Axy) Date: Mon, 14 Nov 2022 19:32:25 +0000 Subject: Are these good ideas? In-Reply-To: References: Message-ID: <8e988948-4478-18a0-3b2a-02bcb2b315d3@declassed.art> On 14/11/2022 17:14, Stephen Tucker wrote: > Hi, > > I have two related issues I'd like comments on. > > Issue 1 - Global Values Your "global variables" module acts exactly as a singleton class. Funny, you could (and maybe you do) write in your functions import global_vars_module as self as the first step of refactoring. From personal experience, when I worked at work we used modules for globals as well, but over time such an approach looked more and more ugly and finally was rejected. > Issue 2 - Passed Parameters > > I am now facing another situation where I am wanting to pass 6 or 7 > parameters down through several layers of logic (function A calling > function B calling ... ) and for results to be passed back. Nothing fancy here, we used dicts for args and results. Axy. From list1 at tompassin.net Mon Nov 14 17:02:54 2022 From: list1 at tompassin.net (Thomas Passin) Date: Mon, 14 Nov 2022 17:02:54 -0500 Subject: Are these good ideas? In-Reply-To: References: Message-ID: For parameter passing like your #2, I have packaged them into a dictionary and passed that around. It was easy enough, and worked well. The only potential problem is in documenting the key/value pairs the dictionary is supposed to contain. You had better make sure it's made clear somewhere, preferable where it is consumed. For "global" values, sure, put them in a module and import them as needed. Just make sure that none of your code is going to mutate those values, or you will end up with mass confusion. I suppose you could make them be properties that have no setters, if you want to go to that trouble. On 11/14/2022 12:14 PM, Stephen Tucker wrote: > Hi, > > I have two related issues I'd like comments on. > > Issue 1 - Global Values > > Some years ago, I had a situation where > (a) I could supply low-level functions that carry out tasks, > (b) I needed those functions to communicate with each other, but > (c) I had no access to the module that invoked my functions. > > In order to achieve this, I hit on the idea that I also supply a module > that I describe as a "global values" module. This module ? > (i) ? defines the values that the functions use to communicate with each > other; > (ii) ? is the subject of an import statement in each of my functions; > (iii) ? initialises its values at the start of each run (since the import > only carries out an actual import once per session); > (iv) ? acts as a repository for the values thereafter. > > This solution works well. > > Given that I am not particularly concerned about efficiency, > (1) Is this a reasonable way to achieve this goal? > (2) Do you know of any better ways? > > Issue 2 - Passed Parameters > > I am now facing another situation where I am wanting to pass 6 or 7 > parameters down through several layers of logic (function A calling > function B calling ... ) and for results to be passed back. > > Having had the idea described above, I am considering using it again to > save all the parameter-and-results passing. > > I see nothing wrong with doing that, but I may well be missing something! > > Comments, please! > > Stephen Tucker. From cs at cskk.id.au Mon Nov 14 17:11:10 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Tue, 15 Nov 2022 09:11:10 +1100 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: Message-ID: On 13Nov2022 22:23, DFS wrote: >On 11/13/2022 9:11 PM, Chris Angelico wrote: >> [ ... `x.clear` ... ] >>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. It's a valid expression. It looks to your eye like a no-op, but at actually Python _looks up the name `clear`_ on an object (which happens to be a `list`). That is a real thing to do, and can have side effects. While most of the examples here have been in the REPL where running an expression with no side effects is itself useful, because the REPL can print the result, I've personally got some real world code with a bare `some_object.attribute` line. I'm not sure where, or I'd show it, but I _think_ it was probably prepriming a cached object property. There might have been a more expressive way to do that, but it was a bare attribute lookup with side effects, _used for those side effects_. >This is an easy check for the interpreter to make. It really isn't, given that (a) this isn't known by the interpreter to be a `list` until runtime and (b) that would need embedding special knowledge that looking up an attribute on a `list` has no side effects (versus some other things, where it is not the case). Linters are the best place for this: they warn about probably-mistakes idioms like this, and can have slightly deep knowledge of the code's semantics sometimes. >If I submit a suggestion to python-list at python.org will it just show >up here? Or do the actual Python devs intercept it? Nah, it'll go through. Cheers, Cameron Simpson From barry at barrys-emacs.org Mon Nov 14 17:32:35 2022 From: barry at barrys-emacs.org (Barry) Date: Mon, 14 Nov 2022 22:32:35 +0000 Subject: Debugging Python C extensions with GDB In-Reply-To: References: Message-ID: > On 14 Nov 2022, at 19:10, Jen Kris via Python-list wrote: > > ?In September 2021, Victor Stinner wrote ?Debugging Python C extensions with GDB? (https://developers.redhat.com/articles/2021/09/08/debugging-python-c-extensions-gdb#getting_started_with_python_3_9). > > My question is: with Python 3.9+, can I debug into a C extension written in pure C and called from ctypes -- that is not written using the C_API? Yes. Just put a breakpoint on the function in the c library that you want to debug. You can set the breakpoint before a .so is loaded. Barry > > Thanks. > > Jen > > > > -- > https://mail.python.org/mailman/listinfo/python-list From barry at barrys-emacs.org Mon Nov 14 17:36:43 2022 From: barry at barrys-emacs.org (Barry) Date: Mon, 14 Nov 2022 22:36:43 +0000 Subject: Are these good ideas? In-Reply-To: References: Message-ID: <1726FA55-0D24-45DD-89C5-12E792626931@barrys-emacs.org> > On 14 Nov 2022, at 22:06, Thomas Passin wrote: > > ?For parameter passing like your #2, I have packaged them into a dictionary and passed that around. It was easy enough, and worked well. > I used to use a dict but having been burnt with issues now create a class. With a class you can add accessor methods that allow you to run debug code as values are changed. Also you can check that values being set are spelt correctly, have reasonable values etc. Barry > The only potential problem is in documenting the key/value pairs the dictionary is supposed to contain. You had better make sure it's made clear somewhere, preferable where it is consumed. > > For "global" values, sure, put them in a module and import them as needed. Just make sure that none of your code is going to mutate those values, or you will end up with mass confusion. I suppose you could make them be properties that have no setters, if you want to go to that trouble. > >> On 11/14/2022 12:14 PM, Stephen Tucker wrote: >> Hi, >> I have two related issues I'd like comments on. >> Issue 1 - Global Values >> Some years ago, I had a situation where >> (a) I could supply low-level functions that carry out tasks, >> (b) I needed those functions to communicate with each other, but >> (c) I had no access to the module that invoked my functions. >> In order to achieve this, I hit on the idea that I also supply a module >> that I describe as a "global values" module. This module ? >> (i) ? defines the values that the functions use to communicate with each >> other; >> (ii) ? is the subject of an import statement in each of my functions; >> (iii) ? initialises its values at the start of each run (since the import >> only carries out an actual import once per session); >> (iv) ? acts as a repository for the values thereafter. >> This solution works well. >> Given that I am not particularly concerned about efficiency, >> (1) Is this a reasonable way to achieve this goal? >> (2) Do you know of any better ways? >> Issue 2 - Passed Parameters >> I am now facing another situation where I am wanting to pass 6 or 7 >> parameters down through several layers of logic (function A calling >> function B calling ... ) and for results to be passed back. >> Having had the idea described above, I am considering using it again to >> save all the parameter-and-results passing. >> I see nothing wrong with doing that, but I may well be missing something! >> Comments, please! >> Stephen Tucker. > > -- > https://mail.python.org/mailman/listinfo/python-list From rosuav at gmail.com Mon Nov 14 17:46:00 2022 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 15 Nov 2022 09:46:00 +1100 Subject: Are these good ideas? In-Reply-To: <1726FA55-0D24-45DD-89C5-12E792626931@barrys-emacs.org> References: <1726FA55-0D24-45DD-89C5-12E792626931@barrys-emacs.org> Message-ID: On Tue, 15 Nov 2022 at 09:38, Barry wrote: > > > > > On 14 Nov 2022, at 22:06, Thomas Passin wrote: > > > > ?For parameter passing like your #2, I have packaged them into a dictionary and passed that around. It was easy enough, and worked well. > > > I used to use a dict but having been burnt with issues now create a class. > > With a class you can add accessor methods that allow you to run debug code as values are changed. Also you can check that values being set are spelt correctly, have reasonable values etc. > TBH you could add accessor methods to a dict just as easily ChrisA From barry at barrys-emacs.org Mon Nov 14 17:53:14 2022 From: barry at barrys-emacs.org (Barry) Date: Mon, 14 Nov 2022 22:53:14 +0000 Subject: Are these good ideas? In-Reply-To: References: Message-ID: <5E0C85A2-5F3B-46F6-BB15-81CA102797B2@barrys-emacs.org> > On 14 Nov 2022, at 22:49, Chris Angelico wrote: > > ?On Tue, 15 Nov 2022 at 09:38, Barry wrote: >> >> >> >>>> On 14 Nov 2022, at 22:06, Thomas Passin wrote: >>> >>> ?For parameter passing like your #2, I have packaged them into a dictionary and passed that around. It was easy enough, and worked well. >>> >> I used to use a dict but having been burnt with issues now create a class. >> >> With a class you can add accessor methods that allow you to run debug code as values are changed. Also you can check that values being set are spelt correctly, have reasonable values etc. >> > > TBH you could add accessor methods to a dict just as easily Its the dict interface that we found allowed for API abuse and lead to hard to fix bugs. Barry > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list From list1 at tompassin.net Mon Nov 14 18:39:05 2022 From: list1 at tompassin.net (Thomas Passin) Date: Mon, 14 Nov 2022 18:39:05 -0500 Subject: Are these good ideas? In-Reply-To: <1726FA55-0D24-45DD-89C5-12E792626931@barrys-emacs.org> References: <1726FA55-0D24-45DD-89C5-12E792626931@barrys-emacs.org> Message-ID: <22dd6df0-1008-9036-42ff-519b6024a5fb@tompassin.net> On 11/14/2022 5:36 PM, Barry wrote: > > >> On 14 Nov 2022, at 22:06, Thomas Passin wrote: >> >> ?For parameter passing like your #2, I have packaged them into a dictionary and passed that around. It was easy enough, and worked well. >> > I used to use a dict but having been burnt with issues now create a class. > > With a class you can add accessor methods that allow you to run debug code as values are changed. Also you can check that values being set are spelt correctly, have reasonable values etc. > > Barry Of course, it all depends on how you are going to use the parameters, whether you plan to mutate some of them in place, etc. Mutating some of the input parameters can be useful, but also can lead to bugs that are harder to track down. For simple cases, dicts will probably be fine. Otherwise, classes or data classes may be better, as you suggest. >> The only potential problem is in documenting the key/value pairs the dictionary is supposed to contain. You had better make sure it's made clear somewhere, preferable where it is consumed. >> >> For "global" values, sure, put them in a module and import them as needed. Just make sure that none of your code is going to mutate those values, or you will end up with mass confusion. I suppose you could make them be properties that have no setters, if you want to go to that trouble. >> >>> On 11/14/2022 12:14 PM, Stephen Tucker wrote: >>> Hi, >>> I have two related issues I'd like comments on. >>> Issue 1 - Global Values >>> Some years ago, I had a situation where >>> (a) I could supply low-level functions that carry out tasks, >>> (b) I needed those functions to communicate with each other, but >>> (c) I had no access to the module that invoked my functions. >>> In order to achieve this, I hit on the idea that I also supply a module >>> that I describe as a "global values" module. This module ? >>> (i) ? defines the values that the functions use to communicate with each >>> other; >>> (ii) ? is the subject of an import statement in each of my functions; >>> (iii) ? initialises its values at the start of each run (since the import >>> only carries out an actual import once per session); >>> (iv) ? acts as a repository for the values thereafter. >>> This solution works well. >>> Given that I am not particularly concerned about efficiency, >>> (1) Is this a reasonable way to achieve this goal? >>> (2) Do you know of any better ways? >>> Issue 2 - Passed Parameters >>> I am now facing another situation where I am wanting to pass 6 or 7 >>> parameters down through several layers of logic (function A calling >>> function B calling ... ) and for results to be passed back. >>> Having had the idea described above, I am considering using it again to >>> save all the parameter-and-results passing. >>> I see nothing wrong with doing that, but I may well be missing something! >>> Comments, please! >>> Stephen Tucker. >> >> -- >> https://mail.python.org/mailman/listinfo/python-list > From jenkris at tutanota.com Mon Nov 14 18:44:28 2022 From: jenkris at tutanota.com (Jen Kris) Date: Tue, 15 Nov 2022 00:44:28 +0100 (CET) Subject: Debugging Python C extensions with GDB In-Reply-To: References: Message-ID: Thanks for your reply.? Victor's article didn't mention ctypes extensions, so I wanted to post a question before I build from source.? Nov 14, 2022, 14:32 by barry at barrys-emacs.org: > > >> On 14 Nov 2022, at 19:10, Jen Kris via Python-list wrote: >> >> ?In September 2021, Victor Stinner wrote ?Debugging Python C extensions with GDB? (https://developers.redhat.com/articles/2021/09/08/debugging-python-c-extensions-gdb#getting_started_with_python_3_9). >> >> My question is: with Python 3.9+, can I debug into a C extension written in pure C and called from ctypes -- that is not written using the C_API? >> > > Yes. > > Just put a breakpoint on the function in the c library that you want to debug. > You can set the breakpoint before a .so is loaded. > > Barry > >> >> Thanks. >> >> Jen >> >> >> >> -- >> https://mail.python.org/mailman/listinfo/python-list >> From wlfraed at ix.netcom.com Mon Nov 14 19:15:22 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 14 Nov 2022 19:15:22 -0500 Subject: In code, list.clear doesn't throw error - it's just ignored References: Message-ID: <8bm5nhlvh5tcqk0n75a9fuuplv76q90u7b@4ax.com> On Tue, 15 Nov 2022 09:11:10 +1100, Cameron Simpson declaimed the following: >On 13Nov2022 22:23, DFS wrote: >>This is an easy check for the interpreter to make. > >It really isn't, given that (a) this isn't known by the interpreter to >be a `list` until runtime and (b) that would need embedding special >knowledge that looking up an attribute on a `list` has no side effects >(versus some other things, where it is not the case). > There is also the minor facet that "x.clear" can be bound to a different name... >>> x = [1, 2, 3.145926536, "Pie"] >>> clearx = x.clear >>> x [1, 2, 3.145926536, 'Pie'] >>> clearx() >>> x [] >>> -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From cs at cskk.id.au Mon Nov 14 21:33:40 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Tue, 15 Nov 2022 13:33:40 +1100 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: <8bm5nhlvh5tcqk0n75a9fuuplv76q90u7b@4ax.com> References: <8bm5nhlvh5tcqk0n75a9fuuplv76q90u7b@4ax.com> Message-ID: On 14Nov2022 19:15, Dennis Lee Bieber wrote: > There is also the minor facet that "x.clear" can be bound to a >different name... > >>>> x = [1, 2, 3.145926536, "Pie"] >>>> clearx = x.clear >>>> x >[1, 2, 3.145926536, 'Pie'] >>>> clearx() >>>> x >[] >>>> I think the OP would take the stance that this: clearx = x.clear is more valid than: x.clear which discards the return value of the expression. Cheers, Cameron Simpson From drsalists at gmail.com Mon Nov 14 23:36:47 2022 From: drsalists at gmail.com (Dan Stromberg) Date: Mon, 14 Nov 2022 20:36:47 -0800 Subject: Are these good ideas? In-Reply-To: <8e988948-4478-18a0-3b2a-02bcb2b315d3@declassed.art> References: <8e988948-4478-18a0-3b2a-02bcb2b315d3@declassed.art> Message-ID: On Mon, Nov 14, 2022 at 11:33 AM Axy via Python-list wrote: > On 14/11/2022 17:14, Stephen Tucker wrote: > > Hi, > > > > I have two related issues I'd like comments on. > > > > Issue 1 - Global Values > > Your "global variables" module acts exactly as a singleton class. > Which is apparently a design pattern that some now believe is regrettable. It's something I've done before too, but it's pretty much shared, mutable state, which isn't great for functional programming or for parallelism. From axy at declassed.art Tue Nov 15 00:16:02 2022 From: axy at declassed.art (Axy) Date: Tue, 15 Nov 2022 05:16:02 +0000 Subject: Are these good ideas? In-Reply-To: References: <8e988948-4478-18a0-3b2a-02bcb2b315d3@declassed.art> Message-ID: <8e3d2d0e-80f2-dff1-33e6-7fd67e5024a3@declassed.art> On 15/11/2022 04:36, Dan Stromberg wrote: > > On Mon, Nov 14, 2022 at 11:33 AM Axy via Python-list > wrote: > > On 14/11/2022 17:14, Stephen Tucker wrote: > > Hi, > > > > I have two related issues I'd like comments on. > > > > Issue 1 - Global Values > > Your "global variables" module acts exactly as a singleton class. > > > Which is apparently a design pattern that some now believe is regrettable. Exactly. I dislike it too and always avoid. However, it could be a good starting point. Stepping directly into class-based approach would raise the same question: where to place global instance of that class. Gradual refactoring might have greater side effect of better overall design where many issues simply vanished by themselves. Maybe, (c) will change in favor of well-designed classes, who knows? Dropping singleton code is not a difficult task. Axy. From avi.e.gross at gmail.com Tue Nov 15 00:45:17 2022 From: avi.e.gross at gmail.com (avi.e.gross at gmail.com) Date: Tue, 15 Nov 2022 00:45:17 -0500 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: <8bm5nhlvh5tcqk0n75a9fuuplv76q90u7b@4ax.com> Message-ID: <001a01d8f8b5$717bfdf0$5473f9d0$@gmail.com> Cameron, What would be the meaning of an ordering relation determining what is MORE VALID? As has been pointed out, not only are some uses that look odd sometimes valid, but perhaps even can be used in ways you simply may not see, such as side effects. Some examples ranging from poor to horrible are mentioned below. In some languages, trying to access a variable that is not properly existing or initialized, can generate an error, as an example, which may cause the current function to terminate if not caught and jump up the call chain till an error handler is found. Code like: 1/0 May seem meaningless as the result is not saved, but may trigger a divide by zero error. Is it an error to write code like: If x.clear: pass I suspect it is possible to write quite weird code that might pass most linters but that does nothing useful and also to write code that is useful but might be disparaged by many interpreters or linters. My example above is a fairly common code pattern while code is being written as a sort of reminder to perhaps come back later and flesh it out properly, or remove it if it is no longer applicable. If so, it would be reasonable for it to be challenged and also to ignore such warnings until later when either it is gone, or the code hint should be gone. There are many cases where short-circuit evaluation means code is not run such as "True || x" that is less obvious but equally bypassed if you set a variable to True and do not change it and use it instead of True above. But is it an error? What if again, my later goal is to add code that may change the Truth value. As it is, the statement is not evaluated. But it may be set up as a placeholder to enhance later, perhaps long after, or retain some flexibility. Insisting it be removed might be too harsh while a warning might be reasonable. Yet again, it is not always an error to not use something like declaring a variable you might need or importing a module you never use. Code is chock full of such things in mid-stream. And you can deliberately ignore some things without it being a mistake as in: ( _, mean, _) = minMeanMax(args) Sure, it may be overkill to call a function that returns three things then ignore two of them. So what? What if instead of "_" I used real variable names like min and max? Should I get error messages that two variable are set up with values but never again used? Or consider what I sometimes do when I write code that someone else will use and to test it I must use something like a different filename/path on my machine than they do on theirs. I might write code like # Comment out one or more of the below so only one exists: Place = "whatever" Place = "Some other place" Clearly if I am using the second one, I can comment the first out OR I can leave it alone and at minor expenses let the variable be unconditionally reset to the second value. Is it a bug or a feature? I could go on with other examples including some more subtle ones like declaring a variable name just to mask another variable from being accessible from a higher level and perhaps prevent the interpreter or compiler optimizing it away by using it in the meaningless way this discussion began with as it has been accessed once. One person's bug can be another person's feature. And clearly, as has been mentioned, there MAY be subtle side effects like invoking your custom setter or dunder method which also does logging or increments a count. There is a spectrum between being overly permissive and overly strict. This case almost amuses me because of the way that many a REPL works so something run directly in a console will take an expression like "varname" and PRINT the current value to the screen. If the same code is run from a file, or from inside some function, it does nothing useful and you need something like "print(varname)" instead. People often cut and paste such snippets of code and in one context they did something and in another, it seems meaningless and possibly an error. -----Original Message----- From: Python-list On Behalf Of Cameron Simpson Sent: Monday, November 14, 2022 9:34 PM To: python-list at python.org Subject: Re: In code, list.clear doesn't throw error - it's just ignored On 14Nov2022 19:15, Dennis Lee Bieber wrote: > There is also the minor facet that "x.clear" can be bound to a >different name... > >>>> x = [1, 2, 3.145926536, "Pie"] >>>> clearx = x.clear >>>> x >[1, 2, 3.145926536, 'Pie'] >>>> clearx() >>>> x >[] >>>> I think the OP would take the stance that this: clearx = x.clear is more valid than: x.clear which discards the return value of the expression. Cheers, Cameron Simpson -- https://mail.python.org/mailman/listinfo/python-list From cs at cskk.id.au Tue Nov 15 04:13:04 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Tue, 15 Nov 2022 20:13:04 +1100 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: <001a01d8f8b5$717bfdf0$5473f9d0$@gmail.com> References: <001a01d8f8b5$717bfdf0$5473f9d0$@gmail.com> Message-ID: On 15Nov2022 00:45, avi.e.gross at gmail.com wrote: >What would be the meaning of an ordering relation determining what is >MORE VALID? Are you asking what criterion would rate: clearx = x.clear as "more" valid than: x.clear on its own? I don't want to speak for the OP, but I'd think the OP's issue is that the bare `x.clear` is evaluated but not stored in a variable. As a metric, we might gather various descriptive statements we could make about these statements. They'd perhaps include "is legal Python code", "is pretty simple". The former line could include "saves the expression value in a variable for later use" and the latter could not. That's a comparison test you could use for ordering. My own opinion is that a bare: x.clear is legal and valid for all the example use cases already mentioned, but an entirely valid target for complaint by a linter, whose task is to point out dodgy looking stuff for review by the author. Cheers, Cameron Simpson From barry at barrys-emacs.org Tue Nov 15 16:50:43 2022 From: barry at barrys-emacs.org (Barry) Date: Tue, 15 Nov 2022 21:50:43 +0000 Subject: Debugging Python C extensions with GDB In-Reply-To: References: Message-ID: <95B658EC-902E-4382-A69B-26C33E8E9F66@barrys-emacs.org> > On 14 Nov 2022, at 23:44, Jen Kris wrote: > > ? > Thanks for your reply. Victor's article didn't mention ctypes extensions, so I wanted to post a question before I build from source. Gdb works on any program its not special to python. Victor is only talking about a specific use of gdb for python c extensions. Barry > > > Nov 14, 2022, 14:32 by barry at barrys-emacs.org: > > On 14 Nov 2022, at 19:10, Jen Kris via Python-list wrote: > > ?In September 2021, Victor Stinner wrote ?Debugging Python C extensions with GDB? (https://developers.redhat.com/articles/2021/09/08/debugging-python-c-extensions-gdb#getting_started_with_python_3_9). > > My question is: with Python 3.9+, can I debug into a C extension written in pure C and called from ctypes -- that is not written using the C_API? > > Yes. > > Just put a breakpoint on the function in the c library that you want to debug. > You can set the breakpoint before a .so is loaded. > > Barry > > Thanks. > > Jen > > > > -- > https://mail.python.org/mailman/listinfo/python-list > From avi.e.gross at gmail.com Tue Nov 15 18:10:28 2022 From: avi.e.gross at gmail.com (avi.e.gross at gmail.com) Date: Tue, 15 Nov 2022 18:10:28 -0500 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: <001a01d8f8b5$717bfdf0$5473f9d0$@gmail.com> Message-ID: <007c01d8f947$73ffae40$5bff0ac0$@gmail.com> That is clear, Cameron, but on my python interpreter values evaluated on the command line ARE saved: >>> numb = 5 >>> 5 + numb 10 >>> numb 5 >>> _ + _ + 1 11 >>> _ * 2 22 >>> The point is that a dummy variable of _ is assigned and re-assigned at each step and there can be a valid, if not very useful, reason to evaluating it and storing a result. If the darn thing is a very long name like alpha.beta.gamma.delta.epsilon then code that uses it repeatedly in the very next line can be much simpler by using _ repeatedly and perhaps more efficient. Consider: negsq = _ * -_ versus negsq = alpha.beta.gamma.delta.epsilon * - alpha.beta.gamma.delta.epsilon So does your linter now need to look ahead and see if "_" is used properly in the next line? Note it can also be used on the LHS where it means something else. Still, I grant generally a naked evaluation is generally an error. LOL! -----Original Message----- From: Python-list On Behalf Of Cameron Simpson Sent: Tuesday, November 15, 2022 4:13 AM To: python-list at python.org Subject: Re: In code, list.clear doesn't throw error - it's just ignored On 15Nov2022 00:45, avi.e.gross at gmail.com wrote: >What would be the meaning of an ordering relation determining what is >MORE VALID? Are you asking what criterion would rate: clearx = x.clear as "more" valid than: x.clear on its own? I don't want to speak for the OP, but I'd think the OP's issue is that the bare `x.clear` is evaluated but not stored in a variable. As a metric, we might gather various descriptive statements we could make about these statements. They'd perhaps include "is legal Python code", "is pretty simple". The former line could include "saves the expression value in a variable for later use" and the latter could not. That's a comparison test you could use for ordering. My own opinion is that a bare: x.clear is legal and valid for all the example use cases already mentioned, but an entirely valid target for complaint by a linter, whose task is to point out dodgy looking stuff for review by the author. Cheers, Cameron Simpson -- https://mail.python.org/mailman/listinfo/python-list From rosuav at gmail.com Tue Nov 15 18:15:32 2022 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 16 Nov 2022 10:15:32 +1100 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: <007c01d8f947$73ffae40$5bff0ac0$@gmail.com> References: <001a01d8f8b5$717bfdf0$5473f9d0$@gmail.com> <007c01d8f947$73ffae40$5bff0ac0$@gmail.com> Message-ID: On Wed, 16 Nov 2022 at 10:11, wrote: > > That is clear, Cameron, but on my python interpreter values evaluated on the > command line ARE saved: > > >>> numb = 5 > >>> 5 + numb > 10 > >>> numb > 5 > >>> _ + _ + 1 > 11 That's a REPL feature. ChrisA From avi.e.gross at gmail.com Tue Nov 15 19:10:23 2022 From: avi.e.gross at gmail.com (avi.e.gross at gmail.com) Date: Tue, 15 Nov 2022 19:10:23 -0500 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: <001a01d8f8b5$717bfdf0$5473f9d0$@gmail.com> <007c01d8f947$73ffae40$5bff0ac0$@gmail.com> Message-ID: <008f01d8f94f$d26ef7d0$774ce770$@gmail.com> Yes, Chris, that is a REPL feature and one that people may use interactively. As you note, it does not work inside something like a function which the REPL is not trying to evaluate and print. So clearly my supposed use would not make much sense in such code. -----Original Message----- From: Python-list On Behalf Of Chris Angelico Sent: Tuesday, November 15, 2022 6:16 PM To: python-list at python.org Subject: Re: In code, list.clear doesn't throw error - it's just ignored On Wed, 16 Nov 2022 at 10:11, wrote: > > That is clear, Cameron, but on my python interpreter values evaluated > on the command line ARE saved: > > >>> numb = 5 > >>> 5 + numb > 10 > >>> numb > 5 > >>> _ + _ + 1 > 11 That's a REPL feature. ChrisA -- https://mail.python.org/mailman/listinfo/python-list From ismaelharunid at gmail.com Tue Nov 15 22:58:04 2022 From: ismaelharunid at gmail.com (Ismael Harun) Date: Tue, 15 Nov 2022 19:58:04 -0800 (PST) Subject: potential feature "Yield in " Message-ID: <3e3bd28a-dda8-40a3-ab98-5f17c1c70691n@googlegroups.com> This is about a feature suggestion regarding having the ability to have parallel generators. Currently you can have generators and iterators that can yield a single value. or a collection of values (still a single value). But what if you could yield to multiple objects. In a sense build multiple generators but without having to set these up as return objects. The main concept is having a way to push values to multiple iterable objects from the same loop or code. We have the ability to zip multable iterables for use in parallel. Why not the reverse? As in create multiple generators in parallel. It's just an idea, and I haven't thought it through thoroughly nut I wanted to see if anyone had thoughts, critics or feedback. It would require not only a parser change, but also a new type which I am calling a Collector in my example. A class that has a method used to receive new items. Such a thing could be asynchronous. . Something like: ``` def split_values(values, *collectors): for i in values: for n, c in enumerate(collectors, 1): yield i**n in c class MyCollector(list, Collector): def __receive__(self, value): yield value collector0 = MyCollector() collector1 = MyCollector() split_values(range(1,6), collector0, collector1) for i in collector0: print(i) for i in collector1: print(i) ``` Which would result in output: ``` 1 2 3 4 5 1 4 9 16 25 ``` From jfong at ms4.hinet.net Wed Nov 16 01:52:07 2022 From: jfong at ms4.hinet.net (Jach Feng) Date: Tue, 15 Nov 2022 22:52:07 -0800 (PST) Subject: Importlib behaves differently when importing pyd file Message-ID: <6d86c0bd-0832-4279-bad8-f049951454b9n@googlegroups.com> My working directory d:\Works\Python\ has a package 'fitz' looks like this: ....fitz\ ........__init__.py ........fitz.py ........utils.py ........_fitz.pyd There is a statement in fitz.py: ....return importlib.import_module('fitz._fitz') It works fine under Python 3.4 interpreter: >>> import fitz >>> But under Python 3.8 I get an exception: >>> import fitz Traceback(... ... ... ImportError: DLL load failed while importing _fitz >>> I work under Windows7 64bit with Python 32bit. Can anyone help? --Jach From dieter at handshake.de Wed Nov 16 12:11:52 2022 From: dieter at handshake.de (Dieter Maurer) Date: Wed, 16 Nov 2022 18:11:52 +0100 Subject: Importlib behaves differently when importing pyd file In-Reply-To: <6d86c0bd-0832-4279-bad8-f049951454b9n@googlegroups.com> References: <6d86c0bd-0832-4279-bad8-f049951454b9n@googlegroups.com> Message-ID: <25461.6616.640478.596683@ixdm.fritz.box> Jach Feng wrote at 2022-11-15 22:52 -0800: >My working directory d:\Works\Python\ has a package 'fitz' looks like this: > >....fitz\ >........__init__.py >........fitz.py >........utils.py >........_fitz.pyd > >There is a statement in fitz.py: >....return importlib.import_module('fitz._fitz') > >It works fine under Python 3.4 interpreter: >>>> import fitz >>>> > >But under Python 3.8 I get an exception: >>>> import fitz >Traceback(... >... >... >ImportError: DLL load failed while importing _fitz >>>> The Python C-API is Python version dependent. Your `_fitz.pyd` may need to be recreated for Python 3.8. From jfong at ms4.hinet.net Wed Nov 16 21:58:58 2022 From: jfong at ms4.hinet.net (Jach Feng) Date: Wed, 16 Nov 2022 18:58:58 -0800 (PST) Subject: Importlib behaves differently when importing pyd file In-Reply-To: References: <25461.6616.640478.596683@ixdm.fritz.box> <6d86c0bd-0832-4279-bad8-f049951454b9n@googlegroups.com> Message-ID: <022a4b1a-696a-4c54-89b1-d36748137803n@googlegroups.com> Dieter Maurer ? 2022?11?17? ?????1:12:20 [UTC+8] ?????? > Jach Feng wrote at 2022-11-15 22:52 -0800: > >My working directory d:\Works\Python\ has a package 'fitz' looks like this: > > > >....fitz\ > >........__init__.py > >........fitz.py > >........utils.py > >........_fitz.pyd > > > >There is a statement in fitz.py: > >....return importlib.import_module('fitz._fitz') > > > >It works fine under Python 3.4 interpreter: > >>>> import fitz > >>>> > > > >But under Python 3.8 I get an exception: > >>>> import fitz > >Traceback(... > >... > >... > >ImportError: DLL load failed while importing _fitz > >>>> > The Python C-API is Python version dependent. > Your `_fitz.pyd` may need to be recreated for Python 3.8. It seems that I have to install pymupdf to use fitz. Thank you. From toby at tobiah.org Fri Nov 18 10:19:42 2022 From: toby at tobiah.org (Tobiah) Date: Fri, 18 Nov 2022 07:19:42 -0800 Subject: Passing information between modules References: Message-ID: On 11/18/22 02: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 ] Kind of seems like a code smell. I think you would normally just inject the dependencies like: module_b.do_thing("Hi there!") If you really want to have a module-global space, you could just create a module globals.py, and import that in every module that needs to share globals. You can just do globals.message = "Hi there!" and from another module do print globals.message. From list1 at tompassin.net Fri Nov 18 14:24:32 2022 From: list1 at tompassin.net (Thomas Passin) Date: Fri, 18 Nov 2022 14:24:32 -0500 Subject: Passing information between modules In-Reply-To: References: Message-ID: <65d1c246-bc31-4e60-8333-8be63bd58391@tompassin.net> On 11/18/2022 10:19 AM, Tobiah wrote: > On 11/18/22 02: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 ] > > Kind of seems like a code smell.? I think you would normally > just inject the dependencies like: > > ????module_b.do_thing("Hi there!") > > If you really want to have a module-global space, > you could just create a module globals.py, and > import that in every module that needs to share globals. > You can just do globals.message = "Hi there!" and > from another module do print globals.message. The module can even create the message or variable dynamically. I have one that, when it is loaded, asks git for the branch and changeset hash the code's working directory is using. This module is imported by others that use the branch and changeset data in one way or another. From axy at declassed.art Fri Nov 18 14:28:24 2022 From: axy at declassed.art (Axy) Date: Fri, 18 Nov 2022 19:28:24 +0000 Subject: Passing information between modules In-Reply-To: References: Message-ID: On 18/11/2022 10: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 ] This idea has a couple of flaws so can be regarded as bad. However, if nothing else works (including suggested globals.py module), then os.environ could be a better way. Axy. From PythonList at DancesWithMice.info Sat Nov 19 13:09:18 2022 From: PythonList at DancesWithMice.info (dn) Date: Sun, 20 Nov 2022 07:09:18 +1300 Subject: Help Merging Of Separate Python Codes In-Reply-To: References: Message-ID: <71279a62-2764-8b8e-a451-7bb18b9971da@DancesWithMice.info> On 20/11/2022 02.20, maria python wrote: > Hello, I have these two python codes that work well separately and I > want to combine them, but I am not sure how to do it. Also after that, I > want to print the result in txt cvs or another file format. Do you have > a code for that? Thank you. Have you tried joining them together, one after the other? Have you looked at the Python docs? eg https://docs.python.org/3/library/csv.html Do you need the help of a professional to write code for you? If you are learning Python, perhaps the Tutor list will be a more appropriate for you... -- Regards, =dn From baran200167 at gmail.com Sat Nov 19 05:44:21 2022 From: baran200167 at gmail.com (=?UTF-8?B?QmFyYW4gR8O2a8OnZWtsaQ==?=) Date: Sat, 19 Nov 2022 02:44:21 -0800 (PST) Subject: Logging Message-ID: <5fb80174-1266-49f4-813f-6b1546ef8a74n@googlegroups.com> How can I solve this question? There is a module called ?logging? to employ logging facility in Python. import logging logging. info('Just a normal message' ) Logging.warning('Not fatal but still noted') logging.error('There is something wrong') You are expected to implement logging feature to an existing code which uses the function below. def my_ugly_debug(s, level=0): pre_text = [ "INFO", "WARNING", "ERROR" ] print(f"{pre_text[level]}: {s}") You are not allowed to make changes in my_ugly_debug, so find another way. From PythonList at DancesWithMice.info Sat Nov 19 14:37:29 2022 From: PythonList at DancesWithMice.info (dn) Date: Sun, 20 Nov 2022 08:37:29 +1300 Subject: Passing information between modules In-Reply-To: References: Message-ID: <14ee5354-ecdb-1689-6917-6db7c4b6ec26@DancesWithMice.info> On 18/11/2022 23.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 ] > > . "sys.argv" is said to be a list by the standard > documentation, so it should be guaranteed to be > appendable as lists are appendable. > > Moreover, in my own program, after its startup, third parties > do not inspect "sys.argv". So by appending something to it > (or modifying it) I do not tamper with information that might > be misinterpreted by any third party outside of my own code. > > Another hack might be: > > in module A > > import builtins > builtins.message = "Hi there!" > > in module B > > import builtins > message = builtins.message > > But I'm not sure whether modules (such as "builtins" here) > are guaranteed to be modifyable and visible by the language > reference in this way though The re-use of built-in features is risky, if only because of the remote possibility that a future version of Python will add something that clashes. That's why Python makes such good (and careful) use of namespaces! In some respects we have the (OP) problem because Python does not have "interfaces" as a formal component of the language. So, we often get-away with taking an easier course - but in doing-so, may forget that they serve specific purposes. There is a general idea that globals are harmful, a code-smell, etc; and therefore something to be avoided. However, the global namespace is a (built-in!) feature of Python, so why not use it? The problem comes when we try to re-use module A or B in some other application. It may not be relatively-obvious that some global, eg config, must be previously-defined and made-available. If you're prepared to accept that risk - and presumably combat the criticism by carefully (and prominently) documenting it, just as with any other docstring, where's the problem? (caveat emptor!) Considering the use-case, it is unlikely to be as trivial as the example-given (OP). A classic example would be set of credentials to access an RDBMS and specific table(s). A 'standard' solution is to collect all such configuration-data at the start of the application, into an object (or other data-structure) - I usually call it "env" (an instantiation of "Environment"). Thereafter, when needing such data within a module, calling the particular function/class/method by name (moduleNM.function(...) ), and passing only that section of the env[ironment] required. Such achieved by passing some sub-structure of env, or by passing a retrieval/get method. (a module handling GUI, for example, has no business looking at RDBMS-creds - which it would be able to do if the whole env was passed!) but... the module's code will expect its data in a particular form (an interface!), which must be documented and understood by both the provider and consumer (people and software) - which sounds like the same 'solution' to the 'globals problem'... -- Regards, =dn From michael.stemper at gmail.com Sat Nov 19 15:46:16 2022 From: michael.stemper at gmail.com (Michael F. Stemper) Date: Sat, 19 Nov 2022 14:46:16 -0600 Subject: Passing information between modules In-Reply-To: References: Message-ID: 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. From list1 at tompassin.net Sat Nov 19 16:35:15 2022 From: list1 at tompassin.net (Thomas Passin) Date: Sat, 19 Nov 2022 16:35:15 -0500 Subject: Passing information between modules In-Reply-To: References: Message-ID: <35f3acbe-c09a-f9d7-f214-a021821d8db3@tompassin.net> On 11/19/2022 4:28 PM, Thomas Passin wrote: > On 11/19/2022 3:46 PM, Michael F. Stemper wrote: >> 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. > > For that matter, you can just directly add attributes to the sys module, > no need to use sys.argv: > > >>> import sys > >>> sys._extra = 'spam'?? # Not an exception > >>> print(sys._extra) > spam > > Probably not the best idea, though.? Better to use some module that you > control directly. This could be one of those things of which Raymond Chen (The Old New Thing) asks "what if everyone did this?". Imagine if every (non-standard-library) module misused sys or sys.argv like this. The result could be chaotic. Best to put all your own stuff into modules that you yourself control. From list1 at tompassin.net Sat Nov 19 16:28:43 2022 From: list1 at tompassin.net (Thomas Passin) Date: Sat, 19 Nov 2022 16:28:43 -0500 Subject: Passing information between modules In-Reply-To: References: Message-ID: On 11/19/2022 3:46 PM, Michael F. Stemper wrote: > 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. For that matter, you can just directly add attributes to the sys module, no need to use sys.argv: >>> import sys >>> sys._extra = 'spam' # Not an exception >>> print(sys._extra) spam Probably not the best idea, though. Better to use some module that you control directly. From cs at cskk.id.au Sat Nov 19 17:27:58 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 20 Nov 2022 09:27:58 +1100 Subject: Logging In-Reply-To: References: Message-ID: On 19Nov2022 11:08, Stefan Ram wrote: > writes: >>You are expected to implement logging feature to an existing >>code which uses the function below. [...] >>You are not allowed to make changes in my_ugly_debug, so find another >>way. > > If found a solution that is even more ugly than your > function. I was just about to post it here, but then > remembered about the "no homework" rule. Bummer! I suspect that the OP is just being asked to modify existing code which calls my_ugly_debug to use more conventional logging calls. Baran, in addition to the various info(), warning() etc logging calls there is a log() logging call which accepts a log level (the warning() etc calls basicly call this with their own logging level). I would be inclined to write a my_better_debug(s,level=0) function which took those existing levels (0,1,2) and mapped them to the official logging levels logging.INFO, logging.WARNING etc, and then called logging.log() with the official level. Then adjust the calling code to call your new function. The alternative is to just replace every calling function which uses my_ugly_debug() to directly call a logging.whatever() call. Cheers, Cameron Simpson From cs at cskk.id.au Sat Nov 19 17:36:41 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 20 Nov 2022 09:36:41 +1100 Subject: Passing information between modules In-Reply-To: References: Message-ID: On 18Nov2022 10:53, Stefan Ram wrote: > Can I use "sys.argv" to pass information between modules > as follows? [...] Stefan, it looks like most of the replies take the form: yes you can do that but it is probably a bad idea. Could you outline the larger situation where you want to do this? Often this kind of response ("yes but don't!") can be a clue that you're chasing the wrong (sorry, "suboptimal/poor") solution to a problem which can be solved in another way. Cheers, Cameron Simpson From list1 at tompassin.net Sat Nov 19 18:26:25 2022 From: list1 at tompassin.net (Thomas Passin) Date: Sat, 19 Nov 2022 18:26:25 -0500 Subject: Logging In-Reply-To: References: Message-ID: <6ba20661-6487-4071-0e87-1f7c369049cf@tompassin.net> On 11/19/2022 5:27 PM, Cameron Simpson wrote: > On 19Nov2022 11:08, Stefan Ram wrote: >> writes: >>> You are expected to implement logging feature to an existing >>> code which uses the function below. [...] >>> You are not allowed to make changes in my_ugly_debug, so find another >>> way. >> >> ?If found a solution that is even more ugly than your >> ?function. I was just about to post it here, but then >> ?remembered about the "no homework" rule. Bummer! > > I suspect that the OP is just being asked to modify existing code which > calls my_ugly_debug to use more conventional logging calls. > > Baran, in addition to the various info(), warning() etc logging calls > there is a log() logging call which accepts a log level (the warning() > etc calls basicly call this with their own logging level). > > I would be inclined to write a my_better_debug(s,level=0) function which > took those existing levels (0,1,2) and mapped them to the official > logging levels logging.INFO, logging.WARNING etc, and then called > logging.log() with the official level. > > Then adjust the calling code to call your new function. > > The alternative is to just replace every calling function which uses > my_ugly_debug() to directly call a logging.whatever() call. Maybe a place for a decorator... > Cheers, > Cameron Simpson From cs at cskk.id.au Sat Nov 19 20:26:19 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 20 Nov 2022 12:26:19 +1100 Subject: Logging In-Reply-To: <6ba20661-6487-4071-0e87-1f7c369049cf@tompassin.net> References: <6ba20661-6487-4071-0e87-1f7c369049cf@tompassin.net> Message-ID: On 19Nov2022 18:26, Thomas Passin wrote: >>The alternative is to just replace every calling function which uses >>my_ugly_debug() to directly call a logging.whatever() call. > >Maybe a place for a decorator... Indeed, though I don't think the OP is up to decorators yet. But really, is there any problem which cannot be solved with a decorator? I've even got a @decorator decorator for my decorators. Cheers, Cameron Simpson From rosuav at gmail.com Sat Nov 19 20:36:29 2022 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 20 Nov 2022 12:36:29 +1100 Subject: Logging In-Reply-To: References: <6ba20661-6487-4071-0e87-1f7c369049cf@tompassin.net> Message-ID: On Sun, 20 Nov 2022 at 12:27, Cameron Simpson wrote: > > On 19Nov2022 18:26, Thomas Passin wrote: > >>The alternative is to just replace every calling function which uses > >>my_ugly_debug() to directly call a logging.whatever() call. > > > >Maybe a place for a decorator... > > Indeed, though I don't think the OP is up to decorators yet. > > But really, is there any problem which cannot be solved with a > decorator? I've even got a @decorator decorator for my decorators. > Do you have a @toomanydecorators decorator to reduce the number of decorators you need to decorate your decorators? ChrisA From list1 at tompassin.net Sat Nov 19 21:17:00 2022 From: list1 at tompassin.net (Thomas Passin) Date: Sat, 19 Nov 2022 21:17:00 -0500 Subject: Superclass static method name from subclass In-Reply-To: <4f83091d-951e-eb3e-a3ad-670ecd894d97@declassed.art> References: <4f83091d-951e-eb3e-a3ad-670ecd894d97@declassed.art> Message-ID: <2c972bf2-82b3-36f5-2e60-1c3ca3837f1b@tompassin.net> On 11/13/2022 7:27 AM, Axy via Python-list wrote: > On 11/11/2022 16:21, Ian Pilcher wrote: >> Is it possible to access the name of a superclass static method, when >> defining a subclass attribute, without specifically naming the super- >> class? A instance's __bases__ attribute is a sequence that contains all its base classes. So: class A: @staticmethod def double(n): return 2 * n class B(A): def parent_method(self, n): par = self.__class__.__bases__[0] # For single inheritance return par.double(n) b = B() print(b.parent_method(3)) # 6 # or print(b.__class__.__bases__[0].double(4)) # 8 >> Contrived example: >> >> ? class SuperClass(object): >> ????? @staticmethod >> ????? def foo(): >> ????????? pass >> >> ? class SubClass(SuperClass): >> ????? bar = SuperClass.foo >> ??????????? ^^^^^^^^^^ >> >> Is there a way to do this without specifically naming 'SuperClass'? >> > There is, but it's weird. I constructed classes from yaml config so I > did not even know the name of super class but I wanted similar things > for my clabate templates and I implemented superattr() which works for me: > > class BasePage: > > ??? body = '

Hello

' > > class MySpecificPage(BasePage): > > ??? body = superattr() + '

World

' > > Actually, it's suboptimally elegant code. Artistic code, to be clear, as > if you looked at modern art and thought: WTF? Also, it's specific for > templates only and supports only __add__. > > But I think the approach can be extended to a general superclass() if > you log __getattr__ calls and apply them in __get__ method same way. > > I realize this reply is not an immediate help and probably won't help, > but there's always a way out. > > Axy. > > Here's the code: > > > class? superattr: > ??? ''' > This is a descriptor that allows extending attributes in a simple and > elegant way: > > my_attr = superattr() + some_addition_to_my_attr > ''' > ??? def? __init__(self): > ??????? self.additions? =? [] > > ??? def? __set_name__(self,? owner,? name): > ??????? print('__set_name__',? name) > ??????? self.attr_name? =? name > > ??? def? __get__(self,? obj,? objtype=None): > ??????? for? cls? in? obj.__class__.__mro__[1:]: > ??????????? try: > ??????????????? value? =? getattr(cls,? self.attr_name) > ??????????? except? AttributeError: > ??????????????? continue > ??????????? for? a? in? self.additions: > ??????????????? value? =? value? +? a > ??????????? return? value > ??????? raise? AttributeError(self.attr_name) > > ??? def? __add__(self,? other): > ??????? print('__add__:',? other) > ??????? self.additions.append(other) > ??????? return? self Full article: > https://declassed.art/en/blog/2022/07/02/a-note-on-multiple-inheritance-in-python From cs at cskk.id.au Sat Nov 19 22:00:58 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 20 Nov 2022 14:00:58 +1100 Subject: Logging In-Reply-To: References: Message-ID: On 20Nov2022 12:36, Chris Angelico wrote: >On Sun, 20 Nov 2022 at 12:27, Cameron Simpson wrote: >> But really, is there any problem which cannot be solved with a >> decorator? I've even got a @decorator decorator for my decorators. > >Do you have a @toomanydecorators decorator to reduce the number of >decorators you need to decorate your decorators? Apparently not :-) @classmethod @pfx_method @promote @typechecked def promote(cls, policy, epoch: Optional[Epoch] = None, **policy_kw): and there aren't even any @require decorators on that one (from the excellent icontract package). Cheers, Cameron Simpson From dankolis at gmail.com Sat Nov 19 21:17:54 2022 From: dankolis at gmail.com (Dan Kolis) Date: Sat, 19 Nov 2022 18:17:54 -0800 (PST) Subject: Passing information between modules In-Reply-To: References: Message-ID: <86f61539-b419-4f0a-a721-377e90f3ed5dn@googlegroups.com> In a module mostly for this purpose; ( big program means many modules aka files ): ---------------------------------------------------------------------------------- globalIdeas.py ---------------------------------------------------------------------------------- # Empty object maker ( M T ) ... get it say it ! class MT(): pass # IO dot area readier def prepIO(): # Prep for general IO use really dotObjOps.ioSupport = MT() dotObjOps.ioSupport.sequenceMacro = MT() ----------------------------------------------------------------- In Every use module: ----------------------------------------------------------------- import globalIdeas as gi so now without burdensome advanced planning, a swap area is not only segregated by function but doesn't overly pollute too much globalism everywhere. New Idea: gl.ioSupport.sequencesMacro.newStartupIdea = {} gl.ioSupport.sequencesMacro.thingToReuse = 14 etc ... A method in globalIdeas is named like startEverything(): prepIO() prepNext() prepSounds() etc... This seems to me amenable to management of large programs in which absolutely any shaped objects be created as needed and be RW sharable in orderly fashion, etc. Its important if you read write files to plan ahead and have MT() names in surplus before you need them. I cant see any drawback to this at all. Many program have very legit reasons to have universal ideas. This avoids the emotional burden of the' "global KW" ; entirely. Regards, Daniel B. Kolis From avi.e.gross at gmail.com Sun Nov 20 10:29:44 2022 From: avi.e.gross at gmail.com (Avi Gross) Date: Sun, 20 Nov 2022 10:29:44 -0500 Subject: Passing information between modules In-Reply-To: <35f3acbe-c09a-f9d7-f214-a021821d8db3@tompassin.net> References: <35f3acbe-c09a-f9d7-f214-a021821d8db3@tompassin.net> Message-ID: There is no guarantee that argv is consulted earlier in the program than other modules will use it for communication. Consider a case where a program does look at argv but later wants to call another program using some or all of the components of argv and now there are added components there. That could lead to all kinds of problems. Some languages have global objects available that you can add to, sort of like a dictionary object and as long as you add keys guaranteed to be unique, can be used carefully to coordinate between parts of your program. Of course, you may also need to use techniques that ensure atomic concurrency. Reusing argv is a hack that should not be needed. On Sat, Nov 19, 2022, 4:37 PM Thomas Passin wrote: > On 11/19/2022 4:28 PM, Thomas Passin wrote: > > On 11/19/2022 3:46 PM, Michael F. Stemper wrote: > >> 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. > > > > For that matter, you can just directly add attributes to the sys module, > > no need to use sys.argv: > > > > >>> import sys > > >>> sys._extra = 'spam' # Not an exception > > >>> print(sys._extra) > > spam > > > > Probably not the best idea, though. Better to use some module that you > > control directly. > > This could be one of those things of which Raymond Chen (The Old New > Thing) asks "what if everyone did this?". Imagine if every > (non-standard-library) module misused sys or sys.argv like this. The > result could be chaotic. > > Best to put all your own stuff into modules that you yourself control. > > -- > https://mail.python.org/mailman/listinfo/python-list > From cht6768316 at gmail.com Sun Nov 20 07:32:00 2022 From: cht6768316 at gmail.com (Hoe Tee) Date: Sun, 20 Nov 2022 20:32:00 +0800 Subject: An email from a user In-Reply-To: References: Message-ID: Hi, I recently installed Python 3.11.0 on my laptop. However, there was no folder named 'Python' in my Program folder after the software was installed. I'm writing this letter since I'm a python learner and the loss of the Python folder in the Program folder seems to cause the Pycharm on my computer unable to import the pandas module. I'm really distressed since I have to get this problem solved to earn grades on my course. I would appreciate it if you can help me evaluate the issue. Best regards, Hoe Tee On Sun, 20 Nov 2022 at 17:14, Hoe Tee wrote: > Hi, I recently installed Python 3.11.0 on my laptop. However, there was no > folder named 'Python' in my Program folder after the software was > installed. I'm writing this letter since I'm a python learner and the loss > of the Python folder in the Program folder seems to cause the Pycharm on my > computer unable to import the pandas module. > > I'm really distressed since I have to get this problem solved to earn > grades on my course. > > I would appreciate it if you can help me evaluate the issue. > > Best regards, > Hoe Tee > From dankolis at gmail.com Sun Nov 20 10:51:54 2022 From: dankolis at gmail.com (Dan Kolis) Date: Sun, 20 Nov 2022 07:51:54 -0800 (PST) Subject: Passing information between modules In-Reply-To: References: <35f3acbe-c09a-f9d7-f214-a021821d8db3@tompassin.net> Message-ID: <98d81e17-6205-4c15-882c-7f455dec4dabn@googlegroups.com> It's certainly not an "incredibly bad idea", it is a mildly bad idea however. Why be stuck with maybe's and just text strings ? Functions as "first class operators" and object oriented languages are a natural pair with a bit of heavy thinking. The problem is... there is nobody giving you a 3 line solution without thinking. Its a 7 line solution requiring understanding. One you do it right, then its a 2 line solution ! Once you construct the bridges; then, in any module you can consider global sharables like so: First vague use of functionality gi.setAsideArea.NewIdea = 'ok' Next usages anywhere ! gi.setAsideArea.NewIdea = "StateMachine Argon" There is no hangover of vague ideas bothering future executions of the code either. This is not some scary file buried in a directory system which needs calling and might be stale, using bad ideas, etc. How much easier can a solution be ? Regards, Daniel B. Kolis From list1 at tompassin.net Sun Nov 20 13:18:11 2022 From: list1 at tompassin.net (Thomas Passin) Date: Sun, 20 Nov 2022 13:18:11 -0500 Subject: An email from a user In-Reply-To: References: Message-ID: <383b1354-8652-39fe-7162-d9941d04113a@tompassin.net> On 11/20/2022 7:32 AM, Hoe Tee wrote: > Hi, I recently installed Python 3.11.0 on my laptop. However, there was no > folder named 'Python' in my Program folder after the software was > installed. I'm writing this letter since I'm a python learner and the loss > of the Python folder in the Program folder seems to cause the Pycharm on my > computer unable to import the pandas module. > > I'm really distressed since I have to get this problem solved to earn > grades on my course. > > I would appreciate it if you can help me evaluate the issue. These days, Python usually installs on Windows into %USERPROFILE%\AppData\Local\Programs. Here, %USERPROFILE% means your user directory, which is usually at c:\Users\. You can type %USERPROFILE% directly into the box at the top of Windows Explorer. If Pycharm cannot find Pandas, it is probably because Pandas has not yet been installed with the new Python 3.11. You would need to install it. From roel at roelschroeven.net Sun Nov 20 13:50:24 2022 From: roel at roelschroeven.net (Roel Schroeven) Date: Sun, 20 Nov 2022 19:50:24 +0100 Subject: Passing information between modules In-Reply-To: References: Message-ID: Stefan Ram schreef op 20/11/2022 om 11:39: > The idea is about parameterizing the behavior of a module. > For example, the module "M" may contain functions that contain > "input.read()" to get input and "output.write()" to write > output. Then one would write code like (the following is > not correct Python code, just pseudo code assuming a possible > extended Python where one can assigned to a module before > it's loaded): > > import sys > > M.input = sys.stdin > M.output = sys.stdout > import M > > . So now M would use sys.stdin for input and sys.stdout > for output. I feel this is a bad idea. This uses global state for customizing local behavior. Yes, maybe you want to customize behavior in one of your modules, or even only in some functions, or maybe in several or even all of your modules. But by changing module "M", you're changing it for *every* user of it, even for standard library modules or third party packages. You can't customize it in different ways in different parts of your code. And it's a kind of spooky action at a distance: the behavior of a module gets changed by another, possibly completely unrelated, module. This has the potential to grossly violate the principle of least surprise. > If someone else would ask this, I'd tell him to use a class: > > import MM > import sys > > M = MM.moduleclass( input=sys.stdin, output=sys.stdout ) That is a *much* better solution, and I would even say it's the only acceptable solution. > , but this is another layer of indirection, so it's a bit > more complicated than the direct approach of parameterizing > a module. I'm not even sure it's more complicated. It's more explicit, which I like. You could have a hybrid approach, like what the random module does. The functions in the random module are actually methods of a global hidden instance of class random.Random; if you want random generators with separate states you can create your own instance(s) of random.Random, or of random.SystemRandom. -- "You can fool some of the people all the time, and all of the people some of the time, but you cannot fool all of the people all of the time." -- Abraham Lincoln "You can fool too many of the people too much of the time." -- James Thurber From PythonList at DancesWithMice.info Sun Nov 20 14:11:30 2022 From: PythonList at DancesWithMice.info (dn) Date: Mon, 21 Nov 2022 08:11:30 +1300 Subject: Passing information between modules In-Reply-To: References: <14ee5354-ecdb-1689-6917-6db7c4b6ec26@DancesWithMice.info> Message-ID: <4f932742-b479-6ad3-8f33-3c8c1beb3f15@DancesWithMice.info> On 21/11/2022 01.03, Stefan Ram wrote: > dn writes: >> In some respects we have the (OP) problem because Python does not have >> "interfaces" as a formal component of the language. > > What one can do today is, > > class my_interface( metaclass=abc.ABCMeta ): > """This interface ...""" > > @abc.abstractmethod > def method( __self__, *s, **x ): > """This abstract method ...""" > > # ... > > my_interface.register( my_class ) > > # ... Ugh! -- Regards, =dn From list1 at tompassin.net Sun Nov 20 14:33:01 2022 From: list1 at tompassin.net (Thomas Passin) Date: Sun, 20 Nov 2022 14:33:01 -0500 Subject: Passing information between modules In-Reply-To: References: Message-ID: <2b030783-d879-924d-d581-89f73c262427@tompassin.net> On 11/20/2022 1:50 PM, Roel Schroeven wrote: > Stefan Ram schreef op 20/11/2022 om 11:39: >> ?? The idea is about parameterizing the behavior of a module. >> ?? For example, the module "M" may contain functions that contain >> ?? "input.read()" to get input and "output.write()" to write >> ?? output. Then one would write code like (the following is >> ?? not correct Python code, just pseudo code assuming a possible >> ?? extended Python where one can assigned to a module before >> ?? it's loaded): >> >> import sys >> >> M.input = sys.stdin >> M.output = sys.stdout >> import M >> >> ?? . So now M would use sys.stdin for input and sys.stdout >> ?? for output. > I feel this is a bad idea. This uses global state for customizing local > behavior. Yes, maybe you want to customize behavior in one of your > modules, or even only in some functions, or maybe in several or even all > of your modules. But by changing module "M", you're changing it for > *every* user of it, even for standard library modules or third party > packages. You can't customize it in different ways in different parts of > your code. And it's a kind of spooky action at a distance: the behavior > of a module gets changed by another, possibly completely unrelated, > module. This has the potential to grossly violate the principle of least > surprise. >> ?? If someone else would ask this, I'd tell him to use a class: >> >> import MM >> import sys >> >> M = MM.moduleclass( input=sys.stdin, output=sys.stdout ) > That is a *much* better solution, and I would even say it's the only > acceptable solution. >> ?? , but this is another layer of indirection, so it's a bit >> ?? more complicated than the direct approach of parameterizing >> ?? a module. > I'm not even sure it's more complicated. It's more explicit, which I like. > > You could have a hybrid approach, like what the random module does. The > functions in the random module are actually methods of a global hidden > instance of class random.Random; if you want random generators with > separate states you can create your own instance(s) of random.Random, or > of random.SystemRandom. As I wrote, it's another case of "what if everyone did this". e.g.: https://devblogs.microsoft.com/oldnewthing/20050607-00/?p=35413 https://devblogs.microsoft.com/oldnewthing/20101125-00/?p=12203 From roel at roelschroeven.net Sun Nov 20 16:07:05 2022 From: roel at roelschroeven.net (Roel Schroeven) Date: Sun, 20 Nov 2022 22:07:05 +0100 Subject: Passing information between modules In-Reply-To: <2b030783-d879-924d-d581-89f73c262427@tompassin.net> References: <2b030783-d879-924d-d581-89f73c262427@tompassin.net> Message-ID: Thomas Passin schreef op 20/11/2022 om 20:33: > https://devblogs.microsoft.com/oldnewthing/20050607-00/?p=35413 > https://devblogs.microsoft.com/oldnewthing/20101125-00/?p=12203 > Now that I think about it, The Old New Thing is also where I got the global vs local thing: "Don?t use global state to manage a local problem", https://devblogs.microsoft.com/oldnewthing/20081211-00/?p=19873 -- "In the old days, writers used to sit in front of a typewriter and stare out of the window. Nowadays, because of the marvels of convergent technology, the thing you type on and the window you stare out of are now the same thing.? -- Douglas Adams From dankolis at gmail.com Sun Nov 20 16:16:18 2022 From: dankolis at gmail.com (Dan Kolis) Date: Sun, 20 Nov 2022 13:16:18 -0800 (PST) Subject: Passing information between modules In-Reply-To: References: <2b030783-d879-924d-d581-89f73c262427@tompassin.net> Message-ID: <627531c4-3397-4ec0-b789-bad233bbaf0dn@googlegroups.com> Using sys.stdout / is simply nonsense. The more I think about it, the more I realise how bad it is. Going on about it endlessly seems pointless. If the even mini threading thing is turned on, now what ? some other module eats the message intended for a different module ? A state machine with its own matching code in sends and receives to reuse the unwanted singular value ? The precise rules for establishing a variable without the global keyword is not obvious, or catcat of anything by leaving a empty set dangling initially. *especially* if the program is fundamentally open ended, that is, there could be considerable new functions sharing ideas all over, planning ahead for as good 45 seconds is a lot better then endless hacking any old way. 1) Make a variable in a module known to be a shared item. Named for that specifically. def Mt() {} IoDot = {} # Once before program does anything... in global. ref import global as gi later. 2) Create highly generalised speculative named ideas init each variable once with a {} ioDot.weights = Mt{} ; ( I make it a local method so the method can stand alone for unit testing ) 3) Uniformly ref it with a import statement. in all 'other' modules 4) When a shared idea is apparent concat a new named portion to the name for this purpose. Then use those fairly without fussing as required. If one scares you, set it to {} after some scary moment if you are feeling fussy. 5) All 'ideas' will be at a 3rd or more subsid level in naming. ex: gi.IoDot.weights.trucks = whatever gi.IoDot.weights.cars = whatever gi.toastDot.warnings.tooHeavy gi.toastDot.warnings.isOk These can all be any kind of object. So easy I have a very sizable highly generalized program using this and have not found any defect in doing so. Regs Dan From rosuav at gmail.com Sun Nov 20 17:40:45 2022 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 21 Nov 2022 09:40:45 +1100 Subject: Passing information between modules In-Reply-To: <627531c4-3397-4ec0-b789-bad233bbaf0dn@googlegroups.com> References: <2b030783-d879-924d-d581-89f73c262427@tompassin.net> <627531c4-3397-4ec0-b789-bad233bbaf0dn@googlegroups.com> Message-ID: On Mon, 21 Nov 2022 at 09:37, Dan Kolis wrote: > > Using sys.stdout / is simply nonsense. The more I think about it, the more I realise how bad it is. > > Going on about it endlessly seems pointless. > > If the even mini threading thing is turned on, now what ? some other module eats the message intended for a different module ? A state machine with its own matching code in sends and receives to reuse the unwanted singular value ? > > The precise rules for establishing a variable without the global keyword is not obvious, or catcat of anything by leaving a empty set dangling initially. > > *especially* if the program is fundamentally open ended, that is, there could be considerable new functions sharing ideas all over, planning ahead for as good 45 seconds is a lot better then endless hacking any old way. You should print this out and get it on a t-shirt. It's a perfect example of AI-generated text. ChrisA From dankolis at gmail.com Sun Nov 20 18:07:22 2022 From: dankolis at gmail.com (Dan Kolis) Date: Sun, 20 Nov 2022 15:07:22 -0800 (PST) Subject: Passing information between modules In-Reply-To: References: <2b030783-d879-924d-d581-89f73c262427@tompassin.net> <627531c4-3397-4ec0-b789-bad233bbaf0dn@googlegroups.com> Message-ID: <43a6b362-a651-409d-a3e3-027b04550ff7n@googlegroups.com> Its advice, I don't think the style issue is particularly important. If you understand its meaning, it achieves my purpose. If you don't I you're perhaps not a programmer... I like the abruptness of technical writing as a style, actually. If that is how machine learning ( aka 'A.I.' ) tends to compose messages, this seems mostly compatible with the sorts of written material I both make and consume. https://interestingliterature.com/2017/03/10-of-the-best-poems-about-forests-and-trees/ The whisper of the aspens is not drowned, And over lightless pane and footless road, Empty as sky, with every other sound Not ceasing, calls their ghosts from their abode, there's one for you... a click will get you nine more. but none will help you write a better, more maintainable program. Regards, Dan From list1 at tompassin.net Sun Nov 20 22:01:40 2022 From: list1 at tompassin.net (Thomas Passin) Date: Sun, 20 Nov 2022 22:01:40 -0500 Subject: Passing information between modules In-Reply-To: References: <2b030783-d879-924d-d581-89f73c262427@tompassin.net> Message-ID: On 11/20/2022 4:07 PM, Roel Schroeven wrote: > Thomas Passin schreef op 20/11/2022 om 20:33: >> https://devblogs.microsoft.com/oldnewthing/20050607-00/?p=35413 >> https://devblogs.microsoft.com/oldnewthing/20101125-00/?p=12203 >> > Now that I think about it, The Old New Thing is also where I got the > global vs local thing: "Don?t use global state to manage a local > problem", https://devblogs.microsoft.com/oldnewthing/20081211-00/?p=19873 > Bingo! From PythonList at DancesWithMice.info Mon Nov 21 00:01:33 2022 From: PythonList at DancesWithMice.info (dn) Date: Mon, 21 Nov 2022 18:01:33 +1300 Subject: Passing information between modules In-Reply-To: <43a6b362-a651-409d-a3e3-027b04550ff7n@googlegroups.com> References: <2b030783-d879-924d-d581-89f73c262427@tompassin.net> <627531c4-3397-4ec0-b789-bad233bbaf0dn@googlegroups.com> <43a6b362-a651-409d-a3e3-027b04550ff7n@googlegroups.com> Message-ID: <145abeb4-c6a8-ba73-f559-5ac9c15a14eb@DancesWithMice.info> On 21/11/2022 12.07, Dan Kolis wrote: > If you understand its meaning, it achieves my purpose. If you don't I you're perhaps not a programmer... Ouch! Does the first sentence imply who is the more important person in the interaction? Does the second further the idea that anyone/everyone who is not at your 'level' has no worth? -- Regards, =dn From list1 at tompassin.net Mon Nov 21 00:12:25 2022 From: list1 at tompassin.net (Thomas Passin) Date: Mon, 21 Nov 2022 00:12:25 -0500 Subject: Passing information between modules In-Reply-To: <145abeb4-c6a8-ba73-f559-5ac9c15a14eb@DancesWithMice.info> References: <2b030783-d879-924d-d581-89f73c262427@tompassin.net> <627531c4-3397-4ec0-b789-bad233bbaf0dn@googlegroups.com> <43a6b362-a651-409d-a3e3-027b04550ff7n@googlegroups.com> <145abeb4-c6a8-ba73-f559-5ac9c15a14eb@DancesWithMice.info> Message-ID: <70b2fa55-4f1a-7cd8-ca2a-52a45c11cf79@tompassin.net> On 11/21/2022 12:01 AM, dn wrote: > On 21/11/2022 12.07, Dan Kolis wrote: >> If you understand its meaning, it achieves my purpose. If you don't I >> you're perhaps not a programmer... > > Ouch! > > Does the first sentence imply who is the more important person in the > interaction? Does the second further the idea that anyone/everyone who > is not at your 'level' has no worth? Folks, this is getting into ad hominem territory. I suggest it's time to end the thread, since it's no longer productive. From PythonList at DancesWithMice.info Mon Nov 21 00:24:41 2022 From: PythonList at DancesWithMice.info (dn) Date: Mon, 21 Nov 2022 18:24:41 +1300 Subject: Passing information between modules In-Reply-To: References: <14ee5354-ecdb-1689-6917-6db7c4b6ec26@DancesWithMice.info> Message-ID: <869bd30f-3e6e-6646-2e65-aa2a14cff5ec@DancesWithMice.info> On 21/11/2022 01.29, Stefan Ram wrote: > dn writes: >> A 'standard' solution is to collect all such configuration-data at the >> start of the application, into an object (or other data-structure) - I >> usually call it "env" (an instantiation of "Environment"). > > Yeah, I had some functions of my library take such an "env", > which in my library is called "context": > > def python_version_check( major=3, minor=9, context=x_default_context ): > passed = _sys.version_info >=( major, minor ) > if not passed: > requirements_info = "This program requires Python " + \ > str( major ) + "." + str( minor )+ "+.\n" > version_info = "Currently running under Python {}.{}.\n". \ > format( *_sys.version_info[ :2 ] ) > context.warning( requirements_info + version_info ) > return passed > > . But so far I am using "context" only for logging, so I am > now thinking about replacing with Pythons logging facility. > > One possible application of "context", however, would also be > normal output, which has to be shown to the user, not only > logging as in: > > def show_sum( x, y, context=x_default_context ): > context.print( f'The sum is {x+y}.' ) > > . For example, there could by a "GUI context" by which > "context.print" would append the output to some GUI text > field. Using the logging facility to output text that must > be show to the user, would abuse logging somewhat. > > def show_sum( x, y, context=x_default_context ): > logger.log\ > ( my_custom_level_for_output_to_user, f'The sum is {x+y}.' ) > > Or one could "print patch" a module, via (using the class from > a recent post of mine): > > M = prepare_module( 'M' ) > M.print = my_gui_print_function > M = M.load() > M.f() > > and "show_sum" would be simply: > > def show_sum( x, y, context=x_default_context ): > print( f'The sum is {x+y}.'). > > My original question probably was intended to be something > like: "Today, we can add attributes to a module from the > outside. How large is the risk that this will be forbidden > one day, so that all code using this will stop working?". Am put-off by the 'smell' of subverting/adapting names like print() = surprise/confusion factor - but I think I understand where you're going. What about an ABC which is inherited by two classes. One class handles all the detail of output to GUI. The other, similarly, output to the terminal, log, (whatever). The ABC should require an output() method, with suitable signature. The two classes will vary on the fine detail of the HOW, leaving the calling-routine to produce the WHAT. Now, at the config stage, take the instructions to define whichever the user prefers, and instantiate that class. Then the 'calling-routine' can use the instantiated object as an interface to whichever type of output. If the choices on-offer include not just either/or, but also 'both of the above'. The instantiation would need to be a class which called both class's output() method serially. Your use of the word "context" provoked some thought. (you don't know just how dangerous that could become!) In many ways, and as described, an Environment/context class could be very easily coded with formal __enter__() and __exit__() methods. The mainline might then become: with Environment() as env: # processing There would be no need to explicitly prevent any 'processing' if the set-up doesn't work, because that context manager class will handle it all! NB haven't had time to try this as a refactoring exercise. Is this how you implement? -- Regards, =dn From rosuav at gmail.com Mon Nov 21 00:46:50 2022 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 21 Nov 2022 16:46:50 +1100 Subject: Passing information between modules In-Reply-To: <869bd30f-3e6e-6646-2e65-aa2a14cff5ec@DancesWithMice.info> References: <14ee5354-ecdb-1689-6917-6db7c4b6ec26@DancesWithMice.info> <869bd30f-3e6e-6646-2e65-aa2a14cff5ec@DancesWithMice.info> Message-ID: On Mon, 21 Nov 2022 at 16:26, dn wrote: > Am put-off by the 'smell' of subverting/adapting names like print() = > surprise/confusion factor - but I think I understand where you're going. To be fair, redefining the "print" function IS one of the reasons that it's no longer a statement. Though I would generally recommend maintaining its signature and purpose. ChrisA From list1 at tompassin.net Mon Nov 21 00:53:40 2022 From: list1 at tompassin.net (Thomas Passin) Date: Mon, 21 Nov 2022 00:53:40 -0500 Subject: Passing information between modules In-Reply-To: <869bd30f-3e6e-6646-2e65-aa2a14cff5ec@DancesWithMice.info> References: <14ee5354-ecdb-1689-6917-6db7c4b6ec26@DancesWithMice.info> <869bd30f-3e6e-6646-2e65-aa2a14cff5ec@DancesWithMice.info> Message-ID: On 11/21/2022 12:24 AM, dn wrote: >> My original question probably was intended to be something >> ?? like: "Today, we can add attributes to a module from the >> ?? outside. How large is the risk that this will be forbidden >> ?? one day, so that all code using this will stop working?". This can happen today if, for example, a class is changed to use slots for everything. Between slots and type checking, it can become impossible to add an arbitrary attribute. *You* may be able to avoid this, but if you use someone else's modules or classes it could happen at any time. I might regret the loss of being able to assign an arbitrary attribute wherever I like, but for complex libraries, it is probably a good idea in the long run. From darkstone at o2online.de Mon Nov 21 12:59:03 2022 From: darkstone at o2online.de (darkstone at o2online.de) Date: Mon, 21 Nov 2022 17:59:03 +0000 Subject: Python 3.11.0 installation and Tkinter does not work Message-ID: <1669053543.611j21mcgk4ckgsw@mail.o2online.de> Dear list, I want learn python for 4 weeks and have problems, installing Tkinter. If I installed 3.11.0 for my windows 8.1 from python.org and type ? >>> import _tkinter > Traceback (most recent call last): >? ? File "", line 1, in > ImportError: DLL load failed while importing _tkinter: Das angegebene > Modul wurde nicht gefunden. > So I it is a tkinter Problem and I tried this: >? >>> import _tkinter > Traceback (most recent call last): >? ? File "", line 1, in > ImportError: DLL load failed while importing _tkinter: Das angegebene > Modul wurde nicht gefunden. How can I fix this and make it work? From list1 at tompassin.net Mon Nov 21 16:41:57 2022 From: list1 at tompassin.net (Thomas Passin) Date: Mon, 21 Nov 2022 16:41:57 -0500 Subject: Python 3.11.0 installation and Tkinter does not work In-Reply-To: References: Message-ID: <8378b7f9-64ea-917f-baf0-d60fa360d7fb@tompassin.net> On 11/21/2022 1:24 PM, Stefan Ram wrote: > darkstone at o2online.de writes: >>>>> import _tkinter > > I don't know why you get this error message. Here, I do not > get an error message from that line. However, the normal way > to use tkinter, as far as I know, is without the underscore! You can import both tkinter and _tkinter, though I'm not sure why you would do the latter for any normal programming. > I think it might be best if you make sure that a recent > Visual C++ Redistributable Runtime from Microsoft? > is installed before you install Python. That's a worthwhile thought. > If you have no such Runtime, I have no idea how to proceed! > Maybe uninstall Python, install the Runtime, and then install > Python again? python.org says: "Note that Python 3.11.0 cannot be used on Windows 7 or earlier" But maybe there's something about their compilation settings or runtime support versions that doesn't work with the OP's version of Python 8.1. Or, since Python itself seems to be running, maybe the way the tkinter binary was compiled isn't compatible even though Python 3.11 itself is. Maybe this is a bug waiting to be filed... I would try installing a lower version, maybe an older version of Python 3.10, and seeing if that works. > If you have chosen any unusual settings during the installation > of Python, it might help to try an installation with the suggested > settings. > > I am trying to learn tkinter myself and I am very surprised > how well it offers exactly what I am looking for! I hope they > never will remove tkinter from the standard distribution! > > From barry at barrys-emacs.org Mon Nov 21 17:17:45 2022 From: barry at barrys-emacs.org (Barry) Date: Mon, 21 Nov 2022 22:17:45 +0000 Subject: Passing information between modules In-Reply-To: References: Message-ID: <6E37E704-C02C-469F-AEE9-DA080E3CBC6E@barrys-emacs.org> > On 21 Nov 2022, at 21:23, ram at zedat.fu-berlin.de wrote: > > ?dn writes: >> Now, at the config stage, take the instructions to define whichever the >> user prefers, and instantiate that class. Then the 'calling-routine' can >> use the instantiated object as an interface to whichever type of output. > > I had many different functions that are supposed to take > a "context" argument. If I would make them all methods of > a class with a "context" field, that would be a huge class > containing methods with many different purposes, which > reminds of the "anti pattern" "God class". Do you haves lots of free standing functions? Are all these functions not part of classes? > >> with Environment() as env: >> # processing >> There would be no need to explicitly prevent any 'processing' if the >> set-up doesn't work, because that context manager class will handle it all! > > Yes, but my problem was not so much with setting up the env, > but with passing it to many library functions. Are you writing procedural code or object oriented? Why do you have so many functions outside of a small number of classes? > >> Is this how you implement? > > I'm not sure whether I understand the meaning of this question. You appear not to be doing object oriented design. > > My library had a "console context" (before I started to use > the Python logging facility instead). That console context was > the default for output of progress and error messages. > > A client had the possibility to call functions with a custom > context, and then the function would use this custom context > for progress and error messages. The custom context could > direct those message to a text field in a GUI, for example. > > Instead of passing this custom context to many library > functions, it might be simpler to "pass it to the library > once". This could be done via: > > import library > library.context = my_GUI_context That is not oo design. I get the feeling that you need a better understanding of how to structure a non-trivia library. If you need the context object then you must pass it around. > > , but I wonder whether this "writing into another module" > is really possible in every Python implementation and whether > it will still be supported in the future. I do not see such > a pattern being used with the standard packages and suppose > that there might be a reason for this! > > The same question applies to the more advanced technique of > using "importlib.util.find_spec", "importlib.util.module_from_spec", > and ".__spec__.loader.exec_module" to even support having > different instances of a single module with different globals. > > I can now formulate my question this way: > > Many functions of a library have in their source code calls > like "PRINT( f'Done. Output was written to {filename}.' )". > The library uses "print" as a default for "PRINT", but > should explicitly support clients substituting a custom > implementation to be used for "PRINT". What's the best way > for the client to "pass" his custom implementation to the > library (which is a package or a module)? Each place you have PRINT you need to have context.print calls. You said above that you have, or had, such an object - pass it around and use it. If passing it around is the problem then you need to look at why you code has that problem. Barry > > > -- > https://mail.python.org/mailman/listinfo/python-list > From nospam at dfs.com Mon Nov 21 17:32:17 2022 From: nospam at dfs.com (DFS) Date: Mon, 21 Nov 2022 17:32:17 -0500 Subject: Python 3.11.0 installation and Tkinter does not work In-Reply-To: References: <1669053543.611j21mcgk4ckgsw@mail.o2online.de> Message-ID: On 11/21/2022 12:59 PM, darkstone at o2online.de wrote: > > > > > > Dear list, > > I want learn python for 4 weeks and have problems, installing Tkinter. If I installed 3.11.0 for my windows 8.1 from python.org and type > > ? >>> import _tkinter > > Traceback (most recent call last): > >? ? File "", line 1, in > > ImportError: DLL load failed while importing _tkinter: Das angegebene > > Modul wurde nicht gefunden. > > > So I it is a tkinter Problem and I tried this: > > >? >>> import _tkinter > > Traceback (most recent call last): > >? ? File "", line 1, in > > ImportError: DLL load failed while importing _tkinter: Das angegebene > > Modul wurde nicht gefunden. > > How can I fix this and make it work? When installing Python 3.11.0 did you check the box "tcl/tk and IDLE"? (it's an option on the Python Windows installer). I made sure to do that, and then this worked: import tkinter from tkinter import filedialog as fd from tkinter.filedialog import askopenfilename filename = fd.askopenfilename() print(filename) foldername = fd.askdirectory() print(foldername) time.sleep(3) From mats at wichmann.us Tue Nov 22 10:22:08 2022 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 22 Nov 2022 08:22:08 -0700 Subject: Python 3.11.0 installation and Tkinter does not work In-Reply-To: <8378b7f9-64ea-917f-baf0-d60fa360d7fb@tompassin.net> References: <8378b7f9-64ea-917f-baf0-d60fa360d7fb@tompassin.net> Message-ID: <8ec55922-967c-a470-ec9e-3b529bbb2dbf@wichmann.us> On 11/21/22 14:41, Thomas Passin wrote: > On 11/21/2022 1:24 PM, Stefan Ram wrote: >> darkstone at o2online.de writes: >>>>>> import _tkinter >> >> ?? I don't know why you get this error message. Here, I do not >> ?? get an error message from that line. However, the normal way >> ?? to use tkinter, as far as I know, is without the underscore! > > You can import both tkinter and _tkinter, though I'm not sure why you > would do the latter for any normal programming. No, but it's often the advice given when things are not working - see if the underlying tkinter module can be imported, to verify it's actually findable, so not surprised to see someone trying it. From barry at barrys-emacs.org Tue Nov 22 17:18:50 2022 From: barry at barrys-emacs.org (Barry) Date: Tue, 22 Nov 2022 22:18:50 +0000 Subject: Python 3.11.0 installation and Tkinter does not work In-Reply-To: References: Message-ID: <67D88974-C694-415A-811B-DFBACFBDD955@barrys-emacs.org> > On 22 Nov 2022, at 16:09, ram at zedat.fu-berlin.de wrote: > > ?darkstone at o2online.de writes: >>> ImportError: DLL load failed while importing _tkinter: Das angegebene >>> Modul wurde nicht gefunden. > > If you have not already done so, make sure that you install > Python from python.org. > > Then, after the installation, you also should make sure that > you actually use this installed version. > > import sys > sys.version_info > import tkinter > > It is possible that you have installed a different version > of Python before and accidentally have opened that version, > which may not include tkinter. In which case the error is module not found. The error reported suggests that a dll that _tkinter needs is missing. Barry > > > -- > https://mail.python.org/mailman/listinfo/python-list > From loris.bennett at fu-berlin.de Wed Nov 23 11:00:44 2022 From: loris.bennett at fu-berlin.de (Loris Bennett) Date: Wed, 23 Nov 2022 17:00:44 +0100 Subject: Preprocessing not quite fixed-width file before parsing Message-ID: Hi, I am using pandas to parse a file with the following structure: Name fileset type KB quota limit in_doubt grace | files quota limit in_doubt grace shortname sharedhome USR 14097664 524288000 545259520 0 none | 107110 0 0 0 none gracedays sharedhome USR 774858944 524288000 775946240 0 5 days | 1115717 0 0 0 none nametoolong sharedhome USR 27418496 524288000 545259520 0 none | 11581 0 0 0 none I was initially able to use df = pandas.read_csv(file_name, delimiter=r"\s+") because all the values for 'grace' were 'none'. Now, however, non-"none" values have appeared and this fails. I can't use pandas.read_fwf even with an explicit colspec, because the names in the first column which are too long for the column will displace the rest of the data to the right. The report which produces the file could in fact also generate a properly delimited CSV file, but I have a lot of historical data in the readable but poorly parsable format above that I need to deal with. If I were doing something similar in the shell, I would just pipe the file through sed or something to replace '5 days' with, say '5_days'. How could I achieve a similar sort of preprocessing in Python, ideally without having to generate a lot of temporary files? Cheers, Loris -- This signature is currently under constuction. From rosuav at gmail.com Wed Nov 23 14:28:45 2022 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 24 Nov 2022 06:28:45 +1100 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: Message-ID: On Thu, 24 Nov 2022 at 06:26, Stefan Ram wrote: > > Jon Ribbens writes: > >If you want to catch this sort of mistake automatically then you need > >a linter such as pylint: > > output > > , line 1 > list.clear > Warning: Attribute used as statement. > > , line 5 > list.clear > Warning: Attribute used as statement. > > source code > > import ast, sys > > def check( point, source ): > if isinstance( point, ast.Expr ) and\ > type( point.value )== ast.Attribute: > print( ", line", point.lineno, file=sys.stderr ) > print( source.split( '\n' )[ point.lineno-1 ], file=sys.stderr ) > print\ > ( "Warning:", "Attribute used as statement.", file=sys.stderr ) > print() > > def mylinter( source ): > for point in ast.walk( ast.parse( example )): > check( point, source ) > > example = """\ > list.clear > list.clear() > x = list.clear > print( list.clear ) > list.clear > """ > > mylinter( example ) > Uhh, yes? You just created an extremely simplistic linter. Your point? ChrisA From barry at barrys-emacs.org Wed Nov 23 14:48:31 2022 From: barry at barrys-emacs.org (Barry Scott) Date: Wed, 23 Nov 2022 19:48:31 +0000 Subject: Python 3.11.0 installation and Tkinter does not work In-Reply-To: References: Message-ID: <9BE9618A-8BA8-4829-8027-FBE8D990B5F6@barrys-emacs.org> > On 23 Nov 2022, at 06:31, Stefan Ram wrote: > > darkstone at o2online.de writes: >> I want learn python for 4 weeks and have problems, installing Tkinter. If I= >> installed 3.11.0 for my windows 8.1 from python.org and type > > Ok, so you already installed from python.org. I wonder a > little about the wording "installing Tkinter". Here, > I installed /Python/ from python.org, and this /included/ tkinter. > If you have really attempted a separate installation of tkinter, > it may help to uninstall and instead install Python /including/ > tkinter. > >>> ImportError: DLL load failed while importing _tkinter: Das angegebene >>> Modul wurde nicht gefunden. > > Another possibility of analysis is to watch the Python > process using "Process Monitor" (formerly from Sysinternals) > under Microsoft? Windows (not to be confused with "Process > Explorer"). This program requires some familiarization, > but then it can show you in which directories a process is > searching for which DLLs. This might help you to find the > name of the DLL missing and in which directory it should be. I think the depends.exe tool from sysintenals will do this as well. There is a mode where you run a program and it collects the data for all the DLLs that are used either statically linked or dynamicall loaded, that is the case for _tkinter. I have not used in in a very long time but I recall it shows errors from DLLs that failed to load. Barry > > > -- > https://mail.python.org/mailman/listinfo/python-list From gweatherby at uchc.edu Wed Nov 23 15:40:59 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Wed, 23 Nov 2022 20:40:59 +0000 Subject: Preprocessing not quite fixed-width file before parsing In-Reply-To: References: Message-ID: Oops. Forgot to Reformat file before sending. Here?s the proper PEP-8 (at least according to PyCharm) import pandas import logging class Wrapper: """Wrap file to fix up data""" def __init__(self, filename): self.filename = filename def __enter__(self): self.fh = open(self.filename, 'r') return self def __exit__(self, exc_type, exc_val, exc_tb): self.fh.close() def __iter__(self): """This is required by pandas for some reason, even though it doesn't seem to be called""" raise ValueError("Unsupported operation") def read(self, n: int): """Read data. Replace 'grace' before | if it has underscores in it""" try: data = self.fh.readline() ht = data.split('|', maxsplit=2) if len(ht) == 2: head, tail = ht hparts = head.split(maxsplit=7) assert len(hparts) == 8 if ' ' in hparts[7].strip(): hparts[7] = hparts[7].strip().replace(' ', '_') fixed_data = f"{' '.join(hparts)} | {tail}" return fixed_data return data except: logging.exception("read") logging.basicConfig() with Wrapper('data.txt') as f: df = pandas.read_csv(f, delimiter=r"\s+") print(df) From: Weatherby,Gerard Date: Wednesday, November 23, 2022 at 3:38 PM To: Loris Bennett , python-list at python.org Subject: Re: Preprocessing not quite fixed-width file before parsing This seems to work. I?m inferring the | is present in each line that needs to be fixed. import pandas import logging class Wrapper: """Wrap file to fix up data""" def __init__(self, filename): self.filename = filename def __enter__(self): self.fh = open(self.filename,'r') return self def __exit__(self, exc_type, exc_val, exc_tb): self.fh.close() def __iter__(self): """This is required by pandas for some reason, even though it doesn't seem to be called""" raise ValueError("Unsupported operation") def read(self, n: int): """Read data. Replace 'grace' before | if it has underscores in it""" try: data = self.fh.readline() ht = data.split('|', maxsplit=2) if len(ht) == 2: head,tail = ht hparts = head.split(maxsplit=7) assert len(hparts) == 8 if ' ' in hparts[7].strip(): hparts[7] = hparts[7].strip().replace(' ','_') fixed_data = f"{' '.join(hparts)} | {tail}" return fixed_data return data except: logging.exception("read") logging.basicConfig() with Wrapper('data.txt') as f: df = pandas.read_csv(f, delimiter=r"\s+") print(df) From: Python-list on behalf of Loris Bennett Date: Wednesday, November 23, 2022 at 2:00 PM To: python-list at python.org Subject: Preprocessing not quite fixed-width file before parsing *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** Hi, I am using pandas to parse a file with the following structure: Name fileset type KB quota limit in_doubt grace | files quota limit in_doubt grace shortname sharedhome USR 14097664 524288000 545259520 0 none | 107110 0 0 0 none gracedays sharedhome USR 774858944 524288000 775946240 0 5 days | 1115717 0 0 0 none nametoolong sharedhome USR 27418496 524288000 545259520 0 none | 11581 0 0 0 none I was initially able to use df = pandas.read_csv(file_name, delimiter=r"\s+") because all the values for 'grace' were 'none'. Now, however, non-"none" values have appeared and this fails. I can't use pandas.read_fwf even with an explicit colspec, because the names in the first column which are too long for the column will displace the rest of the data to the right. The report which produces the file could in fact also generate a properly delimited CSV file, but I have a lot of historical data in the readable but poorly parsable format above that I need to deal with. If I were doing something similar in the shell, I would just pipe the file through sed or something to replace '5 days' with, say '5_days'. How could I achieve a similar sort of preprocessing in Python, ideally without having to generate a lot of temporary files? Cheers, Loris -- This signature is currently under constuction. -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!hBypaGqqmBaUa_w_PNTK9VelYEJCChO6c7d8k1yz6N56806CJ0wtAfLhvj5UaWrGaccJTzKxrjQJCil9DJ470VZWO4fOfhk$ From gweatherby at uchc.edu Wed Nov 23 15:38:49 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Wed, 23 Nov 2022 20:38:49 +0000 Subject: Preprocessing not quite fixed-width file before parsing In-Reply-To: References: Message-ID: This seems to work. I?m inferring the | is present in each line that needs to be fixed. import pandas import logging class Wrapper: """Wrap file to fix up data""" def __init__(self, filename): self.filename = filename def __enter__(self): self.fh = open(self.filename,'r') return self def __exit__(self, exc_type, exc_val, exc_tb): self.fh.close() def __iter__(self): """This is required by pandas for some reason, even though it doesn't seem to be called""" raise ValueError("Unsupported operation") def read(self, n: int): """Read data. Replace 'grace' before | if it has underscores in it""" try: data = self.fh.readline() ht = data.split('|', maxsplit=2) if len(ht) == 2: head,tail = ht hparts = head.split(maxsplit=7) assert len(hparts) == 8 if ' ' in hparts[7].strip(): hparts[7] = hparts[7].strip().replace(' ','_') fixed_data = f"{' '.join(hparts)} | {tail}" return fixed_data return data except: logging.exception("read") logging.basicConfig() with Wrapper('data.txt') as f: df = pandas.read_csv(f, delimiter=r"\s+") print(df) From: Python-list on behalf of Loris Bennett Date: Wednesday, November 23, 2022 at 2:00 PM To: python-list at python.org Subject: Preprocessing not quite fixed-width file before parsing *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** Hi, I am using pandas to parse a file with the following structure: Name fileset type KB quota limit in_doubt grace | files quota limit in_doubt grace shortname sharedhome USR 14097664 524288000 545259520 0 none | 107110 0 0 0 none gracedays sharedhome USR 774858944 524288000 775946240 0 5 days | 1115717 0 0 0 none nametoolong sharedhome USR 27418496 524288000 545259520 0 none | 11581 0 0 0 none I was initially able to use df = pandas.read_csv(file_name, delimiter=r"\s+") because all the values for 'grace' were 'none'. Now, however, non-"none" values have appeared and this fails. I can't use pandas.read_fwf even with an explicit colspec, because the names in the first column which are too long for the column will displace the rest of the data to the right. The report which produces the file could in fact also generate a properly delimited CSV file, but I have a lot of historical data in the readable but poorly parsable format above that I need to deal with. If I were doing something similar in the shell, I would just pipe the file through sed or something to replace '5 days' with, say '5_days'. How could I achieve a similar sort of preprocessing in Python, ideally without having to generate a lot of temporary files? Cheers, Loris -- This signature is currently under constuction. -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!hBypaGqqmBaUa_w_PNTK9VelYEJCChO6c7d8k1yz6N56806CJ0wtAfLhvj5UaWrGaccJTzKxrjQJCil9DJ470VZWO4fOfhk$ From list1 at tompassin.net Wed Nov 23 16:36:53 2022 From: list1 at tompassin.net (Thomas Passin) Date: Wed, 23 Nov 2022 16:36:53 -0500 Subject: Preprocessing not quite fixed-width file before parsing In-Reply-To: References: Message-ID: <6a3104b2-1c99-5bff-83f3-87381282b947@tompassin.net> On 11/23/2022 11:00 AM, Loris Bennett wrote: > Hi, > > I am using pandas to parse a file with the following structure: > > Name fileset type KB quota limit in_doubt grace | files quota limit in_doubt grace > shortname sharedhome USR 14097664 524288000 545259520 0 none | 107110 0 0 0 none > gracedays sharedhome USR 774858944 524288000 775946240 0 5 days | 1115717 0 0 0 none > nametoolong sharedhome USR 27418496 524288000 545259520 0 none | 11581 0 0 0 none > > I was initially able to use > > df = pandas.read_csv(file_name, delimiter=r"\s+") > > because all the values for 'grace' were 'none'. Now, however, > non-"none" values have appeared and this fails. > > I can't use > > pandas.read_fwf > > even with an explicit colspec, because the names in the first column > which are too long for the column will displace the rest of the data to > the right. > > The report which produces the file could in fact also generate a > properly delimited CSV file, but I have a lot of historical data in the > readable but poorly parsable format above that I need to deal with. > > If I were doing something similar in the shell, I would just pipe the > file through sed or something to replace '5 days' with, say '5_days'. > How could I achieve a similar sort of preprocessing in Python, ideally > without having to generate a lot of temporary files? This is really annoying, isn't it? A space-separated line with spaces in data entries. If the example you give is typical, I don't think there is a general solution. If you know there are only certain values like that, then you could do a search-and-replace for them in Python just like the example you gave for "5 days". If you know that the field that might contain entries with spaces is the same one, e.g., the one just before the "|" marker, you could make use of that. But it could be tricky. I don't know how many files like this you will need to process, nor how many rows they might contain. If I were to do tackle this job, I would probably do some quality checking first. Using this example file, figure out how many fields there are supposed to be. First, split the file into lines: with open("filename") as f: lines = f.readlines() # Check space-separated fields defined in first row: fields = lines[0].split() num_fields = len(fields) print(num_fields) # e.g., 100) # Find lines that have the wrong number of fields bad_lines = [] for line in lines: fields = line.split() if len(fields) != num_fields: bad_lines.append(line) print(len(bad_lines)) # Inspect a sample for line in bad_lines[:10]: print(line) This will give you an idea of how many problems lines there are, and if they can all be fixed by a simple replacement. If they can and this is the only file you need to handle, just fix it up and run it. I would replace the spaces with tabs or commas. Splitting a line on spaces (split()) takes care of the issue of having a variable number of spaces, so that's easy enough. If you will need to handle many files, and you can automate the fixes - possibly with a regular expression - then you should preprocess each file before giving it to pandas. Something like this: def fix_line(line): """Test line for field errors and fix errors if any.""" # .... return fixed # For each file with open("filename") as f: lines = f.readlines() fixed_lines = [] for line in lines: fixed = fix_line(line) fields = fixed.split() tabified = '\t'.join(fields) # Could be done by fix_line() fixed_lines.append(tabified) # Now use an IOString to feed the file to pandas # From memory, some details may not be right f = IOString() f.writelines(fixed_lines) # Give f to pandas as if it were an external file # ... From jsf80238 at gmail.com Wed Nov 23 21:49:19 2022 From: jsf80238 at gmail.com (Jason Friedman) Date: Wed, 23 Nov 2022 19:49:19 -0700 Subject: Python 3.11.0 installation and Tkinter does not work In-Reply-To: <1669053543.611j21mcgk4ckgsw@mail.o2online.de> References: <1669053543.611j21mcgk4ckgsw@mail.o2online.de> Message-ID: > > I want learn python for 4 weeks and have problems, installing Tkinter. If > I installed 3.11.0 for my windows 8.1 from python.org and type > > >>> import _tkinter > > Traceback (most recent call last): > > File "", line 1, in > > ImportError: DLL load failed while importing _tkinter: Das angegebene > > Modul wurde nicht gefunden. > > > So I it is a tkinter Problem and I tried this: > > > >>> import _tkinter > > Traceback (most recent call last): > > File "", line 1, in > > ImportError: DLL load failed while importing _tkinter: Das angegebene > > Modul wurde nicht gefunden. > > How can I fix this and make it work? > Have a look at https://stackoverflow.com/questions/25905540/importerror-no-module-named-tkinter . Most of the answers are for Linux/Mac, but there are Windows answers there, too. From robin at reportlab.com Thu Nov 24 05:05:03 2022 From: robin at reportlab.com (Robin Becker) Date: Thu, 24 Nov 2022 10:05:03 +0000 Subject: is mypy failing here Message-ID: I haven't used dataclasses or typing very much, but while playing about I found this didn't give me an expected error (.py312) robin at minikat:~/devel/reportlab $ cat tmp/examples/tdc.py && python tmp/examples/tdc.py && mypy tmp/examples/tdc.py ################################## from dataclasses import dataclass @dataclass class DC: a: str b: str def main(): dc = DC(DC, "B") print(dc) if __name__ == "__main__": main() ################################## DC(a=, b='B') Success: no issues found in 1 source file (.py312) robin at minikat:~/devel/reportlab DC.a is supposed to be a str and I expected mypy to indicate a type error should typing work for this case? -- Robin Becker From list1 at tompassin.net Thu Nov 24 07:34:04 2022 From: list1 at tompassin.net (Thomas Passin) Date: Thu, 24 Nov 2022 07:34:04 -0500 Subject: is mypy failing here In-Reply-To: References: Message-ID: <750a61b9-2fd7-4dfb-d8d5-92a2e7fa3e7e@tompassin.net> On 11/24/2022 5:05 AM, Robin Becker wrote: > I haven't used dataclasses or typing very much, but while playing about > I found this didn't give me an expected error > > (.py312) robin at minikat:~/devel/reportlab > $ cat tmp/examples/tdc.py && python tmp/examples/tdc.py && mypy > tmp/examples/tdc.py > ################################## > from dataclasses import dataclass > > @dataclass > class DC: > ??? a: str > ??? b: str > > def main(): > ??? dc = DC(DC, "B") > ??? print(dc) > > if __name__ == "__main__": > ??? main() > ################################## > DC(a=, b='B') > Success: no issues found in 1 source file > (.py312) robin at minikat:~/devel/reportlab > > DC.a is supposed to be a str and I expected mypy to indicate a type error > > should typing work for this case? > -- > Robin Becker Sounds like a bug. With Python 3.10: C:\temp\python>py -V Python 3.10.4 C:\temp\python>py tdc.py DC(a=, b='B') C:\temp\python>mypy tdc.py tdc.py:10: error: Argument 1 to "DC" has incompatible type "Type[DC]"; expected "str" [arg-type] Found 1 error in 1 file (checked 1 source file) From gweatherby at uchc.edu Thu Nov 24 08:55:41 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Thu, 24 Nov 2022 13:55:41 +0000 Subject: is mypy failing here In-Reply-To: <750a61b9-2fd7-4dfb-d8d5-92a2e7fa3e7e@tompassin.net> References: <750a61b9-2fd7-4dfb-d8d5-92a2e7fa3e7e@tompassin.net> Message-ID: https://github.com/python/mypy/issues/12971 From: Python-list on behalf of Thomas Passin Date: Thursday, November 24, 2022 at 7:36 AM To: python-list at python.org Subject: Re: is mypy failing here *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** On 11/24/2022 5:05 AM, Robin Becker wrote: > I haven't used dataclasses or typing very much, but while playing about > I found this didn't give me an expected error > > (.py312) robin at minikat:~/devel/reportlab > $ cat tmp/examples/tdc.py && python tmp/examples/tdc.py && mypy > tmp/examples/tdc.py > ################################## > from dataclasses import dataclass > > @dataclass > class DC: > a: str > b: str > > def main(): > dc = DC(DC, "B") > print(dc) > > if __name__ == "__main__": > main() > ################################## > DC(a=, b='B') > Success: no issues found in 1 source file > (.py312) robin at minikat:~/devel/reportlab > > DC.a is supposed to be a str and I expected mypy to indicate a type error > > should typing work for this case? > -- > Robin Becker Sounds like a bug. With Python 3.10: C:\temp\python>py -V Python 3.10.4 C:\temp\python>py tdc.py DC(a=, b='B') C:\temp\python>mypy tdc.py tdc.py:10: error: Argument 1 to "DC" has incompatible type "Type[DC]"; expected "str" [arg-type] Found 1 error in 1 file (checked 1 source file) -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!kFNV-Nh17mkih_KN3698Xv9rdmHpmQyEjpm-GBtPKVScpGjUISLM12MJ6yKj4O3JKeNVh7Ft9zhsPV8cURU$ From list1 at tompassin.net Thu Nov 24 09:10:28 2022 From: list1 at tompassin.net (Thomas Passin) Date: Thu, 24 Nov 2022 09:10:28 -0500 Subject: is mypy failing here In-Reply-To: <750a61b9-2fd7-4dfb-d8d5-92a2e7fa3e7e@tompassin.net> References: <750a61b9-2fd7-4dfb-d8d5-92a2e7fa3e7e@tompassin.net> Message-ID: On 11/24/2022 7:34 AM, Thomas Passin wrote: > On 11/24/2022 5:05 AM, Robin Becker wrote: >> I haven't used dataclasses or typing very much, but while playing >> about I found this didn't give me an expected error >> >> (.py312) robin at minikat:~/devel/reportlab >> $ cat tmp/examples/tdc.py && python tmp/examples/tdc.py && mypy >> tmp/examples/tdc.py >> ################################## >> from dataclasses import dataclass >> >> @dataclass >> class DC: >> ???? a: str >> ???? b: str >> >> def main(): >> ???? dc = DC(DC, "B") >> ???? print(dc) >> >> if __name__ == "__main__": >> ???? main() >> ################################## >> DC(a=, b='B') >> Success: no issues found in 1 source file >> (.py312) robin at minikat:~/devel/reportlab >> >> DC.a is supposed to be a str and I expected mypy to indicate a type error >> >> should typing work for this case? >> -- >> Robin Becker > > > Sounds like a bug.? With Python 3.10: > > C:\temp\python>py -V > Python 3.10.4 > > C:\temp\python>py tdc.py > DC(a=, b='B') > > C:\temp\python>mypy tdc.py > tdc.py:10: error: Argument 1 to "DC" has incompatible type "Type[DC]"; > expected "str"? [arg-type] > Found 1 error in 1 file (checked 1 source file) > Forgot the mypy version: C:\Users\tom>mypy --version mypy 0.910 From niktarlirik at zohomail.com Thu Nov 24 08:50:04 2022 From: niktarlirik at zohomail.com (Kirill Ratkin) Date: Thu, 24 Nov 2022 16:50:04 +0300 Subject: is mypy failing here In-Reply-To: References: Message-ID: Hi Robin, mypy --strict gives you detail info. On Thu, Nov 24, 2022 at 10:05 +0000, Robin Becker wrote: > I haven't used dataclasses or typing very much, but while playing about I found this didn't give me an expected error > > (.py312) robin at minikat:~/devel/reportlab > $ cat tmp/examples/tdc.py && python tmp/examples/tdc.py && mypy tmp/examples/tdc.py > ################################## > from dataclasses import dataclass > > @dataclass > class DC: > a: str > b: str > > def main(): > dc = DC(DC, "B") > print(dc) > > if __name__ == "__main__": > main() > ################################## > DC(a=, b='B') > Success: no issues found in 1 source file > (.py312) robin at minikat:~/devel/reportlab > > DC.a is supposed to be a str and I expected mypy to indicate a type error > > should typing work for this case? > -- > Robin Becker > -- > https://mail.python.org/mailman/listinfo/python-list From loris.bennett at fu-berlin.de Thu Nov 24 09:06:17 2022 From: loris.bennett at fu-berlin.de (Loris Bennett) Date: Thu, 24 Nov 2022 15:06:17 +0100 Subject: Preprocessing not quite fixed-width file before parsing References: <6a3104b2-1c99-5bff-83f3-87381282b947@tompassin.net> Message-ID: Thomas Passin writes: > On 11/23/2022 11:00 AM, Loris Bennett wrote: >> Hi, >> I am using pandas to parse a file with the following structure: >> Name fileset type KB quota limit >> in_doubt grace | files quota limit in_doubt grace >> shortname sharedhome USR 14097664 524288000 545259520 0 none | 107110 0 0 0 none >> gracedays sharedhome USR 774858944 524288000 775946240 0 5 days | 1115717 0 0 0 none >> nametoolong sharedhome USR 27418496 524288000 545259520 0 none | 11581 0 0 0 none >> I was initially able to use >> df = pandas.read_csv(file_name, delimiter=r"\s+") >> because all the values for 'grace' were 'none'. Now, however, >> non-"none" values have appeared and this fails. >> I can't use >> pandas.read_fwf >> even with an explicit colspec, because the names in the first column >> which are too long for the column will displace the rest of the data to >> the right. >> The report which produces the file could in fact also generate a >> properly delimited CSV file, but I have a lot of historical data in the >> readable but poorly parsable format above that I need to deal with. >> If I were doing something similar in the shell, I would just pipe >> the >> file through sed or something to replace '5 days' with, say '5_days'. >> How could I achieve a similar sort of preprocessing in Python, ideally >> without having to generate a lot of temporary files? > > This is really annoying, isn't it? A space-separated line with spaces > in data entries. If the example you give is typical, I don't think > there is a general solution. If you know there are only certain > values like that, then you could do a search-and-replace for them in > Python just like the example you gave for "5 days". > > If you know that the field that might contain entries with spaces is > the same one, e.g., the one just before the "|" marker, you could make > use of that. But it could be tricky. > > I don't know how many files like this you will need to process, nor > how many rows they might contain. If I were to do tackle this job, I > would probably do some quality checking first. Using this example > file, figure out how many fields there are supposed to be. First, > split the file into lines: > > with open("filename") as f: > lines = f.readlines() > > # Check space-separated fields defined in first row: > fields = lines[0].split() > num_fields = len(fields) > print(num_fields) # e.g., 100) > > # Find lines that have the wrong number of fields > bad_lines = [] > for line in lines: > fields = line.split() > if len(fields) != num_fields: > bad_lines.append(line) > > print(len(bad_lines)) > > # Inspect a sample > for line in bad_lines[:10]: > print(line) > > This will give you an idea of how many problems lines there are, and > if they can all be fixed by a simple replacement. If they can and > this is the only file you need to handle, just fix it up and run it. > I would replace the spaces with tabs or commas. Splitting a line on > spaces (split()) takes care of the issue of having a variable number > of spaces, so that's easy enough. > > If you will need to handle many files, and you can automate the fixes > - possibly with a regular expression - then you should preprocess each > file before giving it to pandas. Something like this: > > def fix_line(line): > """Test line for field errors and fix errors if any.""" > # .... > return fixed > > # For each file > with open("filename") as f: > lines = f.readlines() > > fixed_lines = [] > for line in lines: > fixed = fix_line(line) > fields = fixed.split() > tabified = '\t'.join(fields) # Could be done by fix_line() > fixed_lines.append(tabified) > > # Now use an IOString to feed the file to pandas > # From memory, some details may not be right > f = IOString() > f.writelines(fixed_lines) > > # Give f to pandas as if it were an external file > # ... > Thanks to both Gerard and Thomas for the pointer to IOString. I ended up just reading the file line-by-line, using a regex to replace ' |' with ' |' and writing the new lines to an IOString, which I then passed to pandas.read_csv. The wrapper approach looks interesting, but it looks like I need to read up more on contexts before adding that to my own code, otherwise I may not understand it in a month's time. Cheers, Loris -- This signature is currently under constuction. From list1 at tompassin.net Thu Nov 24 20:59:39 2022 From: list1 at tompassin.net (Thomas Passin) Date: Thu, 24 Nov 2022 20:59:39 -0500 Subject: Preprocessing not quite fixed-width file before parsing In-Reply-To: References: <6a3104b2-1c99-5bff-83f3-87381282b947@tompassin.net> Message-ID: <98fff01d-5550-4f74-b62e-3322a38ea7a6@tompassin.net> On 11/24/2022 9:06 AM, Loris Bennett wrote: > Thomas Passin writes: > >> On 11/23/2022 11:00 AM, Loris Bennett wrote: >>> Hi, >>> I am using pandas to parse a file with the following structure: >>> Name fileset type KB quota limit >>> in_doubt grace | files quota limit in_doubt grace >>> shortname sharedhome USR 14097664 524288000 545259520 0 none | 107110 0 0 0 none >>> gracedays sharedhome USR 774858944 524288000 775946240 0 5 days | 1115717 0 0 0 none >>> nametoolong sharedhome USR 27418496 524288000 545259520 0 none | 11581 0 0 0 none >>> I was initially able to use >>> df = pandas.read_csv(file_name, delimiter=r"\s+") >>> because all the values for 'grace' were 'none'. Now, however, >>> non-"none" values have appeared and this fails. >>> I can't use >>> pandas.read_fwf >>> even with an explicit colspec, because the names in the first column >>> which are too long for the column will displace the rest of the data to >>> the right. >>> The report which produces the file could in fact also generate a >>> properly delimited CSV file, but I have a lot of historical data in the >>> readable but poorly parsable format above that I need to deal with. >>> If I were doing something similar in the shell, I would just pipe >>> the >>> file through sed or something to replace '5 days' with, say '5_days'. >>> How could I achieve a similar sort of preprocessing in Python, ideally >>> without having to generate a lot of temporary files? >> >> This is really annoying, isn't it? A space-separated line with spaces >> in data entries. If the example you give is typical, I don't think >> there is a general solution. If you know there are only certain >> values like that, then you could do a search-and-replace for them in >> Python just like the example you gave for "5 days". >> >> If you know that the field that might contain entries with spaces is >> the same one, e.g., the one just before the "|" marker, you could make >> use of that. But it could be tricky. >> >> I don't know how many files like this you will need to process, nor >> how many rows they might contain. If I were to do tackle this job, I >> would probably do some quality checking first. Using this example >> file, figure out how many fields there are supposed to be. First, >> split the file into lines: >> >> with open("filename") as f: >> lines = f.readlines() >> >> # Check space-separated fields defined in first row: >> fields = lines[0].split() >> num_fields = len(fields) >> print(num_fields) # e.g., 100) >> >> # Find lines that have the wrong number of fields >> bad_lines = [] >> for line in lines: >> fields = line.split() >> if len(fields) != num_fields: >> bad_lines.append(line) >> >> print(len(bad_lines)) >> >> # Inspect a sample >> for line in bad_lines[:10]: >> print(line) >> >> This will give you an idea of how many problems lines there are, and >> if they can all be fixed by a simple replacement. If they can and >> this is the only file you need to handle, just fix it up and run it. >> I would replace the spaces with tabs or commas. Splitting a line on >> spaces (split()) takes care of the issue of having a variable number >> of spaces, so that's easy enough. >> >> If you will need to handle many files, and you can automate the fixes >> - possibly with a regular expression - then you should preprocess each >> file before giving it to pandas. Something like this: >> >> def fix_line(line): >> """Test line for field errors and fix errors if any.""" >> # .... >> return fixed >> >> # For each file >> with open("filename") as f: >> lines = f.readlines() >> >> fixed_lines = [] >> for line in lines: >> fixed = fix_line(line) >> fields = fixed.split() >> tabified = '\t'.join(fields) # Could be done by fix_line() >> fixed_lines.append(tabified) >> >> # Now use an IOString to feed the file to pandas >> # From memory, some details may not be right >> f = IOString() >> f.writelines(fixed_lines) >> >> # Give f to pandas as if it were an external file >> # ... >> > > Thanks to both Gerard and Thomas for the pointer to IOString. I ended up > just reading the file line-by-line, using a regex to replace > > ' |' > > with > > ' |' > > and writing the new lines to an IOString, which I then passed to > pandas.read_csv. > > The wrapper approach looks interesting, but it looks like I need to read > up more on contexts before adding that to my own code, otherwise I may > not understand it in a month's time. Glad that IOString works for you here. I seem to remember that after writing to the IOString, you have to seek to 0 before reading from it. Better check that point! From goswamisp9887241480 at gmail.com Thu Nov 24 22:13:54 2022 From: goswamisp9887241480 at gmail.com (Goswami Shiv Prasad) Date: Fri, 25 Nov 2022 08:43:54 +0530 Subject: Unable to uninstall the older version of Python Message-ID: Hello sir/ma?am I was trying to uninstall python with older version although popup with uninstall successful could be seen multiple times but the icon is still there. So please assist me for that Thanks & Regards Shiva Goswami From drsalists at gmail.com Fri Nov 25 10:56:22 2022 From: drsalists at gmail.com (Dan Stromberg) Date: Fri, 25 Nov 2022 07:56:22 -0800 Subject: In code, list.clear doesn't throw error - it's just ignored In-Reply-To: References: Message-ID: On Sun, Nov 13, 2022 at 4:45 PM 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 > > -- > https://mail.python.org/mailman/listinfo/python-list I'm not 100% sanguine about properties, but the fact is they are part of the language: $ cat p below cmd output started 2022 Fri Nov 25 07:54:42 AM PST #!/usr/bin/env python3 class P: def __init__(self): self.count = 0 @property def increment(self): self.count += 1 def result(self): return self.count p = P() p.increment p.increment print(p.result()) above cmd output done 2022 Fri Nov 25 07:54:42 AM PST dstromberg at tp-mini-c:~/src/experiments/property x86_64-pc-linux-gnu 2670 $ ./p below cmd output started 2022 Fri Nov 25 07:54:44 AM PST 2 As you can see, if the interpreter refused to do something with p.increment because it has no parens, the meaning of this code would change significantly. From loris.bennett at fu-berlin.de Fri Nov 25 02:09:52 2022 From: loris.bennett at fu-berlin.de (Loris Bennett) Date: Fri, 25 Nov 2022 08:09:52 +0100 Subject: Preprocessing not quite fixed-width file before parsing References: <6a3104b2-1c99-5bff-83f3-87381282b947@tompassin.net> <98fff01d-5550-4f74-b62e-3322a38ea7a6@tompassin.net> Message-ID: Thomas Passin writes: > On 11/24/2022 9:06 AM, Loris Bennett wrote: >> Thomas Passin writes: >> >>> On 11/23/2022 11:00 AM, Loris Bennett wrote: >>>> Hi, >>>> I am using pandas to parse a file with the following structure: >>>> Name fileset type KB quota limit >>>> in_doubt grace | files quota limit in_doubt grace >>>> shortname sharedhome USR 14097664 524288000 545259520 0 none | 107110 0 0 0 none >>>> gracedays sharedhome USR 774858944 524288000 775946240 0 5 days | 1115717 0 0 0 none >>>> nametoolong sharedhome USR 27418496 524288000 545259520 0 none | 11581 0 0 0 none >>>> I was initially able to use >>>> df = pandas.read_csv(file_name, delimiter=r"\s+") >>>> because all the values for 'grace' were 'none'. Now, however, >>>> non-"none" values have appeared and this fails. >>>> I can't use >>>> pandas.read_fwf >>>> even with an explicit colspec, because the names in the first column >>>> which are too long for the column will displace the rest of the data to >>>> the right. >>>> The report which produces the file could in fact also generate a >>>> properly delimited CSV file, but I have a lot of historical data in the >>>> readable but poorly parsable format above that I need to deal with. >>>> If I were doing something similar in the shell, I would just pipe >>>> the >>>> file through sed or something to replace '5 days' with, say '5_days'. >>>> How could I achieve a similar sort of preprocessing in Python, ideally >>>> without having to generate a lot of temporary files? >>> >>> This is really annoying, isn't it? A space-separated line with spaces >>> in data entries. If the example you give is typical, I don't think >>> there is a general solution. If you know there are only certain >>> values like that, then you could do a search-and-replace for them in >>> Python just like the example you gave for "5 days". >>> >>> If you know that the field that might contain entries with spaces is >>> the same one, e.g., the one just before the "|" marker, you could make >>> use of that. But it could be tricky. >>> >>> I don't know how many files like this you will need to process, nor >>> how many rows they might contain. If I were to do tackle this job, I >>> would probably do some quality checking first. Using this example >>> file, figure out how many fields there are supposed to be. First, >>> split the file into lines: >>> >>> with open("filename") as f: >>> lines = f.readlines() >>> >>> # Check space-separated fields defined in first row: >>> fields = lines[0].split() >>> num_fields = len(fields) >>> print(num_fields) # e.g., 100) >>> >>> # Find lines that have the wrong number of fields >>> bad_lines = [] >>> for line in lines: >>> fields = line.split() >>> if len(fields) != num_fields: >>> bad_lines.append(line) >>> >>> print(len(bad_lines)) >>> >>> # Inspect a sample >>> for line in bad_lines[:10]: >>> print(line) >>> >>> This will give you an idea of how many problems lines there are, and >>> if they can all be fixed by a simple replacement. If they can and >>> this is the only file you need to handle, just fix it up and run it. >>> I would replace the spaces with tabs or commas. Splitting a line on >>> spaces (split()) takes care of the issue of having a variable number >>> of spaces, so that's easy enough. >>> >>> If you will need to handle many files, and you can automate the fixes >>> - possibly with a regular expression - then you should preprocess each >>> file before giving it to pandas. Something like this: >>> >>> def fix_line(line): >>> """Test line for field errors and fix errors if any.""" >>> # .... >>> return fixed >>> >>> # For each file >>> with open("filename") as f: >>> lines = f.readlines() >>> >>> fixed_lines = [] >>> for line in lines: >>> fixed = fix_line(line) >>> fields = fixed.split() >>> tabified = '\t'.join(fields) # Could be done by fix_line() >>> fixed_lines.append(tabified) >>> >>> # Now use an IOString to feed the file to pandas >>> # From memory, some details may not be right >>> f = IOString() >>> f.writelines(fixed_lines) >>> >>> # Give f to pandas as if it were an external file >>> # ... >>> >> Thanks to both Gerard and Thomas for the pointer to IOString. I >> ended up >> just reading the file line-by-line, using a regex to replace >> ' |' >> with >> ' |' >> and writing the new lines to an IOString, which I then passed to >> pandas.read_csv. >> The wrapper approach looks interesting, but it looks like I need to >> read >> up more on contexts before adding that to my own code, otherwise I may >> not understand it in a month's time. > > Glad that IOString works for you here. I seem to remember that after > writing to the IOString, you have to seek to 0 before reading from > it. Better check that point! Stefan (whom I forgot to thank: Verziehung, Stefan!), mentioned seek(0), so fortunately I was primed when I read the Python documentation for IOString. Cheers, Loris -- This signature is currently under constuction. From robin at reportlab.com Fri Nov 25 12:00:32 2022 From: robin at reportlab.com (Robin Becker) Date: Fri, 25 Nov 2022 17:00:32 +0000 Subject: is mypy failing here In-Reply-To: References: <750a61b9-2fd7-4dfb-d8d5-92a2e7fa3e7e@tompassin.net> Message-ID: <3a6e39d1-96d9-444e-fc78-49b0a185fee8@everest.reportlab.co.uk> On 24/11/2022 14:10, Thomas Passin wrote: ............. >> >> C:\temp\python>py -V >> Python 3.10.4 >> >> C:\temp\python>py tdc.py >> DC(a=, b='B') >> >> C:\temp\python>mypy tdc.py >> tdc.py:10: error: Argument 1 to "DC" has incompatible type "Type[DC]"; expected "str"? [arg-type] >> Found 1 error in 1 file (checked 1 source file) >> > Forgot the mypy version: > > C:\Users\tom>mypy --version > mypy 0.910 > interesting; I'm on archlinux and neither the system python 3.10.8 / mypy 0.982 gives an error. I did try running in my self build 3.10.8 with latest mypy 0.991 and mypy 0.910 and I still don't get an error. I'll break out the windows 10 laptop and see what happens there. You ran with the py runner. I wonder if that does something special. -- Robin Becker From robin at reportlab.com Fri Nov 25 12:12:37 2022 From: robin at reportlab.com (Robin Becker) Date: Fri, 25 Nov 2022 17:12:37 +0000 Subject: is mypy failing here In-Reply-To: References: Message-ID: <94808036-55fe-fb30-7de8-e1c665073127@everest.reportlab.co.uk> On 24/11/2022 13:50, Kirill Ratkin via Python-list wrote: > mypy --strict gives you detail info. Thanks Kirill, it seems --strict does find the errors. One of those is that on line 9 I have to add a return type ie def main() -> None: ..... if that is added then mypy without --strict also finds the real typing error. So it seems the tool fails in the simplest cases if you forget some typing. Interesting that it works in windows without --strict though. -- Robin Becker From list1 at tompassin.net Fri Nov 25 13:26:02 2022 From: list1 at tompassin.net (Thomas Passin) Date: Fri, 25 Nov 2022 13:26:02 -0500 Subject: is mypy failing here In-Reply-To: <3a6e39d1-96d9-444e-fc78-49b0a185fee8@everest.reportlab.co.uk> References: <750a61b9-2fd7-4dfb-d8d5-92a2e7fa3e7e@tompassin.net> <3a6e39d1-96d9-444e-fc78-49b0a185fee8@everest.reportlab.co.uk> Message-ID: <5de12c25-f4bd-5bc5-75cb-0ecda762137d@tompassin.net> On 11/25/2022 12:00 PM, Robin Becker wrote: > On 24/11/2022 14:10, Thomas Passin wrote: > ............. >>> >>> C:\temp\python>py -V >>> Python 3.10.4 >>> >>> C:\temp\python>py tdc.py >>> DC(a=, b='B') >>> >>> C:\temp\python>mypy tdc.py >>> tdc.py:10: error: Argument 1 to "DC" has incompatible type >>> "Type[DC]"; expected "str"? [arg-type] >>> Found 1 error in 1 file (checked 1 source file) >>> >> Forgot the mypy version: >> >> C:\Users\tom>mypy --version >> mypy 0.910 >> > interesting; I'm on archlinux and neither the system python 3.10.8 / > mypy 0.982 gives an error. I did try running in my self build 3.10.8 > with latest mypy 0.991 and mypy 0.910 and I still don't get an error. > > I'll break out the windows 10 laptop and see what happens there. > > You ran with the py runner. I wonder if that does something special. > -- > Robin Becker I've never noticed any difference running anything else with "py" instead of "python3" or whatever would have to be typed to get another version. From phd at phdru.name Sat Nov 26 07:42:40 2022 From: phd at phdru.name (Oleg Broytman) Date: Sat, 26 Nov 2022 15:42:40 +0300 Subject: Cheetah 3.3.0.post1 Message-ID: Hello! I'm pleased to announce version 3.3.0.post1, the 1st post release of release 3.3.0 of branch 3.3 of CheetahTemplate3. What's new in CheetahTemplate3 ============================== Nothing changed in the library code, no need to upgrade. Tests: - Run tests with Python 3.11. - Fix DeprecationWarning: ``unittest.findTestCases()`` is deprecated. Use ``unittest.TestLoader.loadTestsFromModule()`` instead. CI: - Publish wheels at Github Releases. What is CheetahTemplate3 ======================== Cheetah3 is a free and open source (MIT) Python template engine. It's a fork of the original CheetahTemplate library. Python 2.7 or 3.4+ is required. Where is CheetahTemplate3 ========================= Site: https://cheetahtemplate.org/ Download: https://pypi.org/project/CT3/3.3.0.post1 News and changes: https://cheetahtemplate.org/news.html StackOverflow: https://stackoverflow.com/questions/tagged/cheetah Mailing lists: https://sourceforge.net/p/cheetahtemplate/mailman/ Development: https://github.com/CheetahTemplate3 Developer Guide: https://cheetahtemplate.org/dev_guide/ Example ======= Install:: $ pip install CT3 # (or even "ct3") Below is a simple example of some Cheetah code, as you can see it's practically Python. You can import, inherit and define methods just like in a regular Python module, since that's what your Cheetah templates are compiled to :) :: #from Cheetah.Template import Template #extends Template #set $people = [{'name' : 'Tom', 'mood' : 'Happy'}, {'name' : 'Dick', 'mood' : 'Sad'}, {'name' : 'Harry', 'mood' : 'Hairy'}] How are you feeling?

    #for $person in $people
  • $person['name'] is $person['mood']
  • #end for
Oleg. -- Oleg Broytman https://phdru.name/ phd at phdru.name Programmers don't die, they just GOSUB without RETURN. From jkpark at mymts.net Sun Nov 27 17:47:29 2022 From: jkpark at mymts.net (Karen Park) Date: Sun, 27 Nov 2022 16:47:29 -0600 Subject: Python coding Message-ID: <00CF6ACE-2414-448D-8DD7-A3553BF26B63@mymts.net> Hello, I am trying to do a python code. Using Windows, I got as far as the step that asks me to ?copy the logistics.py file and save it in the same folder that you are running python from? (as displayed by the command prompt). Can you help direct me where to go to copy and save this ?logistics.py? file? Thank you, Karen From skip.montanaro at gmail.com Sun Nov 27 18:40:06 2022 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Sun, 27 Nov 2022 17:40:06 -0600 Subject: =?UTF-8?Q?argparse_=E2=80=94_adding_a_=2D=2Dversion_flag_in_the_face_of_?= =?UTF-8?Q?positional_args?= Message-ID: I have a script to which I'd like to add a --version flag. It should print the version number then exit, much in the same way --help prints the help text then exits. I haven't been able to figure that out. I always get a complaint about the required positional argument. I think I could use something like nargs='*', but that would push off detection of the presence of the positional arg to the application. Shouldn't I be able to tell argparse I'm going to process --verbose, then exit? Thx, Skip From cs at cskk.id.au Sun Nov 27 19:02:29 2022 From: cs at cskk.id.au (Cameron Simpson) Date: Mon, 28 Nov 2022 11:02:29 +1100 Subject: Python coding In-Reply-To: <00CF6ACE-2414-448D-8DD7-A3553BF26B63@mymts.net> References: <00CF6ACE-2414-448D-8DD7-A3553BF26B63@mymts.net> Message-ID: On 27Nov2022 16:47, Karen Park wrote: >I am trying to do a python code. Using Windows, I got as far as the >step that asks me to ?copy the logistics.py file and save it in the >same folder that you are running python from? (as displayed by the >command prompt). >Can you help direct me where to go to copy and save this ?logistics.py? >file? It sounds like you're follow some tutorial? Can you provide the URL of the tutorial you're following? Cheers, Cameron Simpson From m at funkyhat.org Sun Nov 27 19:18:24 2022 From: m at funkyhat.org (Matt Wheeler) Date: Mon, 28 Nov 2022 00:18:24 +0000 (UTC) Subject: argparse =?UTF-8?B?4oCU?= adding a --version flag in the face of positional args In-Reply-To: References: Message-ID: I wondered whether subparsers might work, but they don't quite fit here. This seems to fit the bill fairly well, though I agree it would be nice if there were a neater option: import argparse import sys VERSION = 0.1 def main(args): parser.parse_args(args) class VersionAction(argparse.Action): def __call__(self, parser, namespace, values, option_string): print(VERSION) exit() parser = argparse.ArgumentParser() parser.add_argument("-v", "--version", nargs=0, action=VersionAction) parser.add_argument("pos", nargs=1) if __name__ == "__main__": main(sys.argv[1:]) On Sun, 27 Nov 2022 at 23:40, Skip Montanaro wrote: > > I have a script to which I'd like to add a --version flag. It should print > the version number then exit, much in the same way --help prints the help > text then exits. I haven't been able to figure that out. I always get a > complaint about the required positional argument. > > I think I could use something like nargs='*', but that would push off > detection of the presence of the positional arg to the application. > Shouldn't I be able to tell argparse I'm going to process --verbose, then > exit? > > Thx, > > Skip > -- > https://mail.python.org/mailman/listinfo/python-list -- Matt Wheeler http://funkyh.at From skip.montanaro at gmail.com Sun Nov 27 19:24:31 2022 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Sun, 27 Nov 2022 18:24:31 -0600 Subject: =?UTF-8?Q?Re=3A_argparse_=E2=80=94_adding_a_=2D=2Dversion_flag_in_the_face?= =?UTF-8?Q?_of_positional_args?= In-Reply-To: References: Message-ID: > class VersionAction(argparse.Action): > def __call__(self, parser, namespace, values, option_string): > print(VERSION) > exit() ... > parser.add_argument("-v", "--version", nargs=0, action=VersionAction) Thanks. An action class didn't occur to me. I looked briefly at the code for argparse to see how it handled --help. The added argument seemed normal, so gave up, figuring there was some special handling of that option. Skip From mats at wichmann.us Sun Nov 27 19:29:34 2022 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 27 Nov 2022 17:29:34 -0700 Subject: =?UTF-8?Q?Re=3a_argparse_=e2=80=94_adding_a_--version_flag_in_the_f?= =?UTF-8?Q?ace_of_positional_args?= In-Reply-To: References: Message-ID: <48e1696a-8448-7403-b8e4-8603ff948811@wichmann.us> On 11/27/22 16:40, Skip Montanaro wrote: > I have a script to which I'd like to add a --version flag. It should print > the version number then exit, much in the same way --help prints the help > text then exits. I haven't been able to figure that out. I always get a > complaint about the required positional argument. > > I think I could use something like nargs='*', but that would push off > detection of the presence of the positional arg to the application. > Shouldn't I be able to tell argparse I'm going to process --verbose, then > exit? ummm, hate to say this, but have you checked the documentation? this case is supported using an action named 'version' without doing very much. From miked at dewhirst.com.au Sun Nov 27 19:36:51 2022 From: miked at dewhirst.com.au (Mike Dewhirst) Date: Mon, 28 Nov 2022 11:36:51 +1100 Subject: Python coding In-Reply-To: <00CF6ACE-2414-448D-8DD7-A3553BF26B63@mymts.net> Message-ID: <4NL6C10pJqznVCN@mail.python.org> Create a folder anywhere convenient and copy it in there.Then - if python has been downloaded from the Python website and installed "normally" you can open a command prompt in that folder and type?C:\\$>python logistics.py"normally" means Python is in your path environment variable.--(Unsigned mail from my phone) -------- Original message --------From: Karen Park Date: 28/11/22 10:07 (GMT+10:00) To: python-list at python.org Subject: Python coding Hello,I am trying to do a python code. Using Windows, I got as far as the step that asks me to ?copy the logistics.py file and save it in the same folder that you are running python from? (as displayed by the command prompt). Can you help direct me where to go to copy and save this ?logistics.py? file?Thank you,Karen -- https://mail.python.org/mailman/listinfo/python-list From wlfraed at ix.netcom.com Sun Nov 27 22:09:44 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sun, 27 Nov 2022 22:09:44 -0500 Subject: Python coding References: <00CF6ACE-2414-448D-8DD7-A3553BF26B63@mymts.net> Message-ID: <2798oh1d3qeg8ud3n2v6js54pjrpt4gpdl@4ax.com> On Sun, 27 Nov 2022 16:47:29 -0600, Karen Park declaimed the following: >I am trying to do a python code. Using Windows, I got as far as the step that asks me to ?copy the logistics.py file and save it in the same folder that you are running python from? (as displayed by the command prompt). >Can you help direct me where to go to copy and save this ?logistics.py? file? Well, where do the instructions tell you to obtain "logistics.py"? Or maybe that is the file you are supposed to create using some editor? Unless you've changed directories, opening a command shell should reveal something like: Microsoft Windows [Version 10.0.19044.2251] (c) Microsoft Corporation. All rights reserved. C:\Users\Wulfraed> ... C:\Users\Wulfraed would be the directory in which to save the file (for my machine)... But if I run a few directory changes... Microsoft Windows [Version 10.0.19044.2251] (c) Microsoft Corporation. All rights reserved. C:\Users\Wulfraed>cd "Documents\_Hg-Repositories\Python Progs" C:\Users\Wulfraed\Documents\_Hg-Repositories\Python Progs> ... means the directory to save in would be C:\Users\Wulfraed\Documents\_Hg-Repositories\Python Progs The idea is to save the .py file in the /current working directory/. That way you only need to type the name of the file, without the long directory path, when invoking the program (which assumes 'python" [python.exe] is on your system path). -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From gweatherby at uchc.edu Sun Nov 27 22:26:52 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Mon, 28 Nov 2022 03:26:52 +0000 Subject: =?Windows-1252?Q?Re:_argparse_=97_adding_a_--version_flag_in_the_face_of_?= =?Windows-1252?Q?positional_args?= In-Reply-To: References: Message-ID: Use two parsers: import argparse import sys vparser = argparse.ArgumentParser(add_help=False) vparser.add_argument('--version',action="store_true",help="show version") # look for version, ignore remaining arguments vargs, _ = vparser.parse_known_args() if vargs.version: print("Version 2.0") sys.exit(0) parser = argparse.ArgumentParser() parser.add_argument("positional",type=int) # add version again, so it displays if --help called parser.add_argument('--version',action="store_true",help="show version") args = parser.parse_args() # double argument print(args.positional * 2) From: Python-list on behalf of Skip Montanaro Date: Sunday, November 27, 2022 at 6:42 PM To: Python Subject: argparse ? adding a --version flag in the face of positional args *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** I have a script to which I'd like to add a --version flag. It should print the version number then exit, much in the same way --help prints the help text then exits. I haven't been able to figure that out. I always get a complaint about the required positional argument. I think I could use something like nargs='*', but that would push off detection of the presence of the positional arg to the application. Shouldn't I be able to tell argparse I'm going to process --verbose, then exit? Thx, Skip -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!k-JSWNRKr8fNARGIFw3z_eh_Kv0ouXZKTDEQfWplA3Y3yrLUl81TmbNLiuDiXGOjgXcmNFPOqU2Ldmsh1VCLvLsxBas$ From skip.montanaro at gmail.com Sun Nov 27 22:33:43 2022 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Sun, 27 Nov 2022 21:33:43 -0600 Subject: =?UTF-8?Q?Re=3A_argparse_=E2=80=94_adding_a_=2D=2Dversion_flag_in_the_face?= =?UTF-8?Q?_of_positional_args?= In-Reply-To: <48e1696a-8448-7403-b8e4-8603ff948811@wichmann.us> References: <48e1696a-8448-7403-b8e4-8603ff948811@wichmann.us> Message-ID: > > ummm, hate to say this, but have you checked the documentation? this > case is supported using an action named 'version' without doing very much. > Thanks, Mats. I actually searched all over the argparse docs. (There's a lot to digest. Honestly, if I wasn't attempting to be sort of up-to-date I'd just continue using getopt.) It never occurred to me that "version" would be special, so I didn't specifically search for it, or realize there would be a specific action devoted to it. I knew (the default) "help" was special, so I focused my search for it. Obviously, "--help" is a pretty bad search term. Skip > From jkpark at mymts.net Sun Nov 27 23:23:16 2022 From: jkpark at mymts.net (Karen Park) Date: Sun, 27 Nov 2022 22:23:16 -0600 Subject: =?utf-8?Q?Re:_argparse_=E2=80=94_adding_a_--version_flag_in_the_?= =?utf-8?Q?face_of_positional_args?= In-Reply-To: References: Message-ID: I figured it out?there was a logistics file given with the assignment! I thought it was supposed to be a download included with the python download?oops! Thanks, Karen > On Nov 27, 2022, at 9:34 PM, Skip Montanaro wrote: > > ? >> >> >> ummm, hate to say this, but have you checked the documentation? this >> case is supported using an action named 'version' without doing very much. >> > > Thanks, Mats. > > I actually searched all over the argparse docs. (There's a lot to digest. > Honestly, if I wasn't attempting to be sort of up-to-date I'd just continue > using getopt.) It never occurred to me that "version" would be special, so > I didn't specifically search for it, or realize there would be a specific > action devoted to it. I knew (the default) "help" was special, so I focused > my search for it. Obviously, "--help" is a pretty bad search term. > > Skip > >> > -- > https://mail.python.org/mailman/listinfo/python-list From gweatherby at uchc.edu Mon Nov 28 08:23:35 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Mon, 28 Nov 2022 13:23:35 +0000 Subject: =?Windows-1252?Q?Re:_argparse_=97_adding_a_--version_flag_in_the_face_of_?= =?Windows-1252?Q?positional_args?= In-Reply-To: References: Message-ID: More better: import argparse parser = argparse.ArgumentParser() parser.add_argument("positional",type=int) parser.add_argument('--version',action="version",version="2.0") args = parser.parse_args() # double argument print(args.positional * 2) From: Python-list on behalf of Weatherby,Gerard Date: Sunday, November 27, 2022 at 10:29 PM To: Skip Montanaro , Python Subject: Re: argparse ? adding a --version flag in the face of positional args Use two parsers: import argparse import sys vparser = argparse.ArgumentParser(add_help=False) vparser.add_argument('--version',action="store_true",help="show version") # look for version, ignore remaining arguments vargs, _ = vparser.parse_known_args() if vargs.version: print("Version 2.0") sys.exit(0) parser = argparse.ArgumentParser() parser.add_argument("positional",type=int) # add version again, so it displays if --help called parser.add_argument('--version',action="store_true",help="show version") args = parser.parse_args() # double argument print(args.positional * 2) From: Python-list on behalf of Skip Montanaro Date: Sunday, November 27, 2022 at 6:42 PM To: Python Subject: argparse ? adding a --version flag in the face of positional args *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** I have a script to which I'd like to add a --version flag. It should print the version number then exit, much in the same way --help prints the help text then exits. I haven't been able to figure that out. I always get a complaint about the required positional argument. I think I could use something like nargs='*', but that would push off detection of the presence of the positional arg to the application. Shouldn't I be able to tell argparse I'm going to process --verbose, then exit? Thx, Skip -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!k-JSWNRKr8fNARGIFw3z_eh_Kv0ouXZKTDEQfWplA3Y3yrLUl81TmbNLiuDiXGOjgXcmNFPOqU2Ldmsh1VCLvLsxBas$ -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iuJxNp5rr6BjU2VBDXr3OC1kal6NmqPTePUyYJ3K9gvrkpd-O6LrEW77sZ1Km5k3eglgSURIu991H8zLO9n2APmf$ From skip.montanaro at gmail.com Mon Nov 28 11:36:17 2022 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Mon, 28 Nov 2022 10:36:17 -0600 Subject: =?UTF-8?Q?Re=3A_argparse_=E2=80=94_adding_a_=2D=2Dversion_flag_in_the_face?= =?UTF-8?Q?_of_positional_args?= In-Reply-To: References: Message-ID: Thanks. It occurs to me that instead of providing two special actions ("help" and "version"), it might be worthwhile to provide a standard way of saying, "if present, process this option and exit before considering other details of the command line." Matt's example action works well enough for my needs, but it would be nice if more than one such option could be given. For example: import argparse parser = argparse.ArgumentParser() parser.add_argument("url") parser.add_argument("--version", version="777", action="version") args = parser.parse_args(["--help", "--version"]) Which option is processed depends on their order on the command line. I don't believe it's possible to run the script and see them both processed. That's probably a secondary consideration though. My script is working well enough in this regard now. Skip From loris.bennett at fu-berlin.de Mon Nov 28 01:59:44 2022 From: loris.bennett at fu-berlin.de (Loris Bennett) Date: Mon, 28 Nov 2022 07:59:44 +0100 Subject: argparse =?utf-8?Q?=E2=80=94?= adding a --version flag in the face of positional args References: <48e1696a-8448-7403-b8e4-8603ff948811@wichmann.us> Message-ID: Mats Wichmann writes: > On 11/27/22 16:40, Skip Montanaro wrote: >> I have a script to which I'd like to add a --version flag. It should print >> the version number then exit, much in the same way --help prints the help >> text then exits. I haven't been able to figure that out. I always get a >> complaint about the required positional argument. >> I think I could use something like nargs='*', but that would push >> off >> detection of the presence of the positional arg to the application. >> Shouldn't I be able to tell argparse I'm going to process --verbose, then >> exit? > > ummm, hate to say this, but have you checked the documentation? this > case is supported using an action named 'version' without doing very > much. I hadn't noticed the action 'version'. I just use parser.add_argument( "-v", "--version", action="store_true", dest="version", help="print version" ) ... if args.version: print(f"Version {my_module.__version__}") sys.exit(0) where the version is specified in a pyproj.toml file and __init__.py contains try: import importlib.metadata as importlib_metadata except ModuleNotFoundError: import importlib_metadata __version__ = importlib_metadata.version(__name__) I use poetry to then build the corresponding versioned package. What am I missing by not using the action 'version'? Do I just save having to explicitly test for the version arg? Cheers, Loris -- This signature is currently under constuction. From buurikelvin7 at gmail.com Mon Nov 28 09:12:06 2022 From: buurikelvin7 at gmail.com (Kelvin Buuri) Date: Mon, 28 Nov 2022 17:12:06 +0300 Subject: Setupfailure Message-ID: May python failed to install From wlfraed at ix.netcom.com Mon Nov 28 10:56:13 2022 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 28 Nov 2022 10:56:13 -0500 Subject: =?utf-8?Q?argparse_=E2=80=94_adding_a?= =?utf-8?Q?_--version_flag_in_th?= =?utf-8?Q?e_face_of_positional_?= =?utf-8?Q?args?= References: Message-ID: <2gm9oh91tj1ojlt7lv8ik8kc0lo6fftsd4@4ax.com> On Sun, 27 Nov 2022 22:23:16 -0600, Karen Park declaimed the following: >I figured it out?there was a logistics file given with the assignment! I thought it was supposed to be a download included with the python download?oops! > I think you made this response in the wrong thread... -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From rosuav at gmail.com Mon Nov 28 21:14:44 2022 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 29 Nov 2022 13:14:44 +1100 Subject: =?UTF-8?Q?Re=3A_argparse_=E2=80=94_adding_a_=2D=2Dversion_flag_in_the_face?= =?UTF-8?Q?_of_positional_args?= In-Reply-To: References: <48e1696a-8448-7403-b8e4-8603ff948811@wichmann.us> Message-ID: On Tue, 29 Nov 2022 at 12:37, Loris Bennett wrote: > > Mats Wichmann writes: > > > On 11/27/22 16:40, Skip Montanaro wrote: > >> I have a script to which I'd like to add a --version flag. It should print > >> the version number then exit, much in the same way --help prints the help > >> text then exits. I haven't been able to figure that out. I always get a > >> complaint about the required positional argument. > >> I think I could use something like nargs='*', but that would push > >> off > >> detection of the presence of the positional arg to the application. > >> Shouldn't I be able to tell argparse I'm going to process --verbose, then > >> exit? > > > > ummm, hate to say this, but have you checked the documentation? this > > case is supported using an action named 'version' without doing very > > much. > > I hadn't noticed the action 'version'. I just use > > parser.add_argument( > "-v", "--version", action="store_true", dest="version", > help="print version" > ) > That's still going to validate the rest of the args though - notably, you can't omit any mandatory arguments (like a subcommand). The version and help actions are implemented pretty simply, actually. They're just little action classes that do their action immediately on getting triggered. It should be easy enough to make any action you want that way. ChrisA From miked at dewhirst.com.au Tue Nov 29 02:18:24 2022 From: miked at dewhirst.com.au (Mike Dewhirst) Date: Tue, 29 Nov 2022 18:18:24 +1100 Subject: Python script not letting go of files Message-ID: <245c1bbe-79f4-94f8-95f9-02adfd7251bc@dewhirst.com.au> I have a script which fetches a production site directly from a Subversion repo using svn export It runs a bunch of commands by calling this little method ... def trycmd(cmd, log): ??? retcode = -1 ??? ret = f"Trying {cmd}" ??? try: ??????? retcode = os.system(cmd) ??????? ret = f"\n{cmd} -ok-> {retcode}" ??? except Exception as err: ??????? ret = f"\n{cmd} -fail-> {err}" ??? log.write(remove_password(ret)) ??? return retcode This is the fetching script (omitting variables at the top) which appears to be keeping a finger on files which Apache wants. with open(fetchlog, 'a') as log: ??? ret = f"\n\nFetching {tag}" ??? log.write(ret) ??? cmd = f"sudo rm -Rf {site_root}" ??? if trycmd(cmd, log) == 0: ??????? cmd = f"sudo svn export --force --username {usr} --password {pw} {svn_repo} {site_root}" ??????? if trycmd(cmd, log) == 0: ??????????? # get any new dependencies ??????????? cmd = f"sudo -H pip install -r {reqfile}" ??????????? if trycmd(cmd, log) == 0: ??????????????? # run any migrations shipped from the repo ??????????????? cmd = f"sudo python3 {site_root}/manage.py migrate --noinput --settings={settings}" ??????????????? if trycmd(cmd, log) == 0: ??????????????????? # shouldn't find anything ??????????????????? cmd = f"sudo python3 {site_root}/manage.py makemigrations --noinput --settings={settings}" ??????????????????? if trycmd(cmd, log) == 0: ??????????????????????? # should have been done already ??????????????????????? cmd = f"sudo python3 {site_root}/manage.py migrate --noinput --settings={settings}" ??????????????????????? if trycmd(cmd, log) == 0: ??????????????????????????? # remove all static files from their Apache dir ??????????????????????????? cmd = f"sudo rm -Rf {static_root}/*" ??????????????????????????? if trycmd(cmd, log) == 0: ??????????????????????????????? # copy all static files to the Apache location ??????????????????????????????? cmd = f"sudo python3 {site_root}/manage.py collectstatic --noinput --settings={settings}" ??????????????????????????????? if trycmd(cmd, log) == 0: ??????????????????????????????????? # set all permissions ??????????????????????????????????? cmd = f"sudo {scripts}/perms_{host}.sh" ??????????????????????????????????? if trycmd(cmd, log) == 0: ??????????????????????????????????????? cmd = "sudo service apache2 restart" ??????????????????????????????????????? if trycmd(cmd, log) == 0: ??????????????????????????????????????????? ret = f"\nFinish {tag}\n\n" ??????????????????????????????????????????? log.write(ret) ??????????????????????????????????????? else: ??????????????????????????????????????????? print("Apache didn't restart") ??????????????????????????????????? else: ??????????????????????????????????????? print("Didn't set permissions") ??????????????????????????????? else: ??????????????????????????????????? print("Didn't collectstaic") ??????????????????????????? else: ??????????????????????????????? print("Didn't delete static files") ??????????????????????? else: ??????????????????????????? print("Didn't migrate 2") ??????????????????? else: ??????????????????????? print("Didn't makemigration") ??????????????? else: ??????????????????? print("Didn't migrate 1") ??????????? else: ??????????????? print("Didn't install requirements") ??????? else: ??????????? print("Didn't get source") ??? else: ??????? print("Didn't remove site") exit() The problem I'm trying to fix is that after an Apache reload Apache seems hellbent on filling up its scoreboard and running out of resources. The kind folk on the Apache mailing list say something is hogging the workers. You can see the last operation above is an Apache restart. It should be an Apache reload. Reload however lets Apache run out of resources. Do any of you Python folks see any blunders in the above code along the lines of not letting go of py files or static assets? mod_wsgi is configured with 100% defaults. mod_mpm_event conf per advice from the Apache mailing list is ... ??????? ServerLimit???????????????????? 32 ??????? StartServers??????????????????? 16 ??????? MinSpareThreads???????????????? 400 ??????? MaxSpareThreads???????????????? 800 ??????? ThreadLimit???????????????????? 64 ??????? ThreadsPerChild???????????????? 50 ??????? AsyncRequestWorkerFactor??????? 2 ??????? MaxRequestWorkers?????????????? 800 ??????? MaxConnectionsPerChild????????? 0 Server Version: Apache/2.4.52 (Ubuntu 2022.04) OpenSSL/3.0.2 mod_wsgi/4.9.0 Python/3.10 Server MPM: event Server Built: 2022-09-30T04:09:50 DigitalOcean droplet 8BG RAM and lightly loaded. Many thanks for any hints. Cheers Mike -- Signed email is an absolute defence against phishing. This email has been signed with my private key. If you import my public key you can automatically decrypt my signature and be sure it came from me. Just ask and I'll send it to you. Your email software can handle signing. -------------- next part -------------- A non-text attachment was scrubbed... Name: OpenPGP_signature Type: application/pgp-signature Size: 495 bytes Desc: OpenPGP digital signature URL: From kkchn.in at gmail.com Tue Nov 29 06:53:31 2022 From: kkchn.in at gmail.com (KK CHN) Date: Tue, 29 Nov 2022 17:23:31 +0530 Subject: NEO6 GPS with Py PICO with micropython Message-ID: List , I am following this tutorial to get latitude and longitude data using NEO6 GPS module and Py PICO to read the GPS data from the device. I followed the code specified in this tutorial. https://microcontrollerslab.com/neo-6m-gps-module-raspberry-pi-pico-micropython/ I have installed thony IDE in my Desktop(windows PC) and run the code after the devices all connected and using USB cable connected to my PC. When I ran the program I am able to see the output of latitude and longitude in the console of thony IDE. But between certain intervals of a few seconds I am getting the latitude and longitude data ( its printing GPS data not found ?? ) in the python console. The satellite count from the $GGPA output showing 03 .. and the GPS data not found repeating randomly for intervals of seconds. Any hints why it is missing the GPS data (randomly) ?? PS:- The GPS device I placed outside my window and connected to the PC with a USB cable from the PICO module. GPS device NEO6 light (Red LED ) blinking even though the " GPS data not found" messages in th python console. Any hints ?? most welcome Yours, Krishane From gweatherby at uchc.edu Tue Nov 29 07:52:15 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Tue, 29 Nov 2022 12:52:15 +0000 Subject: Python script not letting go of files In-Reply-To: <245c1bbe-79f4-94f8-95f9-02adfd7251bc@dewhirst.com.au> References: <245c1bbe-79f4-94f8-95f9-02adfd7251bc@dewhirst.com.au> Message-ID: Does the script exit when complete? If you?re running on a Linux based system and have root access you can use lsof to see what processes have with files open. (Or use the psutil Python package). From: Python-list on behalf of Mike Dewhirst Date: Tuesday, November 29, 2022 at 2:20 AM To: python-list at python.org Subject: Python script not letting go of files I have a script which fetches a production site directly from a Subversion repo using svn export It runs a bunch of commands by calling this little method ... def trycmd(cmd, log): retcode = -1 ret = f"Trying {cmd}" try: retcode = os.system(cmd) ret = f"\n{cmd} -ok-> {retcode}" except Exception as err: ret = f"\n{cmd} -fail-> {err}" log.write(remove_password(ret)) return retcode This is the fetching script (omitting variables at the top) which appears to be keeping a finger on files which Apache wants. with open(fetchlog, 'a') as log: ret = f"\n\nFetching {tag}" log.write(ret) cmd = f"sudo rm -Rf {site_root}" if trycmd(cmd, log) == 0: cmd = f"sudo svn export --force --username {usr} --password {pw} {svn_repo} {site_root}" if trycmd(cmd, log) == 0: # get any new dependencies cmd = f"sudo -H pip install -r {reqfile}" if trycmd(cmd, log) == 0: # run any migrations shipped from the repo cmd = f"sudo python3 {site_root}/manage.py migrate --noinput --settings={settings}" if trycmd(cmd, log) == 0: # shouldn't find anything cmd = f"sudo python3 {site_root}/manage.py makemigrations --noinput --settings={settings}" if trycmd(cmd, log) == 0: # should have been done already cmd = f"sudo python3 {site_root}/manage.py migrate --noinput --settings={settings}" if trycmd(cmd, log) == 0: # remove all static files from their Apache dir cmd = f"sudo rm -Rf {static_root}/*" if trycmd(cmd, log) == 0: # copy all static files to the Apache location cmd = f"sudo python3 {site_root}/manage.py collectstatic --noinput --settings={settings}" if trycmd(cmd, log) == 0: # set all permissions cmd = f"sudo {scripts}/perms_{host}.sh" if trycmd(cmd, log) == 0: cmd = "sudo service apache2 restart" if trycmd(cmd, log) == 0: ret = f"\nFinish {tag}\n\n" log.write(ret) else: print("Apache didn't restart") else: print("Didn't set permissions") else: print("Didn't collectstaic") else: print("Didn't delete static files") else: print("Didn't migrate 2") else: print("Didn't makemigration") else: print("Didn't migrate 1") else: print("Didn't install requirements") else: print("Didn't get source") else: print("Didn't remove site") exit() The problem I'm trying to fix is that after an Apache reload Apache seems hellbent on filling up its scoreboard and running out of resources. The kind folk on the Apache mailing list say something is hogging the workers. You can see the last operation above is an Apache restart. It should be an Apache reload. Reload however lets Apache run out of resources. Do any of you Python folks see any blunders in the above code along the lines of not letting go of py files or static assets? mod_wsgi is configured with 100% defaults. mod_mpm_event conf per advice from the Apache mailing list is ... ServerLimit 32 StartServers 16 MinSpareThreads 400 MaxSpareThreads 800 ThreadLimit 64 ThreadsPerChild 50 AsyncRequestWorkerFactor 2 MaxRequestWorkers 800 MaxConnectionsPerChild 0 Server Version: Apache/2.4.52 (Ubuntu 2022.04) OpenSSL/3.0.2 mod_wsgi/4.9.0 Python/3.10 Server MPM: event Server Built: 2022-09-30T04:09:50 DigitalOcean droplet 8BG RAM and lightly loaded. Many thanks for any hints. Cheers Mike -- Signed email is an absolute defence against phishing. This email has been signed with my private key. If you import my public key you can automatically decrypt my signature and be sure it came from me. Just ask and I'll send it to you. Your email software can handle signing. From PythonList at DancesWithMice.info Tue Nov 29 12:16:05 2022 From: PythonList at DancesWithMice.info (dn) Date: Wed, 30 Nov 2022 06:16:05 +1300 Subject: NEO6 GPS with Py PICO with micropython In-Reply-To: References: Message-ID: On 30/11/2022 00.53, KK CHN wrote: > List , > I am following this tutorial to get latitude and longitude data using > NEO6 GPS module and Py PICO to read the GPS data from the device. > > I followed the code specified in this tutorial. > https://microcontrollerslab.com/neo-6m-gps-module-raspberry-pi-pico-micropython/ > > I have installed thony IDE in my Desktop(windows PC) and run the code > after the devices all connected and using USB cable connected to my PC. > > When I ran the program I am able to see the output of latitude and > longitude in the console of thony IDE. But between certain intervals of a > few seconds I am getting the latitude and longitude data ( its printing > GPS data not found ?? ) in the python console. > > The satellite count from the $GGPA output showing 03 .. > and the GPS data not found repeating randomly for intervals of seconds. > Any hints why it is missing the GPS data (randomly) ?? > > PS:- The GPS device I placed outside my window and connected to the PC > with a USB cable from the PICO module. GPS device NEO6 light (Red LED > ) blinking even though the " GPS data not found" messages in th python > console. > > Any hints ?? most welcome If it works (correctly*) some of the time, and there is only one look-up in the code, it doesn't really sound like a problem with the Python. * is it? Does the unit also report the number of satellites it can 'see'? Is it always more than one? Other data not-discussed: change of cable, reducing length of cable, ... -- Regards, =dn From mats at wichmann.us Tue Nov 29 12:34:29 2022 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 29 Nov 2022 10:34:29 -0700 Subject: Setupfailure In-Reply-To: References: Message-ID: <5957924f-399c-f72b-91bf-6370a625136f@wichmann.us> On 11/28/22 07:12, Kelvin Buuri wrote: > May python failed to install Was there an antual question here? If so, give details when re-asking. From gheskett at shentel.net Tue Nov 29 16:59:02 2022 From: gheskett at shentel.net (gene heskett) Date: Tue, 29 Nov 2022 16:59:02 -0500 Subject: NEO6 GPS with Py PICO with micropython In-Reply-To: References: Message-ID: On 11/29/22 06:56, KK CHN wrote: > List , > I am following this tutorial to get latitude and longitude data using > NEO6 GPS module and Py PICO to read the GPS data from the device. > > I followed the code specified in this tutorial. > https://microcontrollerslab.com/neo-6m-gps-module-raspberry-pi-pico-micropython/ > > I have installed thony IDE in my Desktop(windows PC) and run the code > after the devices all connected and using USB cable connected to my PC. > > When I ran the program I am able to see the output of latitude and > longitude in the console of thony IDE. But between certain intervals of a > few seconds I am getting the latitude and longitude data ( its printing > GPS data not found ?? ) in the python console. > > The satellite count from the $GGPA output showing 03 .. > and the GPS data not found repeating randomly for intervals of seconds. > Any hints why it is missing the GPS data (randomly) ?? > > PS:- The GPS device I placed outside my window and connected to the PC > with a USB cable from the PICO module. GPS device NEO6 light (Red LED > ) blinking even though the " GPS data not found" messages in th python > console. > > Any hints ?? most welcome > > Yours, > Krishane From a retired broadcast engineer, intimately familiar with vswr: std, wire only usb cables can get to acting flaky at 5 feet. If the cable to the receiver is more than that, a higher quality cable may be required. The better cable will probably have active electronics in the molded on ends that treats the cable as a transmission line, Which if done right can go as much as ten meters at usb2 speeds. Cheers, Gene Heskett. -- "There are four boxes to be used in defense of liberty: soap, ballot, jury, and ammo. Please use in that order." -Ed Howdershelt (Author, 1940) If we desire respect for the law, we must first make the law respectable. - Louis D. Brandeis Genes Web page From johan.gunnarsson at med.lu.se Tue Nov 29 05:06:03 2022 From: johan.gunnarsson at med.lu.se (Johan Gunnarsson) Date: Tue, 29 Nov 2022 10:06:03 +0000 Subject: Bug report - Python 3.10 from Microsoft Store - IDLE won't start Message-ID: <75024091d7ff46169db73e6261447e96@med.lu.se> Hello, IDLE won't start if ver. 3.10 is installed from Microsoft Store. 3.9 works just fine. Thanks in advance! Johan Gunnarsson Lunds universitet Medicinska fakulteten Bibliotek & IKT Box 118, 221 00 Lund Bes?ksadress: S?lvegatan 19, 221 84 Lund Telefon: +46 46 222 18 23 www.medicin.lu.se From info at cmcc.it Tue Nov 29 08:57:18 2022 From: info at cmcc.it (CMCC Foundation) Date: Tue, 29 Nov 2022 14:57:18 +0100 Subject: Job positions at CMCC Foundation, Italy - Advanced Scientific Computing - ASC Division In-Reply-To: References: Message-ID: /Please, feel free to circulate //to anyone you think may be interested/ /Apologies for cross-posting / /-- / _ _ The CMCC Foundation is a scientific research center on climate change and its interactions with the environment, the society, the world of business and policy makers. Our work aims to stimulate sustainable growth, protect the environment and develop strategies for the adaptation and mitigation of climate change. Our Division of Advanced Scientific Computing (ASC Division) is considering the possibility to hire a talented and proactive:_ _ _ _ *- POST DEGREE-Data Science skills*_ _ [Job Opening cod.12402] *Deadline: December 16th, 2022* More details and info about HOW TO APPLY: https://cmccfoundation.applytojob.com/apply/gAKKckG5zF/12402-POST-DEGREEData-Science-Skills _ _ *- POST DEGREE-HPC skills*_ _[Job Opening cod.12403] *Deadline: December 16th, 2022* More details and info about HOW TO APPLY: https://cmccfoundation.applytojob.com/apply/CUso6CnoRt/12403-POST-DEGREEHPC-Skills _ _ *- POST DEGREE-Machine Learning skills *[Job Opening cod.12404] *Deadline: December 16th, 2022* More details and info about HOW TO APPLY: https://cmccfoundation.applytojob.com/apply/c4A2a92Co7/12404-POST-DEGREEMachine-Learning-Skills FOR FURTHER INFORMATION ON CMCC JOB OPPORTUNITIES, PLEASE VISIT OUR WEBSITE: https://www.cmcc.it/work-with-us -- Fondazione CMCC Centro Euro-Mediterraneo sui Cambiamenti Climatici Via Marco Biagi, 5 - 73100 Lecce, Italy info at cmcc.it - www.cmcc.it From bowman at montana.com Tue Nov 29 12:13:50 2022 From: bowman at montana.com (rbowman) Date: 29 Nov 2022 17:13:50 GMT Subject: NEO6 GPS with Py PICO with micropython References: Message-ID: On Tue, 29 Nov 2022 17:23:31 +0530, KK CHN wrote: > When I ran the program I am able to see the output of latitude and > longitude in the console of thony IDE. But between certain intervals > of a few seconds I am getting the latitude and longitude data ( its > printing GPS data not found ?? ) in the python console. I would guess the 8 seconds in timeout = time.time() + 8 is too short. Most GPS receivers repeat a sequence on NMEA sentences and the code is specifically looking for $GPGGA. Add print(buff) to see the sentences being received. I use the $GPRMC since I'm interested in the position, speed, and heading. It's a different format but if you only want lat/lon you could decode it in a similar fashion as the $GPGGA. From gweatherby at uchc.edu Tue Nov 29 17:46:12 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Tue, 29 Nov 2022 22:46:12 +0000 Subject: Python script not letting go of files In-Reply-To: References: Message-ID: "Weatherby,Gerard" writes: >Do any of you Python folks see any blunders in the above code along the >lines of not letting go of py files or static assets? Er, no, I just replied to the original poster. From miked at dewhirst.com.au Tue Nov 29 20:45:37 2022 From: miked at dewhirst.com.au (Mike Dewhirst) Date: Wed, 30 Nov 2022 12:45:37 +1100 Subject: Python script not letting go of files In-Reply-To: References: Message-ID: <6a4ef333-8c56-7d3f-b16e-7896e901b54d@dewhirst.com.au> Stefan Thank you. I should have said this has been working fine for years and years until Ubuntu 2022.04 on a new droplet running Apache/2.4.52 I will refactor it one day - especially if the script is implicated. But I think I have to learn how to use lsof first! Cheers Mike On 30/11/2022 1:44 am, Stefan Ram wrote: > "Weatherby,Gerard" writes: >> Do any of you Python folks see any blunders in the above code along the >> lines of not letting go of py files or static assets? > No, sorry. But I had to refactor it. > > *Warning* The following code is not intended to be executed, > it is just intended to be read by humans. It was not tested > and, therefore, it probably contains errors. If executed, it > may cause destruction such as deletions of files etc. Stefan > Ram (I) does not claim any copyright for his modifications. > > def attempt( task, command ): > if trycmd( command, log ): > print( f'task "{task}" failed.' ) > return False # failure > else: > return True # success > > def main(): > with open( fetchlog, 'a' )as log_: > global log > log = log_ > remove_site() > del log > > def remove_site(): > log.write( f"\n\nFetching {tag}" ) > if attempt( "remove site", f"sudo rm -Rf {site_root}", log ): > get_source() > > def get_source(): > if attempt( "get source", f"sudo svn export --force --username {usr} --password {pw} {svn_repo} {site_root}" ): > install_requirements() > > def install_requirements(): > if attempt( "install requirements", f"sudo -H pip install -r {reqfile}" ): > repo_migrations() > > def repo_migrations(): > if attempt( "run any migrations shipped from the repo", f"sudo python3 {site_root}/manage.py migrate --noinput --settings={settings}" ): > makemigrations() > > def makemigrations(): > # shouldn't find anything > if attempt( "makemigrations", f"sudo python3 {site_root}/manage.py makemigrations --noinput --settings={settings}" ): > migrate() > > def migrate(): > # should already be done > if attempt( "migrate 2", f"sudo python3 {site_root}/manage.py migrate --noinput --settings={settings}" ): > remove_static() > > def remove_static(): > if attempt( "remove all static files from their Apache dir", f"sudo rm -Rf {static_root}/*" ): > copy_static() > > def copy_static(): > if attempt( "copy all static files to the Apache location", f"sudo python3 {site_root}/manage.py collectstatic --noinput --settings={settings}" ): > set_permissions() > > def set_permissions(): > if attempt( "set all permissions", f"sudo {scripts}/perms_{host}.sh" ): > service_restart() > > def service_restart(): > if attempt( "restart of Apache service", f"sudo service apache2 restart" ): > log_success() > > def log_success(): > log.write( f"\nFinish {tag}\n\n" ) > > # main() > # sys.exit() > > -- Signed email is an absolute defence against phishing. This email has been signed with my private key. If you import my public key you can automatically decrypt my signature and be sure it came from me. Just ask and I'll send it to you. Your email software can handle signing. -------------- next part -------------- A non-text attachment was scrubbed... Name: OpenPGP_signature Type: application/pgp-signature Size: 495 bytes Desc: OpenPGP digital signature URL: From gvanem at yahoo.no Wed Nov 30 04:51:27 2022 From: gvanem at yahoo.no (Gisle Vanem) Date: Wed, 30 Nov 2022 10:51:27 +0100 Subject: pip issue References: Message-ID: Hello list. I have an issue with 'pip v. 22.3.1'. On any 'pip install' command I get warning like this: c:\> pip3 install asciinema WARNING: Ignoring invalid distribution -arkupsafe (f:\gv\python310\lib\site-packages) WARNING: Ignoring invalid distribution -arkupsafe (f:\gv\python310\lib\site-packages) Collecting asciinema Downloading asciinema-2.2.0-py3-none-any.whl (92 kB) ... Otherwise no issues. But where is this text "-arkupsafe" stored and how to get rid it it? I've searched through all of my .pth files and found no such string. I assume this is an entry for an orphaned package "MarkupSafe" since a 'pip list | grep markup' will list 'MarkupSafe 2.1.1'. -- --gv From kkchn.in at gmail.com Wed Nov 30 05:58:40 2022 From: kkchn.in at gmail.com (KK CHN) Date: Wed, 30 Nov 2022 16:28:40 +0530 Subject: NEO6 GPS with Py PICO with micropython In-Reply-To: References: Message-ID: List, Just commented the // gpsModule.readline() in the while loop, ( refer the link https://microcontrollerslab.com/neo-6m-gps-module-raspberry-pi-pico-micropython/ ) while True: # gpsModule.readline() // This line commented out and the "GPS not found message disappeared". buff = str(gpsModule.readline()) parts = buff.split(',') The GPS not found error which appears intermittently in the output python console for few seconds ( say 7 to 8 seconds its printing the lines " GPS data not found" ) now disappears. Any thoughts? How the above line comment made it vanish the "GPS data not found" error output. Krishane On Wed, Nov 30, 2022 at 3:58 AM rbowman wrote: > On Tue, 29 Nov 2022 17:23:31 +0530, KK CHN wrote: > > > > When I ran the program I am able to see the output of latitude and > > longitude in the console of thony IDE. But between certain intervals > > of a few seconds I am getting the latitude and longitude data ( its > > printing GPS data not found ?? ) in the python console. > > I would guess the 8 seconds in > > timeout = time.time() + 8 > > is too short. Most GPS receivers repeat a sequence on NMEA sentences and > the code is specifically looking for $GPGGA. Add > > print(buff) > > to see the sentences being received. I use the $GPRMC since I'm interested > in the position, speed, and heading. It's a different format but if you > only want lat/lon you could decode it in a similar fashion as the $GPGGA. > > -- > https://mail.python.org/mailman/listinfo/python-list > From barry at barrys-emacs.org Wed Nov 30 06:51:33 2022 From: barry at barrys-emacs.org (Barry Scott) Date: Wed, 30 Nov 2022 11:51:33 +0000 Subject: NEO6 GPS with Py PICO with micropython In-Reply-To: References: Message-ID: > On 30 Nov 2022, at 10:58, KK CHN wrote: > > List, > > Just commented the // gpsModule.readline() in the while loop, ( > refer the link > https://microcontrollerslab.com/neo-6m-gps-module-raspberry-pi-pico-micropython/ > ) > > > while True: # gpsModule.readline() // This line commented out and the "GPS > not found message disappeared". buff = str(gpsModule.readline()) parts = > buff.split(',') > > > The GPS not found error which appears intermittently in the output python > console for few seconds ( say 7 to 8 seconds its printing the lines " > GPS data not found" ) now disappears. > > Any thoughts? How the above line comment made it vanish the "GPS data > not found" error output. Show the full text of the error that you see. Is it a traceback? What I would do then is read the code that raised the "GPS data not found" error and find out why it reports that error. Barry p.s. Please reply in line, do not top post. > > Krishane > > On Wed, Nov 30, 2022 at 3:58 AM rbowman wrote: > >> On Tue, 29 Nov 2022 17:23:31 +0530, KK CHN wrote: >> >> >>> When I ran the program I am able to see the output of latitude and >>> longitude in the console of thony IDE. But between certain intervals >>> of a few seconds I am getting the latitude and longitude data ( its >>> printing GPS data not found ?? ) in the python console. >> >> I would guess the 8 seconds in >> >> timeout = time.time() + 8 >> >> is too short. Most GPS receivers repeat a sequence on NMEA sentences and >> the code is specifically looking for $GPGGA. Add >> >> print(buff) >> >> to see the sentences being received. I use the $GPRMC since I'm interested >> in the position, speed, and heading. It's a different format but if you >> only want lat/lon you could decode it in a similar fashion as the $GPGGA. >> >> -- >> https://mail.python.org/mailman/listinfo/python-list >> > -- > https://mail.python.org/mailman/listinfo/python-list > From luca72.bertolotti at gmail.com Wed Nov 30 06:56:43 2022 From: luca72.bertolotti at gmail.com (luca72.b...@gmail.com) Date: Wed, 30 Nov 2022 03:56:43 -0800 (PST) Subject: Vb6 type to python Message-ID: Hello i have a byte file, that fill a vb6 type like: Type prog_real codice As String * 12 'hsg denom As String * 24 'oo codprof As String * 12 'ljio note As String * 100 programmer As String * 11 Out As Integer b_out As Byte 'TRUE = Sec FALSE= mm asse_w As Byte '3.zo Asse --> 0=Z 1=W numpassi As Integer 'put len As Long 'leng p(250) As passo_pg vd(9) As Byte 'vel. qUscita(9) As Integer 'quote l_arco As Long 'reserved AxDin As Byte 'dime End Type How i can convert to python From dieter at handshake.de Wed Nov 30 12:06:59 2022 From: dieter at handshake.de (Dieter Maurer) Date: Wed, 30 Nov 2022 18:06:59 +0100 Subject: pip issue In-Reply-To: References: Message-ID: <25479.36275.474665.147728@ixdm.fritz.box> Gisle Vanem wrote at 2022-11-30 10:51 +0100: >I have an issue with 'pip v. 22.3.1'. On any >'pip install' command I get warning like this: > c:\> pip3 install asciinema > WARNING: Ignoring invalid distribution -arkupsafe (f:\gv\python310\lib\site-packages) > WARNING: Ignoring invalid distribution -arkupsafe (f:\gv\python310\lib\site-packages) > Collecting asciinema > Downloading asciinema-2.2.0-py3-none-any.whl (92 kB) > ... > >Otherwise no issues. But where is this text "-arkupsafe" stored >and how to get rid it it? I've searched through all of my .pth >files and found no such string. Have you looked at the content of the folder mentioned in the warnings (e.g. `...\site-packages`). From gvanem at yahoo.no Wed Nov 30 13:49:43 2022 From: gvanem at yahoo.no (Gisle Vanem) Date: Wed, 30 Nov 2022 19:49:43 +0100 Subject: pip issue In-Reply-To: <25479.36275.474665.147728@ixdm.fritz.box> References: <25479.36275.474665.147728@ixdm.fritz.box> Message-ID: <36b1b452-9dd6-a1cd-acff-e4488bf1737f@yahoo.no> Dieter Maurer wrote: >> Otherwise no issues. But where is this text "-arkupsafe" stored >> and how to get rid it it? I've searched through all of my .pth >> files and found no such string. > > Have you looked at the content of the folder mentioned > in the warnings (e.g. `...\site-packages`). I had 2 folders named: site-packages\~arkupsafe\ site-packages\~arkupsafe-2.1.1.dist-info\ Removing those, the problem was gone. So perhaps this tilde '~' means something special for pip? -- --gv From list1 at tompassin.net Wed Nov 30 14:34:25 2022 From: list1 at tompassin.net (Thomas Passin) Date: Wed, 30 Nov 2022 14:34:25 -0500 Subject: pip issue In-Reply-To: <36b1b452-9dd6-a1cd-acff-e4488bf1737f@yahoo.no> References: <25479.36275.474665.147728@ixdm.fritz.box> <36b1b452-9dd6-a1cd-acff-e4488bf1737f@yahoo.no> Message-ID: <64042ba5-6d2c-795d-cddb-dd6c143abc54@tompassin.net> On 11/30/2022 1:49 PM, Gisle Vanem via Python-list wrote: > Dieter Maurer wrote: > >>> Otherwise no issues. But where is this text "-arkupsafe" stored >>> and how to get rid it it? I've searched through all of my .pth >>> files and found no such string. >> >> Have you looked at the content of the folder mentioned >> in the warnings (e.g. `...\site-packages`). > > I had 2 folders named: > ? site-packages\~arkupsafe\ > ? site-packages\~arkupsafe-2.1.1.dist-info\ > > Removing those, the problem was gone. > > So perhaps this tilde '~' means something special > for pip? I've seen things like this before. Those directories - the ones starting with "~" - seem to be used for backing up a package (it could a dependency that is required by the package you are installing) before installing a newer version. I think that somehow pip applies wrong file permissions that prevent it from removing the backup directory at the end. The issue does not affect the successful installation of the newer version. I have been able to remove these directories myself afterwards with no problems. From nospam at dfs.com Wed Nov 30 13:07:17 2022 From: nospam at dfs.com (DFS) Date: Wed, 30 Nov 2022 13:07:17 -0500 Subject: Vb6 type to python In-Reply-To: References: Message-ID: On 11/30/2022 6:56 AM, luca72.b... at gmail.com wrote: > Hello i have a byte file, that fill a vb6 type like: > Type prog_real > codice As String * 12 'hsg > denom As String * 24 'oo > codprof As String * 12 'ljio > note As String * 100 > programmer As String * 11 > Out As Integer > b_out As Byte 'TRUE = Sec FALSE= mm > asse_w As Byte '3.zo Asse --> 0=Z 1=W > numpassi As Integer 'put > len As Long 'leng > p(250) As passo_pg > vd(9) As Byte 'vel. > qUscita(9) As Integer 'quote > l_arco As Long 'reserved > AxDin As Byte 'dime > End Type > > How i can convert to python You don't need to declare variable types in Python. I don't do Python OO so someone else can answer better, but a simple port of your VB type would be a python class definition: class prog_real: codice, denom, codprof, note, programmer AxDin, b_out, asse_w, vd, Out, numpassi, qUscita len, l_arco, p important: at some point you'll have trouble with a variable named 'len', which is a Python built-in function. For a visual aid you could label the variables by type and assign an initial value, if that helps you keep track in your mind. class prog_real: # strings codice, denom, codprof, note, programmer = '', '', '', '', '' # bytes AxDin, b_out, asse_w, vd = 0, 0, 0, 0 # ints Out, numpassi, qUscita = 0, 0, 0 # longs len, l_arco = 0, 0 # misc p = '' But it's not necessary. To restrict the range of values in the variables you would have to manually check them each time before or after they change, or otherwise force some kind of error/exception that occurs when the variable contains data you don't want. # assign values prog_real.codice = 'ABC' print('codice: ' + prog_real.codice) prog_real.codice = 'DEF' print('codice: ' + prog_real.codice) prog_real.codice = 123 print('codice: ' + str(prog_real.codice)) And as shown in the last 2 lines, a variable can accept any type of data, even after it's been initialized with a different type. b = 1 print(type(b)) b = 'ABC' print(type(b)) Python data types: https://www.digitalocean.com/community/tutorials/python-data-types A VB to python program: https://vb2py.sourceforge.net From nospam at dfs.com Wed Nov 30 14:03:31 2022 From: nospam at dfs.com (DFS) Date: Wed, 30 Nov 2022 14:03:31 -0500 Subject: Vb6 type to python In-Reply-To: References: Message-ID: <6ONhL.7352$z011.6737@fx11.iad> On 11/30/2022 1:07 PM, DFS wrote: > On 11/30/2022 6:56 AM, luca72.b... at gmail.com wrote: > > I don't do Python OO so someone else can answer better, but a simple > port of your VB type would be a python class definition: > > class prog_real: > ??? codice, denom, codprof, note, programmer > ??? AxDin, b_out, asse_w, vd, Out, numpassi, qUscita > ??? len, l_arco, p Sorry for bad advice - that won't work. The other class definition that initializes the variables does work: class prog_real: # strings codice, denom, codprof, note, programmer = '', '', '', '', '' # bytes AxDin, b_out, asse_w, vd = 0, 0, 0, 0 # ints Out, numpassi, qUscita = 0, 0, 0 # longs len, l_arco = 0, 0 # misc p = '' From brgl at bgdev.pl Wed Nov 30 15:23:41 2022 From: brgl at bgdev.pl (Bartosz Golaszewski) Date: Wed, 30 Nov 2022 21:23:41 +0100 Subject: python: setup.py: how NOT to install C extensions used only by tests Message-ID: I have a module that has a tests/ directory which contains a C extension that's only used by test cases. I don't want to install it. I'm building it as a setuptools.Extension() added to setup() using the ext_modules argument. The test directory is not added to setup's packages argument. Even though none of the python sources from the tests/ directory gets installed when running setup.py install, the extension binary (and nothing else) is installed into site-packages/tests/. How can I prohibit setuptools from doing it? Best Regards, Bartosz Golaszewski From gweatherby at uchc.edu Wed Nov 30 15:12:16 2022 From: gweatherby at uchc.edu (Weatherby,Gerard) Date: Wed, 30 Nov 2022 20:12:16 +0000 Subject: Vb6 type to python In-Reply-To: References: Message-ID: Look at struct package: https://docs.python.org/3/library/struct.html From: Python-list on behalf of luca72.b... at gmail.com Date: Wednesday, November 30, 2022 at 11:48 AM To: python-list at python.org Subject: Vb6 type to python *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** Hello i have a byte file, that fill a vb6 type like: Type prog_real codice As String * 12 'hsg denom As String * 24 'oo codprof As String * 12 'ljio note As String * 100 programmer As String * 11 Out As Integer b_out As Byte 'TRUE = Sec FALSE= mm asse_w As Byte '3.zo Asse --> 0=Z 1=W numpassi As Integer 'put len As Long 'leng p(250) As passo_pg vd(9) As Byte 'vel. qUscita(9) As Integer 'quote l_arco As Long 'reserved AxDin As Byte 'dime End Type How i can convert to python -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!ky-bqK3l3Sbj0O_n3_x6Yo2wFaF5xABKKYgjbIPH49rdLZ2W_vQlW2gGbSQ7uRplRBZn_wS4h4evqcYQZaR1aSNJaTXnRQ$ From PythonList at DancesWithMice.info Wed Nov 30 15:46:29 2022 From: PythonList at DancesWithMice.info (dn) Date: Thu, 1 Dec 2022 09:46:29 +1300 Subject: AuckPUG's last (virtual) Coding Evening for 2022 Message-ID: <158942ff-7f73-9ff3-6200-b9f6fd973f5e@DancesWithMice.info> Wednesday 7 December, 1800 for 1830 NZDT/0530 UTC We will continue the "Crafting Software" series, gradually developing Monty's Python Supermarket. The evening's aim is to move the product-prices from their hard-coded dict[ionary] into a flat-file (introducing Python I/O), and then to do same with the Accountant's favorite tool - a Workbook or Spreadsheet (Python's library to interact with LibreOffice-Calc and MS-Excel). You can treat it as a code-along-at-home exercise or just watch the fun. The Web-conference URL and a QuickStart Guide (for those who didn't attend last time) will be provided upon RSVP. All welcome! https://www.meetup.com/nzpug-auckland/events/hgxmwsydcqbkb/ The Smart Iterators Challenge has finished (after five Challenge-weeks). Congratulations to all who participated (and if you didn't have time to complete, you're welcome to continue at your own pace). Particular pride for those who hung-in-there right to the end, making astute discoveries and learning ideas which have already been adopted into professional-practice. Well done! A "Retrospective, Review, and Reflection Wrap-up" document is available to participants/upon request. Advice and assistance will continue to be available - please email off-list. -- Regards, =dn