From jonas.thornvall at gmail.com Tue Mar 1 00:40:03 2016 From: jonas.thornvall at gmail.com (jonas.thornvall at gmail.com) Date: Mon, 29 Feb 2016 21:40:03 -0800 (PST) Subject: Condition fullfilled to early but only "sometimes" Message-ID: <11915658-6fcd-4f83-94ba-5f5dceb3af11@googlegroups.com> I've been looking at the code for two days so i am a bit crosseyed. If anyone could help me set the condition so the loop catch the last pair/pairs, it is kind of weird that it succeed sometimes and break to early and report fail others. I would be very greatful if anyone can see why it break to early and return fail. Although it is clearly a succes looking at the last remaining pair none connected pair.It should report fail for the network permutations that stall due to link exhausting, but not stall creating last pair. It just a minor bug due to some condition that i just not get. Have a go 5 munutes maybe someone catch the faulthy condition. http://jt.node365.se/mydebug1.html From tjreedy at udel.edu Tue Mar 1 01:52:24 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 1 Mar 2016 01:52:24 -0500 Subject: Correct IDLE usage (was Reason for not allowing import twice but allowing reload()) In-Reply-To: <075122af-1a9c-44b6-97bb-521ebcb3e4ae@googlegroups.com> References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> <075122af-1a9c-44b6-97bb-521ebcb3e4ae@googlegroups.com> Message-ID: On 2/29/2016 7:42 AM, Rustom Mody wrote: > Is import needed at all when trying out in Idle? ... > So it does appear that > 1. import not necessary with(in) idle > 2. However import and f5 (ie is run as main) are different > > May some idle experts elaborate on this? Whats the idle idiom of import-ing? Rustom, since I know that you are not a rank beginner, I have trouble understanding what you are asking. F5 when editing foo.py is equivalent to running "python -i foo.py" on a command line while 'in' the directory containing foo.py. In both cases, foo.py is run as a main module, with __name__ == '__main__'. The difference is that F5 runs foo.py under IDLE supervision, with results going into and interactive inputs coming from IDLE shell instead of the console interpreter. Imports are used in a module to access objects within the imported module. -- Terry Jan Reedy From tjreedy at udel.edu Tue Mar 1 02:04:35 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 1 Mar 2016 02:04:35 -0500 Subject: Reason for not allowing import twice but allowing reload() In-Reply-To: <5c8e3283-2013-4f68-87b8-6311ccee64a3@googlegroups.com> References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> <5c8e3283-2013-4f68-87b8-6311ccee64a3@googlegroups.com> Message-ID: On 2/29/2016 8:22 AM, alien2utoo at gmail.com wrote: > Hello Rustom, > > F5 in Idle restarts the Python interpreter (that's what my impression is). More exactly, IDLE runs user code in a separate process from the one that runs the IDLE gui. Restarting means that the existing user process is terminated and a new one started. This is easier than trying to 'clean up' the existing process. If you start python with '> python' in a terminal, then restarting the interactive interpreter means '>>> quit' at the interactive prompt followed by "> python" in the console. You do the equivalent in IDLE Shell with 'control-F6' or 'Shell -> Restart Shell. F5 when editing path/file.py replaces the command 'python' with 'cd path' followed by 'python -i file.py' Maybe I should add something to the IDLE doc for people familiar with using python in a console. (Most beginners are not.) > Whatever you have done earlier at Idle prompt (in Idle session) > before F5 is gone after F5. Yes, the same as if you quit(). A change I would like to make sometime is to have F5 run the file is a new user process without killing the old one, so one does not loose work done in Shell. -- Terry Jan Reedy From ian.g.kelly at gmail.com Tue Mar 1 02:48:58 2016 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 1 Mar 2016 00:48:58 -0700 Subject: Condition fullfilled to early but only "sometimes" In-Reply-To: <11915658-6fcd-4f83-94ba-5f5dceb3af11@googlegroups.com> References: <11915658-6fcd-4f83-94ba-5f5dceb3af11@googlegroups.com> Message-ID: It's not at all clear what the problem is from your description. What is it that you expect the code to do? What is it doing instead that violates your expectation? Why are you asking for Javascript help on a Python mailing list? On Mon, Feb 29, 2016 at 10:40 PM, wrote: > I've been looking at the code for two days so i am a bit crosseyed. > If anyone could help me set the condition so the loop catch the last pair/pairs, it is kind of weird that it succeed sometimes and break to early and report fail others. > > I would be very greatful if anyone can see why it break to early and return fail. Although it is clearly a succes looking at the last remaining pair none connected pair.It should report fail for the network permutations that stall due to link exhausting, but not stall creating last pair. > > It just a minor bug due to some condition that i just not get. > Have a go 5 munutes maybe someone catch the faulthy condition. > > http://jt.node365.se/mydebug1.html > -- > https://mail.python.org/mailman/listinfo/python-list From anthony at cajuntechie.org Tue Mar 1 02:58:17 2016 From: anthony at cajuntechie.org (Anthony Papillion) Date: Tue, 1 Mar 2016 01:58:17 -0600 Subject: Sending an email with a binary attachment In-Reply-To: References: Message-ID: <56D54B99.2020206@cajuntechie.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 On 02/29/2016 11:13 AM, Chris Angelico wrote: > On Tue, Mar 1, 2016 at 4:08 AM, Peter Pearson > wrote: >> try: smtp.sendmail(message['From'], message['To'], >> message.as_string()) except: print "Message sending has failed" >> sys.exit(1) print "Message sending was successful" sys.exit(0) >> > > This is the problem, right here. Replace this code with: > > smtp.sendmail(message['From'], message['To'], message.as_string()) Hmm, I'm a bit confused. Are you saying that the problem is that I'm enclosing the code in a Try/Except block? Besides that, I don't see anything different. If it's the Try/Except block, how do I catch the exception it might generate if I'm not using the exception block? Thanks, Anthony -----BEGIN PGP SIGNATURE----- iQIbBAEBCgAGBQJW1UuZAAoJEAKK33RTsEsVdfoP+N/xBIMouhhS1pqInvd9wrk2 jCfjmk7aHQQOdSvtQjXEqdNUu6nPmvX9VRzqvs881bUZAx31usL7VnyzJsL89pZl PPrXG3WzEDkMaWmfZ45/irGwuP3Cpwkw3h7raDcvA/kV7+jLUBq//1kW7itofPh8 6xKJ9yCJ35vCS4LDhEeIbtMQXRe27QQXeFfi2VjFFRQRQeJlKf0nAd8sH/4q1fPa IVKy6lgZcDDzCzy0Ux9us8baUOgTjLIY81AKMXGUmXaUNLpDfF6n6RLRtj8fLcN5 sT37okHyRmK9LNwI1PzU8r2p7i3gweDXx4x9g6nqmi6OV8fm4suSd8VOWb8oF1Yb clQWSvSPE3GcnVaepcixIV1PCF53KsCHaPp63RZbKB3MiPuNTdQQi9Xm1Qfrt0UW uJiEzfGXavkNRYaShycMB6HJGfjIsCZH9wzf1/irCuhiy+kJbvQq9lhojWw/V0N3 TGwY0Sd/eWqtmcx+u449viDIfLZsJDjzXXsYV60JdZtsSsd5+Mud+vfOlv3s/oy0 EPnIzMJar5LGPghPuab8g7rcXim77hFxS7eLp4j9ugWgRPa8TRpiBb/wx2c8a2e0 122ZW8Fc7+9gxHxSCJdM7GIFChdN2IMogCkERAuTyo+dNP01Mv07eMvSA6JkgiN2 ZlSJ8M9UHRS7dplpJGE= =nxc8 -----END PGP SIGNATURE----- From rosuav at gmail.com Tue Mar 1 03:03:50 2016 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 1 Mar 2016 19:03:50 +1100 Subject: Sending an email with a binary attachment In-Reply-To: <56D54B99.2020206@cajuntechie.org> References: <56D54B99.2020206@cajuntechie.org> Message-ID: On Tue, Mar 1, 2016 at 6:58 PM, Anthony Papillion wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA512 > > On 02/29/2016 11:13 AM, Chris Angelico wrote: >> On Tue, Mar 1, 2016 at 4:08 AM, Peter Pearson >> wrote: >>> try: smtp.sendmail(message['From'], message['To'], >>> message.as_string()) except: print "Message sending has failed" >>> sys.exit(1) print "Message sending was successful" sys.exit(0) >>> >> >> This is the problem, right here. Replace this code with: >> >> smtp.sendmail(message['From'], message['To'], message.as_string()) > > Hmm, I'm a bit confused. Are you saying that the problem is that I'm > enclosing the code in a Try/Except block? Besides that, I don't see > anything different. If it's the Try/Except block, how do I catch the > exception it might generate if I'm not using the exception block? > That's exactly the difference. Why do you need to catch the exception? All you're doing is destroying all the information, rendering it down to a blunt "has failed". We've had several threads touching on this, recently. I'm going to say this in what might be taken as a rude way, but the emphasis is necessary: ** Folks, *stop catching exceptions* just to print failure messages and exit. You are shooting yourselves in the foot. ** You should catch exceptions if you can actually handle them, but if all you're doing is printing out a fixed message and aborting, delete that code. Less code AND a better result. ChrisA From jonas.thornvall at gmail.com Tue Mar 1 03:47:05 2016 From: jonas.thornvall at gmail.com (jonas.thornvall at gmail.com) Date: Tue, 1 Mar 2016 00:47:05 -0800 (PST) Subject: Condition fullfilled to early but only "sometimes" In-Reply-To: References: <11915658-6fcd-4f83-94ba-5f5dceb3af11@googlegroups.com> Message-ID: <56e98301-21e5-4387-a012-c1be45ebc1fa@googlegroups.com> Den tisdag 1 mars 2016 kl. 08:49:57 UTC+1 skrev Ian: > It's not at all clear what the problem is from your description. What > is it that you expect the code to do? What is it doing instead that > violates your expectation? Why are you asking for Javascript help on a > Python mailing list? > > On Mon, Feb 29, 2016 at 10:40 PM, wrote: > > I've been looking at the code for two days so i am a bit crosseyed. > > If anyone could help me set the condition so the loop catch the last pair/pairs, it is kind of weird that it succeed sometimes and break to early and report fail others. > > > > I would be very greatful if anyone can see why it break to early and return fail. Although it is clearly a succes looking at the last remaining pair none connected pair.It should report fail for the network permutations that stall due to link exhausting, but not stall creating last pair. > > > > It just a minor bug due to some condition that i just not get. > > Have a go 5 munutes maybe someone catch the faulthy condition. > > > > http://jt.node365.se/mydebug1.html > > -- > > https://mail.python.org/mailman/listinfo/python-list The program creates search for uniform networks, that is x nodes each with y links. Only a subset of permutations possible "easiest found out with pen and paper". So to the left is the node and to the right the nodes it links to. When you run new network, sometimes it is full every node have x links, you create a uniform network. But often ir reports fail the links was exhausted and you stuck into a loop, that i fortunatily have the conditions to break. But it *sometimes* break to early when there is still one or two pairs that would had worked. Not it is easy to make a fix for those, but it certainly would be more beautiful setting the correct condition. function createLinks() { var i = 0; var j = 0; while(i < nodes) { // This see so that links already generated accounted for if one link than j j = arr[i].nodelinks.length; stupid = nodes - 1; temparr = new Array(); while(j < links) { dublett = false; // Onlygenerate random values bigger than "i" else all links exhausted if(i == 0) { aLink = Math.floor(Math.random() * (nodes - 1)); aLink ++ ; } else { aLink = Math.floor(Math.random() * (stupid - i)) + i + 1; } if (aLink == nodes)aLink -- ; if (temparr[0] == null) { temparr[0] = aLink; } for(k = 0; k < arr[i].nodelinks.length; k ++ ) { if(aLink == arr[i].nodelinks[k]) { dublett = true; } } inmylist = false; var t = 0; for(var m = 0; m < temparr.length; m ++ ) { if(temparr[m] == aLink) { inmylist = true; } } if (inmylist == false) { temparr[temparr.length] = aLink; } else { inmylist = false } scope = (nodes - 1) - i; if (temparr.length >= scope) { myboolean = false; return myboolean; } if(dublett == false && arr[aLink].nroflinks < links) { arr[i].nodelinks[arr[i].nodelinks.length] = aLink; arr[aLink].nodelinks[arr[aLink].nodelinks.length] = i; arr[i].nroflinks ++ ; arr[aLink].nroflinks ++ ; j ++ ; } } i ++ ; } myboolean = true; return myboolean; } From __peter__ at web.de Tue Mar 1 03:56:56 2016 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Mar 2016 09:56:56 +0100 Subject: Request More Help With XBM Image References: <8rKdnb6SKYLRIEnLnZ2dnUU7-f3NnZ2d@giganews.com> Message-ID: Wildman via Python-list wrote: > I want to take an image file, convert it to XBM format and > display it. Thanks to Mr. Otten I can open and display the > XBM image without any problems. The script first calls an > external program for the image conversion then I can open > and display it. Of course, I am left with the XBM file that > needs to be deleted. It seemed to me to be a better approach > to use stdout and pipe thereby eliminating the XBM file > altogether. Here is code I have so far but I'm not sure > what to do next... > > convert = "convert " + fileName + " -resize 48x48! -threshold 55% xbm:-" > p = subprocess.Popen([convert], stdout=subprocess.PIPE, shell=True) > xbmFile, err = p.communicate() Why would you need a shell? > The variable fileName contains the image file path and name. > The variable convert contains the complete command. The last > argument in the command tells the convert utility to covert > to an XBM and to direct the output to stdout. After the above > code runs xbmFile contains the actual image, which is plain > text. (X BitMap (XBM) is a plain text binary image format.) > > My question is how do I take the xbmFile variable and convert > it to an image object that can be displayed? The technique > for displaying an image from a file does not work or at least > I have not been able to get it to work. I think Image.open() accepts a file-like object, so import io ... command = [ "convert", fileName, "-resize", "48x48!", "-threshold", "55%", "xbm:-"] p = subprocess.Popen(command, stdout=subprocess.PIPE) xbmFile, err = p.communicate() openImage = Image.open(io.BytesIO(xbmFile)) should work. From jonas.thornvall at gmail.com Tue Mar 1 03:56:59 2016 From: jonas.thornvall at gmail.com (jonas.thornvall at gmail.com) Date: Tue, 1 Mar 2016 00:56:59 -0800 (PST) Subject: Condition fullfilled to early but only "sometimes" In-Reply-To: References: <11915658-6fcd-4f83-94ba-5f5dceb3af11@googlegroups.com> Message-ID: <583ade62-8852-49f0-b148-6e407e1f4b47@googlegroups.com> Den tisdag 1 mars 2016 kl. 08:49:57 UTC+1 skrev Ian: > It's not at all clear what the problem is from your description. What > is it that you expect the code to do? What is it doing instead that > violates your expectation? Why are you asking for Javascript help on a > Python mailing list? > > On Mon, Feb 29, 2016 at 10:40 PM, wrote: > > I've been looking at the code for two days so i am a bit crosseyed. > > If anyone could help me set the condition so the loop catch the last pair/pairs, it is kind of weird that it succeed sometimes and break to early and report fail others. > > > > I would be very greatful if anyone can see why it break to early and return fail. Although it is clearly a succes looking at the last remaining pair none connected pair.It should report fail for the network permutations that stall due to link exhausting, but not stall creating last pair. > > > > It just a minor bug due to some condition that i just not get. > > Have a go 5 munutes maybe someone catch the faulthy condition. > > > > http://jt.node365.se/mydebug1.html > > -- > > https://mail.python.org/mailman/listinfo/python-list Here is example output and as you can see there is no reason to not create the last pair, the link is not a copy it should be created but condition somehow wrong *sometimes*. Hurray failed generate network ***not quite if single pair two nodes missing 0'st NODE Links-> 7,3,5 1'st NODE Links-> 4,6,3 2'st NODE Links-> 5,9,3 3'st NODE Links-> 0,1,2 4'st NODE Links-> 1,8,5 5'st NODE Links-> 0,2,4 6'st NODE Links-> 1,7,9 7'st NODE Links-> 0,6,8 8'st NODE Links-> 4,7 9'st NODE Links-> 2,6 From jonas.thornvall at gmail.com Tue Mar 1 04:06:29 2016 From: jonas.thornvall at gmail.com (jonas.thornvall at gmail.com) Date: Tue, 1 Mar 2016 01:06:29 -0800 (PST) Subject: Condition fullfilled to early but only "sometimes" In-Reply-To: References: <11915658-6fcd-4f83-94ba-5f5dceb3af11@googlegroups.com> Message-ID: <35f6c95f-ed46-4ee1-9e65-dcf3d5872c05@googlegroups.com> Den tisdag 1 mars 2016 kl. 08:49:57 UTC+1 skrev Ian: > It's not at all clear what the problem is from your description. What > is it that you expect the code to do? What is it doing instead that > violates your expectation? Why are you asking for Javascript help on a > Python mailing list? > > On Mon, Feb 29, 2016 at 10:40 PM, wrote: > > I've been looking at the code for two days so i am a bit crosseyed. > > If anyone could help me set the condition so the loop catch the last pair/pairs, it is kind of weird that it succeed sometimes and break to early and report fail others. > > > > I would be very greatful if anyone can see why it break to early and return fail. Although it is clearly a succes looking at the last remaining pair none connected pair.It should report fail for the network permutations that stall due to link exhausting, but not stall creating last pair. > > > > It just a minor bug due to some condition that i just not get. > > Have a go 5 munutes maybe someone catch the faulthy condition. > > > > http://jt.node365.se/mydebug1.html > > -- > > https://mail.python.org/mailman/listinfo/python-list Here is a script to draw networks, drag and drop nodes. So the function will go here, right now only node deep one work. http://jt.node365.se/nodes11.html From steve at pearwood.info Tue Mar 1 06:18:59 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 Mar 2016 22:18:59 +1100 Subject: Reason for not allowing import twice but allowing reload() References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> Message-ID: <56d57aa4$0$1586$c3e8da3$5496439d@news.astraweb.com> On Mon, 29 Feb 2016 06:01 pm, Chris Angelico wrote: > I've never used reload() in any production code, ever. Ever. reload() isn't intended for production code. It is a convenience for interactive use. I cannot imagine why you would want to reload() in production code. That would imply that your production code is modifying already-imported modules, then wanting to import them again. Why would anyone in their right mind do that? Possibly because they lost a bet? -- Steven From rosuav at gmail.com Tue Mar 1 06:39:36 2016 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 1 Mar 2016 22:39:36 +1100 Subject: Reason for not allowing import twice but allowing reload() In-Reply-To: <56d57aa4$0$1586$c3e8da3$5496439d@news.astraweb.com> References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> <56d57aa4$0$1586$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Mar 1, 2016 at 10:18 PM, Steven D'Aprano wrote: > I cannot imagine why you would want to reload() in production code. That > would imply that your production code is modifying already-imported > modules, then wanting to import them again. Why would anyone in their right > mind do that? Possibly because they lost a bet? BartC and I have both done this exact thing, though neither of us used Python for it. It's not so insane as you might think; sometimes you want to update code, but you don't want to restart a process. Just because you've never had a process that hits a year of uptime doesn't mean nobody else does. :) ChrisA From steve at pearwood.info Tue Mar 1 06:42:22 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 Mar 2016 22:42:22 +1100 Subject: General computer language, syntax question. References: <5b619ffa-aae6-4fa8-9f62-58532668ec93@googlegroups.com> Message-ID: <56d5801f$0$1620$c3e8da3$5496439d@news.astraweb.com> On Tue, 1 Mar 2016 12:56 am, jonas.thornvall at gmail.com wrote: > I mean for for example Javascript Jonas, this is a Python forum. If we thought Javascript was a beautiful and well-designed language, we're be on a Javascript forum, complaining about Python. > if (typeof array[index] !== 'undefined' && array[index] !== null) { > or this one > if (array[index] != null) { > > I mean how do they come up with such convoluted syntax, do they pull it > out of ass? Probably. I don't know Javascript very well. It is possible that your statements about Javascript are as misinformed as your statements about Python. In Python, you certainly can do membership testing of a list: py> alist = ["ab", "cd", "ef", "gh"] py> "ef" in alist True py> "xy" in alist False and you can also test for empty lists just as easily: py> if alist: ... print("not empty") ... else: ... print("empty") ... not empty py> blist = [] py> if blist: ... print("not empty") ... else: ... print("empty") ... empty -- Steven From steve at pearwood.info Tue Mar 1 07:00:38 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 Mar 2016 23:00:38 +1100 Subject: common mistakes in this simple program References: Message-ID: <56d58468$0$1601$c3e8da3$5496439d@news.astraweb.com> On Tue, 1 Mar 2016 03:29 am, Ian Kelly wrote: > On Mon, Feb 29, 2016 at 8:18 AM, Ganesh Pal wrote: >> Iam on python 2.6 > > Python 2.6 has been unsupported since October 2013. Among other > things, that means it is no longer receiving security updates like > more recent versions. Unless you have an extremely strong reason for > wanting to stay to Python 2.6, you should update your Python version. Python 2.6 is still fully supported by Red Hat. -- Steven From steve at pearwood.info Tue Mar 1 07:05:42 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 Mar 2016 23:05:42 +1100 Subject: usage of try except for review. References: Message-ID: <56d58598$0$1601$c3e8da3$5496439d@news.astraweb.com> On Tue, 1 Mar 2016 04:38 am, Chris Angelico wrote: > On Tue, Mar 1, 2016 at 4:34 AM, Ganesh Pal wrote: >> On Mon, Feb 29, 2016 at 10:10 PM, Dennis Lee Bieber >> wrote: >> >>> Ask yourself: Will my program still work if I remove all the >>> assert >>> statements. If the answer is "No", then you should not be using an >>> assert. >> >> You meant if the answer is "NO" then I should be using asset ? > > No, Dennis was correct. You should assume that "assert" can > potentially be replaced with "pass" and your program will continue to > work. http://import-that.dreamwidth.org/676.html -- Steven From steve at pearwood.info Tue Mar 1 07:13:51 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 Mar 2016 23:13:51 +1100 Subject: [Off-topic] Requests author discusses MentalHealthError exception References: <56d16e6a$0$1593$c3e8da3$5496439d@news.astraweb.com> <854mcrxxp3.fsf@benfinney.id.au> Message-ID: <56d58780$0$1591$c3e8da3$5496439d@news.astraweb.com> On Tue, 1 Mar 2016 09:38 am, Larry Martell wrote: > But what is reality? Reality is that which, when you stop believing in it, doesn't go away. -- Steven From starkwedder2009 at gmail.com Tue Mar 1 08:36:39 2016 From: starkwedder2009 at gmail.com (starkwedder2009 at gmail.com) Date: Tue, 1 Mar 2016 05:36:39 -0800 (PST) Subject: convert Dbase (.dbf) files to SQLite databases In-Reply-To: <419cc0e0-3a78-4906-8420-c12ce2684bef@c36g2000yqn.googlegroups.com> References: <7c5n8kF25pc8bU1@mid.dfncis.de> <419cc0e0-3a78-4906-8420-c12ce2684bef@c36g2000yqn.googlegroups.com> Message-ID: Il giorno mercoled? 15 luglio 2009 18:30:29 UTC+2, John Machin ha scritto: > On Jul 15, 8:39?pm, David Lyon wrote: > > On Wed, 15 Jul 2009 11:53:28 +0200, Helmut Jarausch > > > > wrote: > > > Hi, > > > > > I have a lot of old Dbase files (.dbf) and I'll like to convert these > > > to SQLite databases as automatically as possible. > > > Does anybody know a tool/Python script to do so? > > > > > I know, I could use dbfpy and create the SQLite table and import all > > > data. But is there something easier? > > > > yes... > > > > Use OpenOffice-Scalc or MS-Office-Excel to open the table... > > Max 64K rows for Scalc and Excel 2003; 2007 can take 2**20 rows. > Only old dBase (not dBase 7). Memo fields not handled. Visual FoxPro > DBFs not supported by Excel even tho' VFP is an MS product. > > > > Export to csv.... > > Yuk. > > > > > Use SQLite Manager (https://addons.mozilla.org/en-US/firefox/addon/5817) > > > > and use the import wizard to import your data.... > > > > It shouldn't take too long... > > ... before you get sick of the error-prone manual tasks. > > I'd write a script that took a DBF file, analysed the field > descriptions, made a CREATE TABLE statement, executed it, and then > started doing inserts. Fairly easy to write. Scripts have the great > benefit that you can fix them and re-run a whole lot easier than > redoing manual steps. > > If dbfpy can't handle any new-fangled stuff you may have in your > files, drop me a line ... I have a soon-to-be released DBF module that > should be able to read the "new" stuff up to dBase7 and VFP9, > including memo files, conversion from whatever to Unicode if > needed, ... > > Cheers, > John From D.Strohl at F5.com Tue Mar 1 10:53:20 2016 From: D.Strohl at F5.com (Dan Strohl) Date: Tue, 1 Mar 2016 15:53:20 +0000 Subject: No subject In-Reply-To: References: Message-ID: <6040b85f1e164435b4d268f7bc11232e@seaexchmbx03.olympus.F5Net.com> I am sorry, though I have to say that I would find it hard working with a large snake every day as well. Luckily, there is a programing language (called Python) that could help in developing a snake removing application pretty easily. If, however you are actually talking about the programming language, then if you are asking for help in understanding it, or better being able to work with it, a little more information would probably help others help you. If you are simply making a statement that you are unable to work with it and have no interest in trying, then I am sorry that you feel that way, and encourage you to try a different language. (I would even try to recommend one, if we knew more about WHY you can't work with python.) If you are just trying to vent, I get that... though I would think that constructive venting would work better; ("I can't work with that damn python because it just won't install for me, I keep getting this stupid error 'blah'"). If you are trying to start an argument, or trolling, I suggest trying something more controversial... "Python is the worst language in the world because you have to indent everything exactly, that is a really stupid design!", that, I suspect would get a really good argument going! In any case, responding to your *actual* statement, good luck with finding co-workers that you can work with, I know how frustrating it can be not liking your co-workers. Dan > -----Original Message----- > From: Python-list [mailto:python-list-bounces+d.strohl=f5.com at python.org] On > Behalf Of Shamanov > Sent: Monday, February 29, 2016 11:20 AM > To: python-list at python.org > Subject: > > I can't work with Python > > -- > https://mail.python.org/mailman/listinfo/python-list From steve at pearwood.info Tue Mar 1 11:35:00 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Mar 2016 03:35:00 +1100 Subject: Everything good about Python except GUI IDE? References: <64a6599c-fae1-469d-bcee-875165b3cc7d@googlegroups.com> <56d294f8$0$1604$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56d5c4b6$0$1591$c3e8da3$5496439d@news.astraweb.com> On Sun, 28 Feb 2016 11:38 pm, BartC wrote: > On 28/02/2016 06:34, Steven D'Aprano wrote: > >> GUI elements are by definition graphical in nature, and like other >> graphical elements, manipulation by hand is superior to command-based >> manipulation. Graphical interfaces for manipulating graphics have won the >> UI war so effectively that some people have forgotten there ever was a >> war. Can you imagine using Photoshop without drag and drop? >> >> And yet programming those graphical interfaces is an exception. There, >> with very few exceptions, we still *require* a command interface. Not >> just a command interface, but an *off-line* command interface, where you >> batch up all your commands then run them at once, as if we were >> Neanderthals living in a cave. > > You've got that back to front. > > It's the GUI users who are the Neanderthals, having to effectively point > at things with sticks. Or have to physically move that rock themselves > (ie. drag a file to a wastebasket). I haven't physically moved an icon to the wastebasket for years. I point at the icon, right-click, and tell it "move yourself to the trash". > More advanced uses have the power of language, with all its > sophistications (ie. commands lines and scripting). Language is pretty important. But when you need to drive a nail into a piece of wood, would you rather hit the nail with a hammer, or explain to the hammer the precise direction and magnitude of force you would like it to apply when it impacts the nails? -- Steven From ethan at stoneleaf.us Tue Mar 1 11:39:14 2016 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 01 Mar 2016 08:39:14 -0800 Subject: convert Dbase (.dbf) files to SQLite databases In-Reply-To: References: <7c5n8kF25pc8bU1@mid.dfncis.de> <419cc0e0-3a78-4906-8420-c12ce2684bef@c36g2000yqn.googlegroups.com> Message-ID: <56D5C5B2.30106@stoneleaf.us> > Il giorno mercoled? 15 luglio 2009 18:30:29 UTC+2, John Machin ha scritto: >> If dbfpy can't handle any new-fangled stuff you may have in your >> files, drop me a line ... I have a soon-to-be released DBF module that >> should be able to read the "new" stuff up to dBase7 and VFP9, >> including memo files, conversion from whatever to Unicode if >> needed, ... Or you can use my dbf module [1] which has been in the wild for several years now and is fairly robust instead of waiting for John's module which has been in the "soon to be released" category for nearly as long. -- ~Ethan~ [1] https://pypi.python.org/pypi/dbf From steve at pearwood.info Tue Mar 1 11:44:41 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Mar 2016 03:44:41 +1100 Subject: Everything good about Python except GUI IDE? References: <64a6599c-fae1-469d-bcee-875165b3cc7d@googlegroups.com> <56d294f8$0$1604$c3e8da3$5496439d@news.astraweb.com> <234a398e-1b0f-467b-a8cb-d7ca748f8062@googlegroups.com> <84922f24-3e00-4a23-b26d-5e6c0d8e7e04@googlegroups.com> <87y4a5c58i.fsf@elektro.pacujo.net> <87twksdg9c.fsf@elektro.pacujo.net> <87d1rgca58.fsf@elektro.pacujo.net> <87h9grorcb.fsf@elektro.pacujo.net> Message-ID: <56d5c6fa$0$1595$c3e8da3$5496439d@news.astraweb.com> On Mon, 29 Feb 2016 07:33 pm, Chris Angelico wrote: > On Mon, Feb 29, 2016 at 7:25 PM, Marko Rauhamaa wrote: >> As for why you should avoid JS/CSS, Web pages open very slowly, jump >> around wildly during rendering and have unexpected artifacts (not to >> mention the numerous data collection abuses) when they are encumbered >> with truckloads of state-of-the-art web dev gimmicks. > > And when I pick up a paintbrush, canvas, and oil paints, the result is > appallingly hard on the eyes. Clearly oil paints should not be used, > and we should just place the brush tastefully on the canvas, because > that is guaranteed to look good. > > Don't blame the tool for its poor users. A better analogy is: When I add cocaine to my stew, the result is a appallingly bad for those who eat it. Do you have any idea how rough cocaine is on the human body and brain? My wife likes the analogy, being on cocaine is like pressing the accelerator of your car all the way to the floor, ALL THE TIME, regardless of whether you are moving forward or stopped at the lights. And yet, for some reason, people seem to like the cocaine-riddled stew, and often ask me to add more cocaine. People cannot get enough of Javascript, no matter what it does to the security and stability of their browser, no matter how many pop-ups it launches or how much spyware and malware it installs, or how many times it kills their browser. -- Steven From ethan at stoneleaf.us Tue Mar 1 11:49:08 2016 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 01 Mar 2016 08:49:08 -0800 Subject: convert Dbase (.dbf) files to SQLite databases In-Reply-To: <56D5C5B2.30106@stoneleaf.us> References: <7c5n8kF25pc8bU1@mid.dfncis.de> <419cc0e0-3a78-4906-8420-c12ce2684bef@c36g2000yqn.googlegroups.com> <56D5C5B2.30106@stoneleaf.us> Message-ID: <56D5C804.9020103@stoneleaf.us> >> Il giorno mercoled? 15 luglio 2009 18:30:29 UTC+2, John Machin ha >> scritto: Hmm, looks like that email was sent back in 2009. Sorry for the noise. I'm still not able to find a dbf module from John, though. -- ~Ethan~ From srkunze at mail.de Tue Mar 1 11:49:52 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Tue, 1 Mar 2016 17:49:52 +0100 Subject: [Off-topic] Requests author discusses MentalHealthError exception In-Reply-To: <56d58780$0$1591$c3e8da3$5496439d@news.astraweb.com> References: <56d16e6a$0$1593$c3e8da3$5496439d@news.astraweb.com> <854mcrxxp3.fsf@benfinney.id.au> <56d58780$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56D5C830.8030405@mail.de> On 01.03.2016 13:13, Steven D'Aprano wrote: > On Tue, 1 Mar 2016 09:38 am, Larry Martell wrote: > >> But what is reality? > Reality is that which, when you stop believing in it, doesn't go away. Just like that. From steve at pearwood.info Tue Mar 1 11:58:50 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Mar 2016 03:58:50 +1100 Subject: usage of try except for review. References: Message-ID: <56d5ca4b$0$1602$c3e8da3$5496439d@news.astraweb.com> On Mon, 29 Feb 2016 07:13 pm, Ganesh Pal wrote: > def run_cmd_and_verify(cmd, timeout=1000): > try: > out, err, ret = run(cmd, timeout=timeout) > assert ret ==0,"ERROR (ret %d): " \ > " \nout: %s\nerr: %s\n" % (ret, out, err) Do not use assert for error checking. http://import-that.dreamwidth.org/676.html Instead, you should write this: out, err, ret = run(cmd, timeout=timeout) if ret != 0: raise RuntimeError( "ERROR (ret %d): \nout: %s\nerr: %s\n" % (ret, out, err)) > except Exception as e: > logging.error("Failed to run %s got %s" % (cmd, e)) > return False > return True > > > def run_test(): > """ > Mount > """ > pdb.set_trace() Do not use the debugger as part of production code. The debugger is for debugging. When you have debugged the section of code, remove the debugger calls. > for cmd in ["mount /nfs_mount1", "mount /cifs_mount1"]: > try: > if not run_cmd_and_verify(cmd, timeout=3600): > return False > except: > logging.error("Failure while running command %") > logging.info("Setup and Creation ....Done !!!") Do not use bare except clauses like this unless you know what you are doing. https://realpython.com/blog/python/the-most-diabolical-python-antipattern/ > cmd = "run_scan" > out, err, ret = run(cmd) > for cmd in ["create_data.py -nfs ", > "validate.py -30 "]: > try: > if not run_cmd_and_verify(cmd, timeout=3600): > return False > except: > logging.error("") > return False > logging.info("Mount IS START.....Done !!!") > > def main(): > if not run_test(): > sys.exit("Exiting Main") > > > if __name__ == '__main__': > main() I would re-write this script as something like this: # Untested def run_cmd(cmd, timeout=1000): out, err, ret = run(cmd, timeout=timeout) if ret != 0: raise RuntimeError( "ERROR (ret %d): \nout: %s\nerr: %s\n" % (ret, out, err)) def run_test(): for cmd in ["mount /nfs_mount1", "mount /cifs_mount1"]: run_cmd(cmd, timeout=3600) logging.info("Setup and Creation ....Done !!!") cmd = "run_scan" out, err, ret = run(cmd) # Do you care about the result of the scan? Then you should log it. for cmd in ["create_data.py -nfs ", "validate.py -30 "]: run_cmd(cmd, timeout=3600) logging.info("Mount IS START.....Done !!!") if __name__ == '__main__': try: run_test() except Exception as err: logging.error("run_test failed", exc_info=True) sys.exit(1) > Question 1: > > > > 1. Have I used try and expect block correctly ? , In my case I have > the except block that's is not needed it just gives an message I > have still included for the sake of try block If the except block is not needed, then you should not use try. > 2. If a failure?s are encountered the error by assert condition the > errors are now displayed on the screen , how do I redirect it to log > file using logging error Don't use assert like that. > 3. my function def has 1000 but Iam using 3600 in the calling fnx etc > , Time out value are overwritten ? I don't understand the question. -- Steven From steve at pearwood.info Tue Mar 1 12:00:17 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Mar 2016 04:00:17 +1100 Subject: Reason for not allowing import twice but allowing reload() References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> <5c8e3283-2013-4f68-87b8-6311ccee64a3@googlegroups.com> <3ec34f5c-7d18-49c8-8d38-dcd4e7c58e9b@googlegroups.com> Message-ID: <56d5caa2$0$1602$c3e8da3$5496439d@news.astraweb.com> On Tue, 1 Mar 2016 12:25 am, alien2utoo at gmail.com wrote: >> As for need of import in Idle session, I use it to >> - import sys >> - sys.append.path('D:\\Where\\Ever\\My\\Modules\\Lie') > > Kindly read above as > sys.path.append(....) > >> - import mymodule There are better ways to manage your Python path than to manually insert paths into sys.path like that. What version of Python are you using? -- Steven From steve at pearwood.info Tue Mar 1 12:05:49 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Mar 2016 04:05:49 +1100 Subject: [Off-topic] Requests author discusses MentalHealthError exception References: <56d16e6a$0$1593$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56d5cbef$0$22142$c3e8da3$5496439d@news.astraweb.com> On Tue, 1 Mar 2016 04:08 am, Rustom Mody wrote: > And who is the last arbiter on that 'reality'? I'll give you the benefit of the doubt that this is a genuine question, and not just an attempt to ask a rhetorical question to demonstrate your profundity. You should not assume that there is any such thing as "the last arbiter" of reality. There is no arbiter at all, let alone a final one. But what we have are various ways of managing and uncertainty and error. One of which is consensus. For instance, there are seven billion people on earth who think they are people, and one who thinks he may be a butterfly. Which is more likely to be correct? https://en.wikiquote.org/wiki/Zhuangzi To quote Terry Pratchett: ?The poet Hoha once dreamed he was a butterfly, and then he awoke and said, ?Am I a man who dreamed he was a butterfly or am I a butterfly dreaming he is a man??? said Lobsang, trying to join in. ?Really?? said Susan briskly. ?And which was he?? ?What? Well?who knows?? ?How did he write his poems?? said Susan. ?With a brush, of course.? ?He didn?t flap around making information-rich patterns in the air or laying eggs on cabbage leaves?? ?No one ever mentioned it.? ?Then he was probably a man,? said Susan. Because there are limitations on how we observe reality, there are limits to how objective we can be. We have an imperfect ability to observe the world around us (including our own mental states) and are prone to errors. But, over a wide range of conditions (although not *all* conditions) we can eliminate many classes of error by comparing notes with our fellows, so to speak. If I think I am a butterfly, and my wife thinks I'm a man, and my co-workers think I'm a man, and my neighbours think I'm a man, chances are good that it is me who is mistaken, not them. Consequently reality is a shared construct -- or rather, our understanding of reality is at least partly a shared construct. In principle, at least, *everything* is subject to disproof. But in practice some things are more certain than others. I wouldn't bet $100 on quarks still being considered the fundamental building block of matter in 200 years, but I would bet a million dollars on the sun still seeming to rise in the east every 24 hours. As Isaac Asimov put it: When people thought the earth was flat, they were wrong. When people thought the earth was spherical, they were wrong. But if you think that thinking the earth is spherical is just as wrong as thinking the earth is flat, then your view is wronger than both of them put together. https://en.wikipedia.org/wiki/Wronger_than_wrong http://chem.tufts.edu/AnswersInScience/RelativityofWrong.htm It's not that reality itself is subject to change (except in the trivial sense that we can take actions that modify the state of the world: I can pick this cup up and move it over there, you can eat that apple) but that our understanding of reality is subject to change. Sometimes our understanding is full of uncertainty and doubt, sometimes it is subject to re-interpretation, and sometimes our understanding is almost certainly correct: it is difficult to imagine any credible or believable reinterpretation that would change the facts as we know them. A thousand years from now, the sun will still appear to be rising in the east. -- Steven From steve at pearwood.info Tue Mar 1 12:11:17 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Mar 2016 04:11:17 +1100 Subject: Reason for not allowing import twice but allowing reload() References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> <56d57aa4$0$1586$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56d5cd36$0$22142$c3e8da3$5496439d@news.astraweb.com> On Tue, 1 Mar 2016 10:39 pm, Chris Angelico wrote: > On Tue, Mar 1, 2016 at 10:18 PM, Steven D'Aprano > wrote: >> I cannot imagine why you would want to reload() in production code. That >> would imply that your production code is modifying already-imported >> modules, then wanting to import them again. Why would anyone in their >> right mind do that? Possibly because they lost a bet? > > BartC and I have both done this exact thing, though neither of us used > Python for it. It's not so insane as you might think; sometimes you > want to update code, but you don't want to restart a process. Just > because you've never had a process that hits a year of uptime doesn't > mean nobody else does. :) I've had an uptime of over 400 days on my laptop, without logging out, so yes I have had processes with over a year of uptime. But that doesn't mean I expect to modify the code of a running process and reload it. Modify data, sure, but not code. I'll grudgingly accept that, just maybe, if you have some sort of plugin system, you may want to unload and reload plugins, replacing the old plugin with a new one of the same name. Maybe you could get that to work in Python using the import system. -- Steven From nomail at invalid.com Tue Mar 1 12:24:12 2016 From: nomail at invalid.com (ast) Date: Tue, 1 Mar 2016 18:24:12 +0100 Subject: What arguments are passed to the __new__ method ? Message-ID: <56d5d043$0$632$426a74cc@news.free.fr> Hello It's not clear to me what arguments are passed to the __new__ method. Here is a piece of code: class Premiere: def __new__(cls, price): return object.__new__(cls) def __init__(self, price): pass p = Premiere(1000) No errors, so it seems that 2 arguments are passed to __new__, cls and price. But if i do: class Premiere: def __new__(cls, price): return object.__new__(cls, price) def __init__(self, price): pass p = Premiere(1000) it fails. It is strange because according to me it is equivalent to: class Premiere: def __init__(self, price): pass p = Premiere(1000) which is OK. From bgailer at gmail.com Tue Mar 1 12:44:00 2016 From: bgailer at gmail.com (Bob Gailer) Date: Tue, 1 Mar 2016 12:44:00 -0500 Subject: No subject In-Reply-To: References: Message-ID: On Mar 1, 2016 9:11 AM, "Shamanov" wrote: > > I can't work with Python I'm sorry to hear that. If you want some help you will have to give us more information. From best_lay at yahoo.com Tue Mar 1 12:52:50 2016 From: best_lay at yahoo.com (Wildman) Date: Tue, 01 Mar 2016 11:52:50 -0600 Subject: Request More Help With XBM Image References: <8rKdnb6SKYLRIEnLnZ2dnUU7-f3NnZ2d@giganews.com> Message-ID: <34GdnUOxhd5vS0jLnZ2dnUU7-Y3OydjZ@giganews.com> On Tue, 01 Mar 2016 09:56:56 +0100, Peter Otten wrote: > Wildman via Python-list wrote: > >> I want to take an image file, convert it to XBM format and >> display it. Thanks to Mr. Otten I can open and display the >> XBM image without any problems. The script first calls an >> external program for the image conversion then I can open >> and display it. Of course, I am left with the XBM file that >> needs to be deleted. It seemed to me to be a better approach >> to use stdout and pipe thereby eliminating the XBM file >> altogether. Here is code I have so far but I'm not sure >> what to do next... >> >> convert = "convert " + fileName + " -resize 48x48! -threshold 55% xbm:-" >> p = subprocess.Popen([convert], stdout=subprocess.PIPE, shell=True) >> xbmFile, err = p.communicate() > > Why would you need a shell? I guess it is a Linux thing. If I don't use it, I get the below error. A shell window does not actually open. I presume it runs in the background while executing the subprocess command. Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1535, in __call__ return self.func(*args) File "./test.py", line 59, in open_image p = subprocess.Popen(command, stdout=subprocess.PIPE) File "/usr/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1335, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory >> The variable fileName contains the image file path and name. >> The variable convert contains the complete command. The last >> argument in the command tells the convert utility to covert >> to an XBM and to direct the output to stdout. After the above >> code runs xbmFile contains the actual image, which is plain >> text. (X BitMap (XBM) is a plain text binary image format.) >> >> My question is how do I take the xbmFile variable and convert >> it to an image object that can be displayed? The technique >> for displaying an image from a file does not work or at least >> I have not been able to get it to work. > > I think Image.open() accepts a file-like object, so > > import io > ... > command = [ > "convert", fileName, > "-resize", "48x48!", > "-threshold", "55%", > "xbm:-"] > p = subprocess.Popen(command, stdout=subprocess.PIPE) > xbmFile, err = p.communicate() > openImage = Image.open(io.BytesIO(xbmFile)) > > should work. I does work, perfectly. During my research I didn't run across anything about using io. The learning process continues... I am in your debt again. Thank you. -- GNU/Linux user #557453 "Be at war with your vices, at peace with your neighbors, and let every new year find you a better man." -Benjamin Franklin From rosuav at gmail.com Tue Mar 1 13:04:39 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Mar 2016 05:04:39 +1100 Subject: Reason for not allowing import twice but allowing reload() In-Reply-To: <56d5cd36$0$22142$c3e8da3$5496439d@news.astraweb.com> References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> <56d57aa4$0$1586$c3e8da3$5496439d@news.astraweb.com> <56d5cd36$0$22142$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Mar 2, 2016 at 4:11 AM, Steven D'Aprano wrote: > On Tue, 1 Mar 2016 10:39 pm, Chris Angelico wrote: > >> On Tue, Mar 1, 2016 at 10:18 PM, Steven D'Aprano >> wrote: >>> I cannot imagine why you would want to reload() in production code. That >>> would imply that your production code is modifying already-imported >>> modules, then wanting to import them again. Why would anyone in their >>> right mind do that? Possibly because they lost a bet? >> >> BartC and I have both done this exact thing, though neither of us used >> Python for it. It's not so insane as you might think; sometimes you >> want to update code, but you don't want to restart a process. Just >> because you've never had a process that hits a year of uptime doesn't >> mean nobody else does. :) > > I've had an uptime of over 400 days on my laptop, without logging out, so > yes I have had processes with over a year of uptime. But that doesn't mean > I expect to modify the code of a running process and reload it. Modify > data, sure, but not code. > > I'll grudgingly accept that, just maybe, if you have some sort of plugin > system, you may want to unload and reload plugins, replacing the old plugin > with a new one of the same name. Maybe you could get that to work in Python > using the import system. And then you expand the plugin system so it includes everything other than a kernel that manages plugins, and you now have the kind of system I'm talking about. My MUD server and client are both structured like this: 1) Startup file, which does basic setup, initializes all other files, then (in the server) binds to a port and starts listening. It then drops to a back-end loop, either threaded or async I/O. 2) Globally-available utilities toolbox. Can be reloaded to add or edit any of the functions/classes in it. 3) (Client only) GUI handling file. Creates the window, handles user interaction. Can be reloaded, although since it doesn't destroy and recreate the window, some changes won't take effect until full restart. 4) All other plugins, which can do pretty much anything. The system is quite happy to add, remove, and update these at any time. Everything except the startup file can be edited after startup. That's basically _every_ piece of code in the whole project. Major features can be implemented and debugged without resetting anything, and once I'm satisfied with the code, I commit and push, and end users can pull that change without restarting. If I were to implement this in Python, I would probably do it by reimplementing module-like behaviour, rather than actually using import. But it could be made to work, and it definitely has its benefits. On the server, it's crucial - I can't kick my users off every time I make changes; even on the client, having to restart and reconnect for every change would be tedious, although that's more for my own debugging than for other people's usage (it's not as big a deal to update the program once a week and then have to restart). ChrisA From marko at pacujo.net Tue Mar 1 13:06:55 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Tue, 01 Mar 2016 20:06:55 +0200 Subject: Everything good about Python except GUI IDE? References: <64a6599c-fae1-469d-bcee-875165b3cc7d@googlegroups.com> <56d294f8$0$1604$c3e8da3$5496439d@news.astraweb.com> <56d5c4b6$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87y4a2ax8g.fsf@elektro.pacujo.net> Steven D'Aprano : > On Sun, 28 Feb 2016 11:38 pm, BartC wrote: >> It's the GUI users who are the Neanderthals, having to effectively >> point at things with sticks. Or have to physically move that rock >> themselves (ie. drag a file to a wastebasket). > > I haven't physically moved an icon to the wastebasket for years. I > point at the icon, right-click, and tell it "move yourself to the > trash". Do you find that interface convenient? Do you often find yourself clickety-clicking around to perform bulk file operations? > Language is pretty important. But when you need to drive a nail into a > piece of wood, would you rather hit the nail with a hammer, or explain > to the hammer the precise direction and magnitude of force you would > like it to apply when it impacts the nails? I don't know. My everyday file manipulation needs are so diverse that I couldn't imagine how a GUI would make my life easier. What I'm thinking is, could Python turn into a serious competitor to bash? The standard shell suffers greatly from sloppy quoting, and many of the age-old list-processing idioms are more awkward than cute. A python shell would need a well-thought-out default import plus a way to string together external commands. Maybe JSON or similar could be the standard I/O framing format (instead of SPC-separated fields and LF-separated records). Someone must have tried that before. (Tclsh did that years back but suffered from analogous problems as bash.) Marko From rosuav at gmail.com Tue Mar 1 13:07:24 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Mar 2016 05:07:24 +1100 Subject: Everything good about Python except GUI IDE? In-Reply-To: <56d5c6fa$0$1595$c3e8da3$5496439d@news.astraweb.com> References: <64a6599c-fae1-469d-bcee-875165b3cc7d@googlegroups.com> <56d294f8$0$1604$c3e8da3$5496439d@news.astraweb.com> <234a398e-1b0f-467b-a8cb-d7ca748f8062@googlegroups.com> <84922f24-3e00-4a23-b26d-5e6c0d8e7e04@googlegroups.com> <87y4a5c58i.fsf@elektro.pacujo.net> <87twksdg9c.fsf@elektro.pacujo.net> <87d1rgca58.fsf@elektro.pacujo.net> <87h9grorcb.fsf@elektro.pacujo.net> <56d5c6fa$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Mar 2, 2016 at 3:44 AM, Steven D'Aprano wrote: > On Mon, 29 Feb 2016 07:33 pm, Chris Angelico wrote: > >> On Mon, Feb 29, 2016 at 7:25 PM, Marko Rauhamaa wrote: >>> As for why you should avoid JS/CSS, Web pages open very slowly, jump >>> around wildly during rendering and have unexpected artifacts (not to >>> mention the numerous data collection abuses) when they are encumbered >>> with truckloads of state-of-the-art web dev gimmicks. >> >> And when I pick up a paintbrush, canvas, and oil paints, the result is >> appallingly hard on the eyes. Clearly oil paints should not be used, >> and we should just place the brush tastefully on the canvas, because >> that is guaranteed to look good. >> >> Don't blame the tool for its poor users. > > A better analogy is: > > When I add cocaine to my stew, the result is a appallingly bad for those who > eat it. Do you have any idea how rough cocaine is on the human body and > brain? My wife likes the analogy, being on cocaine is like pressing the > accelerator of your car all the way to the floor, ALL THE TIME, regardless > of whether you are moving forward or stopped at the lights. And yet, for > some reason, people seem to like the cocaine-riddled stew, and often ask me > to add more cocaine. > > People cannot get enough of Javascript, no matter what it does to the > security and stability of their browser, no matter how many pop-ups it > launches or how much spyware and malware it installs, or how many times it > kills their browser. s/cocaine/sriracha/ and I would agree with you, because there are places where JS can majorly enhance a web site, and it isn't going to kill you if you use it correctly. But while we might disagree on the precise boundary between "good JS" and "bad JS", it seems we're pretty vehemently in agreement that there are a lot of sites out there that serve up a stew that burns the paint off buildings in the next county. ChrisA From rosuav at gmail.com Tue Mar 1 13:21:06 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Mar 2016 05:21:06 +1100 Subject: No subject In-Reply-To: <6040b85f1e164435b4d268f7bc11232e@seaexchmbx03.olympus.F5Net.com> References: <6040b85f1e164435b4d268f7bc11232e@seaexchmbx03.olympus.F5Net.com> Message-ID: On Wed, Mar 2, 2016 at 2:53 AM, Dan Strohl wrote: > If you are trying to start an argument, or trolling, I suggest trying something more controversial... "Python is the worst language in the world because you have to indent everything exactly, that is a really stupid design!", that, I suspect would get a really good argument going! > Python is the worst language in the world because it forces you to use Unicode instead of allowing Shift-JIS or DBCS! ChrisA From __peter__ at web.de Tue Mar 1 13:26:55 2016 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Mar 2016 19:26:55 +0100 Subject: Request More Help With XBM Image References: <8rKdnb6SKYLRIEnLnZ2dnUU7-f3NnZ2d@giganews.com> <34GdnUOxhd5vS0jLnZ2dnUU7-Y3OydjZ@giganews.com> Message-ID: Wildman via Python-list wrote: > On Tue, 01 Mar 2016 09:56:56 +0100, Peter Otten wrote: >> Wildman via Python-list wrote: >>> convert = "convert " + fileName + " -resize 48x48! -threshold 55% xbm:-" >>> p = subprocess.Popen([convert], stdout=subprocess.PIPE, shell=True) >>> xbmFile, err = p.communicate() >> Why would you need a shell? Just in case the example in my previous post has not made it clear: that was a rhetorical question. You do not need the shell, and in fact shouldn't use it. > I guess it is a Linux thing. If I don't use it, I get > the below error. A shell window does not actually open. > I presume it runs in the background while executing the > subprocess command. > Exception in Tkinter callback > Traceback (most recent call last): > File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1535, in __call__ > return self.func(*args) > File "./test.py", line 59, in open_image > p = subprocess.Popen(command, stdout=subprocess.PIPE) > File "/usr/lib/python2.7/subprocess.py", line 710, in __init__ > errread, errwrite) > File "/usr/lib/python2.7/subprocess.py", line 1335, in _execute_child > raise child_exception > OSError: [Errno 2] No such file or directory An exception is raised because you pass the command as a single argument like in [Python 2.7] >>> subprocess.Popen("ls /usr/share/dict/words") Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory This looks for an executable called "ls /usr/share/dict/words" (the whole shebang!) where you actually want to run "ls" with the argument "/usr/share/dict/words". Once you split the parts >>> subprocess.Popen(["ls", "/usr/share/dict/words"]) >>> /usr/share/dict/words everything works as expected. The error message in Python 3.4 would have given you a clue, by the way: [Python 3.4] >>> subprocess.Popen("ls /usr/share/dict/words") Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3.4/subprocess.py", line 859, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.4/subprocess.py", line 1457, in _execute_child raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: 'ls /usr/share/dict/words' From tjreedy at udel.edu Tue Mar 1 13:48:18 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 1 Mar 2016 13:48:18 -0500 Subject: The debug process never connected back to Wing IDE In-Reply-To: <1167897796.1336230.1456789327016.JavaMail.yahoo@mail.yahoo.com> References: <1167897796.1336230.1456789327016.JavaMail.yahoo.ref@mail.yahoo.com> <1167897796.1336230.1456789327016.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 2/29/2016 6:42 PM, quoc tuong via Python-list wrote: > Hi python stopped working on this error: The debug process never > connected back to Wing IDE: Aborting debug session. See > Trouble-shooting Failure to Debug in the product manual. Dit you do that -- check the manual? If the 'product manual' is inadequate, tell the product producer. Or inquire on a WingIDE list. -- Terry Jan Reedy From best_lay at yahoo.com Tue Mar 1 13:56:03 2016 From: best_lay at yahoo.com (Wildman) Date: Tue, 01 Mar 2016 12:56:03 -0600 Subject: Request More Help With XBM Image References: <8rKdnb6SKYLRIEnLnZ2dnUU7-f3NnZ2d@giganews.com> <34GdnUOxhd5vS0jLnZ2dnUU7-Y3OydjZ@giganews.com> Message-ID: On Tue, 01 Mar 2016 19:26:55 +0100, Peter Otten wrote: > An exception is raised because you pass the command as a single argument I did not realize that how the command was passed would make such a difference. I guess I am stuck in my old VB habits for creating variables. You don't have to say it, this ain't VB! :-) After making the changes to "command = ", it works fine without the shell. At the risk of sounding redundant, thank you. -- GNU/Linux user #557453 "The Constitution only gives people the right to pursue happiness. You have to catch it yourself." -Benjamin Franklin From auriocus at gmx.de Tue Mar 1 14:30:59 2016 From: auriocus at gmx.de (Christian Gollwitzer) Date: Tue, 1 Mar 2016 20:30:59 +0100 Subject: Request More Help With XBM Image In-Reply-To: <8rKdnb6SKYLRIEnLnZ2dnUU7-f3NnZ2d@giganews.com> References: <8rKdnb6SKYLRIEnLnZ2dnUU7-f3NnZ2d@giganews.com> Message-ID: Am 29.02.16 um 22:51 schrieb Wildman: > I want to take an image file, convert it to XBM format and > display it. Thanks to Mr. Otten I can open and display the > XBM image without any problems. The script first calls an > external program for the image conversion then I can open > and display it. Of course, I am left with the XBM file that > needs to be deleted. I think you are solving the wrong problem. If your aim is to just display an image using Tkinter, you can use PIL to read the image and transfer the bits into a Tkinter photoimage object. For an example, look here: http://code.activestate.com/recipes/521918-pil-and-tkinter-to-display-images/ (this might need some updating if you are using Python 3) Christian From eryksun at gmail.com Tue Mar 1 14:54:31 2016 From: eryksun at gmail.com (eryk sun) Date: Tue, 1 Mar 2016 13:54:31 -0600 Subject: What arguments are passed to the __new__ method ? In-Reply-To: <56d5d043$0$632$426a74cc@news.free.fr> References: <56d5d043$0$632$426a74cc@news.free.fr> Message-ID: On Tue, Mar 1, 2016 at 11:24 AM, ast wrote: > > class Premiere: > > def __new__(cls, price): > return object.__new__(cls, price) > > def __init__(self, price): > pass > > p = Premiere(1000) > > it fails. It is strange because according to me it is equivalent to: > > class Premiere: > > def __init__(self, price): > pass > > p = Premiere(1000) The implementation knowns whether a type overrides the __new__ or __init__ methods. You're expected to consume additional arguments in this case. However, excess arguments are ignored in object.__new__ if a type overrides __init__ without overriding __new__ (i.e. your second example). Excess arguments are also ignored in object.__init__ if a type overrides __new__ without overriding __init__. In CPython, this behavior is implemented for object.__new__ by the following statement in Objects/typeobject.c, object_new: if (excess_args(args, kwds) && (type->tp_init == object_init || type->tp_new != object_new)) { PyErr_SetString(PyExc_TypeError, "object() takes no parameters"); return NULL; } An exception is always raised if a type overrides __new__ and passes extra arguments to object.__new__. No exception is raised for excess arguments in object.__new__ if a type overrides __init__ but not __new__. The __init__ method must consume the extra arguments; it must not pass them to object.__init__. The behavior for object.__init__ is implemented by the following statement in Objects/typeobject.c, object_init: if (excess_args(args, kwds) && (type->tp_new == object_new || type->tp_init != object_init)) { PyErr_SetString(PyExc_TypeError, "object.__init__() takes no parameters"); err = -1; } An exception is always raised if a type overrides __init__ and passes extra arguments to object.__init__. No exception is raised for excess arguments in object.__init__ if a type overrides __new__ but not __init__. The __new__ method must consume the extra arguments; it must not pass them to object.__new__. From best_lay at yahoo.com Tue Mar 1 15:24:15 2016 From: best_lay at yahoo.com (Wildman) Date: Tue, 01 Mar 2016 14:24:15 -0600 Subject: Request More Help With XBM Image References: <8rKdnb6SKYLRIEnLnZ2dnUU7-f3NnZ2d@giganews.com> Message-ID: On Tue, 01 Mar 2016 20:30:59 +0100, Christian Gollwitzer wrote: > Am 29.02.16 um 22:51 schrieb Wildman: >> I want to take an image file, convert it to XBM format and >> display it. Thanks to Mr. Otten I can open and display the >> XBM image without any problems. The script first calls an >> external program for the image conversion then I can open >> and display it. Of course, I am left with the XBM file that >> needs to be deleted. > > I think you are solving the wrong problem. If your aim is to just > display an image using Tkinter, you can use PIL to read the image and > transfer the bits into a Tkinter photoimage object. For an example, look > here: > > http://code.activestate.com/recipes/521918-pil-and-tkinter-to-display-images/ > > (this might need some updating if you are using Python 3) > > Christian Thanks. I have read that page, among many others, during my research. It deals with an actual image file. I am dealing with an image that is not a file. It was redirected to stdout from another process and was never saved to the hard drive. Anyway, with Mr. Otten's help the problem is resolved. -- GNU/Linux user #557453 "Real patriotism is a willingness to challenge the government when it's wrong." -Ron Paul From tjreedy at udel.edu Tue Mar 1 15:27:48 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 1 Mar 2016 15:27:48 -0500 Subject: What arguments are passed to the __new__ method ? In-Reply-To: <56d5d043$0$632$426a74cc@news.free.fr> References: <56d5d043$0$632$426a74cc@news.free.fr> Message-ID: On 3/1/2016 12:24 PM, ast wrote: > Hello > > It's not clear to me what arguments are passed to the > __new__ method. The objects passed to any function are the objects that are passed. The type and number of objects that *should be* passed depends on the signature of the function. If class C defines __new__, then C.__new__ will receive as args C and all args passed in a C(...) call. So the C(...) call should have args that match those expected by __new__. If C also defines __init__, it will get the same args other than self replacing cls and thus it should have the same signature. The case is covered by in the entry for __new__ in https://docs.python.org/3/reference/datamodel.html#basic-customization "If __new__() returns an instance of cls, then the new instance?s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__()." > class Premiere: > def __new__(cls, price): > return object.__new__(cls) This matches "Typical implementations create a new instance of the class by invoking the superclass?s __new__() method using super(currentclass, cls).__new__(cls[, ...]) with appropriate arguments and then modifying the newly-created instance as necessary before returning it." object.__new__ only takes the cls parameter. > def __init__(self, price): > pass > p = Premiere(1000) > > No errors, so it seems that 2 arguments are passed > to __new__, cls and price, and 2 arguments are passed to __init__, self and price -- as documented. > But if i do: > class Premiere: > def __new__(cls, price): > return object.__new__(cls, price) You get an error in current python because you sent an extra arg to object.__new__. If __new__ calls a superclass __new__, then it should only pass the args expected. At one time, object.__new__ would have accepted the price arg and ignored it. This is no longer true > def __init__(self, price): > pass > p = Premiere(1000) > > it fails. It is strange because according to me it is equivalent to: Well, 'you' is wrong ;-), because in the following case, Premiere.__new__ is object.__new__, which has a different signature than __new__ above. > class Premiere: > def __init__(self, price): > pass > p = Premiere(1000) > > which is OK. Premiere is callable because it inherits object.__call__. That function, or the implementation of the CALL FUNCTION bytecode, must notice that Premiere.__new__ is object.__new__, by inheritance, and only pass Premiere and not 1000. The doc entry for __init__ says "The arguments are those passed to the class constructor expression." (The latter is the expression in the code that results in the class call.) This is always true. But since the signature of object.__new__ was restricted, the claim that the same args are sent to __new__ and __init__ seems not to be true. I may open a new doc issue. -- Terry Jan Reedy From eryksun at gmail.com Tue Mar 1 16:09:14 2016 From: eryksun at gmail.com (eryk sun) Date: Tue, 1 Mar 2016 15:09:14 -0600 Subject: What arguments are passed to the __new__ method ? In-Reply-To: References: <56d5d043$0$632$426a74cc@news.free.fr> Message-ID: On Tue, Mar 1, 2016 at 2:27 PM, Terry Reedy wrote: > On 3/1/2016 12:24 PM, ast wrote: > >> class Premiere: >> def __init__(self, price): >> pass >> p = Premiere(1000) >> >> which is OK. > > Premiere is callable because it inherits object.__call__. That function, or > the implementation of the CALL FUNCTION bytecode, must notice that > Premiere.__new__ is object.__new__, by inheritance, and only pass Premiere > and not 1000. It's not handled in bytecode or __call__. In CPython the type_call function passes its args and kwds to the type's tp_new and tp_init functions without modification. object.__new__ ignores the excess arguments in this case, as described in my previous message. While I think the cases where object.__new__ and object.__init__ ignore excess arguments are practical and sensible, they should still be documented. AFAICT, the language reference has nothing to say on this matter. From ian.g.kelly at gmail.com Tue Mar 1 16:53:06 2016 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 1 Mar 2016 14:53:06 -0700 Subject: Reason for not allowing import twice but allowing reload() In-Reply-To: References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> <56d57aa4$0$1586$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mar 1, 2016 4:41 AM, "Chris Angelico" wrote: > > On Tue, Mar 1, 2016 at 10:18 PM, Steven D'Aprano wrote: > > I cannot imagine why you would want to reload() in production code. That > > would imply that your production code is modifying already-imported > > modules, then wanting to import them again. Why would anyone in their right > > mind do that? Possibly because they lost a bet? > > BartC and I have both done this exact thing, though neither of us used > Python for it. It's not so insane as you might think; sometimes you > want to update code, but you don't want to restart a process. Just > because you've never had a process that hits a year of uptime doesn't > mean nobody else does. :) I have a hard time understanding the appeal of super-long uptimes. I'm not even comfortable running a single kernel version that long. What's so awful about 5 minutes of announced downtime in the middle of the night once a month while the system restarts? From rosuav at gmail.com Tue Mar 1 17:02:49 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Mar 2016 09:02:49 +1100 Subject: Reason for not allowing import twice but allowing reload() In-Reply-To: References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> <56d57aa4$0$1586$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Mar 2, 2016 at 8:53 AM, Ian Kelly wrote: > On Mar 1, 2016 4:41 AM, "Chris Angelico" wrote: >> >> On Tue, Mar 1, 2016 at 10:18 PM, Steven D'Aprano > wrote: >> > I cannot imagine why you would want to reload() in production code. That >> > would imply that your production code is modifying already-imported >> > modules, then wanting to import them again. Why would anyone in their > right >> > mind do that? Possibly because they lost a bet? >> >> BartC and I have both done this exact thing, though neither of us used >> Python for it. It's not so insane as you might think; sometimes you >> want to update code, but you don't want to restart a process. Just >> because you've never had a process that hits a year of uptime doesn't >> mean nobody else does. :) > > I have a hard time understanding the appeal of super-long uptimes. I'm not > even comfortable running a single kernel version that long. What's so awful > about 5 minutes of announced downtime in the middle of the night once a > month while the system restarts? It kicks connections off, which may not matter to web sites, but it matters to servers that are designed for long-running connections. But more importantly, five minutes once a month isn't enough to do all your updates - so a live-update system would be required even with a regular monthly reset. I tend to have announced outages for kernel updates and such (eg a couple weeks ago), but in between, I want to be able to keep everything going, even though I'm making changes. Maybe I don't get to a year all that often (from memory, I think I've just twice achieved >1y uptime), but I certainly have multi-day uptimes, despite making changes multiple times a day. And I want to be able to deploy changes in the middle of a game, not leave off until the next scheduled downtime. So, yes, I need to be able to modify an already-imported module. ChrisA From ian.g.kelly at gmail.com Tue Mar 1 17:29:46 2016 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 1 Mar 2016 15:29:46 -0700 Subject: Reason for not allowing import twice but allowing reload() In-Reply-To: References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> <56d57aa4$0$1586$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Mar 1, 2016 at 3:02 PM, Chris Angelico wrote: > On Wed, Mar 2, 2016 at 8:53 AM, Ian Kelly wrote: >> I have a hard time understanding the appeal of super-long uptimes. I'm not >> even comfortable running a single kernel version that long. What's so awful >> about 5 minutes of announced downtime in the middle of the night once a >> month while the system restarts? > > It kicks connections off, which may not matter to web sites, but it > matters to servers that are designed for long-running connections. But > more importantly, five minutes once a month isn't enough to do all > your updates - so a live-update system would be required even with a > regular monthly reset. I tend to have announced outages for kernel > updates and such (eg a couple weeks ago), but in between, I want to be > able to keep everything going, even though I'm making changes. > > Maybe I don't get to a year all that often (from memory, I think I've > just twice achieved >1y uptime), but I certainly have multi-day > uptimes, despite making changes multiple times a day. And I want to be > able to deploy changes in the middle of a game, not leave off until > the next scheduled downtime. So, yes, I need to be able to modify an > already-imported module. I certainly understand the value of being able to work on a mudlib without having to restart the mud. There's a big difference between that and clocking a year of uptime just because you can, though. The MUD that I used to play had scheduled restarts every 2-4 weeks, not to perform updates, but just to restart the process and clear out memory leaks. This never caused any real problem. You knew that it was coming because it was announced, and you took a break for a couple of minutes. If you were AFK, then your auto-login script reconnected you within shortly after the MUD came back up. From best_lay at yahoo.com Tue Mar 1 19:09:56 2016 From: best_lay at yahoo.com (Wildman) Date: Tue, 01 Mar 2016 18:09:56 -0600 Subject: Request More Help With XBM Image References: <8rKdnb6SKYLRIEnLnZ2dnUU7-f3NnZ2d@giganews.com> <34GdnUOxhd5vS0jLnZ2dnUU7-Y3OydjZ@giganews.com> Message-ID: On Tue, 01 Mar 2016 12:56:03 -0600, Wildman wrote: > On Tue, 01 Mar 2016 19:26:55 +0100, Peter Otten wrote: > >> An exception is raised because you pass the command as a single argument > > > > I did not realize that how the command was passed would > make such a difference. I guess I am stuck in my old > VB habits for creating variables. You don't have to > say it, this ain't VB! :-) > > After making the changes to "command = ", it works fine > without the shell. At the risk of sounding redundant, > thank you. Ok, after some thought I think I understand what happened. Since I had the command as a single element, bash was required to parse the command therefore my code would not run without shell=true. That makes sense. I may not be the fastest oar in the water but I will eventually reach the shore. Thanks again for all your help. -- GNU/Linux user #557453 The cow died so I don't need your bull! From rosuav at gmail.com Tue Mar 1 19:13:23 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Mar 2016 11:13:23 +1100 Subject: Reason for not allowing import twice but allowing reload() In-Reply-To: References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> <56d57aa4$0$1586$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Mar 2, 2016 at 9:29 AM, Ian Kelly wrote: > I certainly understand the value of being able to work on a mudlib > without having to restart the mud. There's a big difference between > that and clocking a year of uptime just because you can, though. Oh, sure. I mentioned the year because I have done that once or twice, but it's the week, rather than the year, that's truly important. If something came up that meant I absolutely had to reset everything on a six-monthly basis, no big deal (although I'd rather not have a reset every month). > The MUD that I used to play had scheduled restarts every 2-4 weeks, > not to perform updates, but just to restart the process and clear out > memory leaks. This never caused any real problem. You knew that it was > coming because it was announced, and you took a break for a couple of > minutes. If you were AFK, then your auto-login script reconnected you > within shortly after the MUD came back up. Yeah, and I play one that has semi-scheduled restarts about every 6-10 weeks, for similar reasons (and also for game balance reasons; they deliberately don't save gear across restarts, so people have to gather new gear). I haven't had issues with memory leaks on my server, but it's relatively low traffic. Again, though, if it turned out (under heavier load) that periodic restarts were important, I could design around that requirement, but there's no way I could design around a model of "weekly downtime as the only way to change anything", the way games like Magic: The Gathering Online do. I've once seen them have to do an emergency out-of-band patch - and it took them an hour or something of outage to do it. Unacceptable in my book. ChrisA From steve at pearwood.info Tue Mar 1 20:19:42 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Mar 2016 12:19:42 +1100 Subject: Reason for not allowing import twice but allowing reload() References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> <56d57aa4$0$1586$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56d63fb0$0$1618$c3e8da3$5496439d@news.astraweb.com> On Wed, 2 Mar 2016 09:29 am, Ian Kelly wrote: > There's a big difference between > that and clocking a year of uptime just because you can, though. What other reason is there for having a year of uptime? It's not like it is difficult. My laptop doesn't actually go anywhere: for historical reasons, it's a laptop but it is (mostly) used as a desktop. It sits on my desk. If there's a power outage, the handy built-in UPS (battery) keeps it alive for an hour or two. I come in, I nudge the mouse to wake xscreensaver and authenticate; I do my work; then I run xscreensaver to lock the screen and leave. If I need access to something from home, I can SSH into the office network, and from there into the laptop. The OS is as stable as the surface of the moon, and simply doesn't crash or go down ever. (If only Firefox was as good, alas, but when it does crash it is nearly always because I've allowed Javascript to run on some popular, multimedia-rich, information-free website.) I don't reboot because I don't need to reboot. Why would you reboot just for the sake of rebooting? When I unlock the screen, my system is usable *instantly*. I don't have to open a dozen applications, wait for them to load, authenticate into half a dozen different systems. They're already open. About once a year, or every 18 months or so, I need to reboot to go into Windows. If not for that, and the occasional kernel update, I'd probably never reboot. -- Steven From duncan at invalid.invalid Tue Mar 1 20:42:33 2016 From: duncan at invalid.invalid (duncan smith) Date: Wed, 2 Mar 2016 01:42:33 +0000 Subject: rdflib subclass problem Message-ID: Hello, I'm just getting to grips with RDF and rdflib, and I've hit something I can't figure out. I have a graph with information on two people. (I haven't shown the imports below because they're scattered around my interactive session and I might reconstruct them incorrectly. Anyone familiar with rdflib will probably know what they are.) >>> G = Graph() >>> mark = BNode() >>> nat = BNode() >>> G.add((mark, RDF.type, FOAF.Person)) >>> G.add((mark, FOAF.firstName, Literal('mark'))) >>> G.add((nat, RDF.type, URIRef('Professor'))) >>> G.add((nat, FOAF.firstName, Literal('natalie'))) >>> G.add((URIRef('Professor'), RDFS.subClassOf, FOAF.Person)) >>> So I have specified that mark is a Person, natalie is a Professor, and that Professor is a subclass of Person. (I know that Professor is really a FOAF.title, but I'm just tinkering ATM.) >>> qres = G.query( """SELECT DISTINCT ?aname WHERE { ?a rdf:type foaf:Person . ?a foaf:firstName ?aname . }""", initNs = {"rdf": RDF,"foaf": FOAF}) >>> for row in qres: print "%s is a person" % row mark is a person >>> qres = G.query( """SELECT DISTINCT ?aname WHERE { ?a rdf:type ?prof . ?a foaf:firstName ?aname . }""", initNs = {"rdf": RDF,"foaf": FOAF, "prof": URIRef('Professor')}) >>> for row in qres: print "%s is a Prof" % row natalie is a Prof mark is a Prof >>> But according to the above queries only mark is a Person, and each is a Professor. I would have thought that both would be Persons and only natalie would be a Professor. Can anyone spot where I'm going wrong here? Thanks. Duncan From steve at pearwood.info Tue Mar 1 20:51:42 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Mar 2016 12:51:42 +1100 Subject: Everything good about Python except GUI IDE? References: <64a6599c-fae1-469d-bcee-875165b3cc7d@googlegroups.com> <56d294f8$0$1604$c3e8da3$5496439d@news.astraweb.com> <56d5c4b6$0$1591$c3e8da3$5496439d@news.astraweb.com> <87y4a2ax8g.fsf@elektro.pacujo.net> Message-ID: <56d64730$0$1589$c3e8da3$5496439d@news.astraweb.com> On Wed, 2 Mar 2016 05:06 am, Marko Rauhamaa wrote: > Steven D'Aprano : > >> On Sun, 28 Feb 2016 11:38 pm, BartC wrote: >>> It's the GUI users who are the Neanderthals, having to effectively >>> point at things with sticks. Or have to physically move that rock >>> themselves (ie. drag a file to a wastebasket). >> >> I haven't physically moved an icon to the wastebasket for years. I >> point at the icon, right-click, and tell it "move yourself to the >> trash". > > Do you find that interface convenient? Do you often find yourself > clickety-clicking around to perform bulk file operations? Sometimes. Especially with media files which display a thumbnail, it is far more convenient to be able to look at the icon and recognise the file than to try to guess from the filename "x73nfh.jpg". And having recognised the file visually, its often easier to drag it into the folder of your choice than to type "mv x7 dir" in a separate window. But not always. It's much easier to do "mv foo* dir". Horses for courses. >> Language is pretty important. But when you need to drive a nail into a >> piece of wood, would you rather hit the nail with a hammer, or explain >> to the hammer the precise direction and magnitude of force you would >> like it to apply when it impacts the nails? > > I don't know. My everyday file manipulation needs are so diverse that I > couldn't imagine how a GUI would make my life easier. *shrug* Then perhaps they're not as diverse as you think. > What I'm thinking is, could Python turn into a serious competitor to > bash? The standard shell suffers greatly from sloppy quoting, and many > of the age-old list-processing idioms are more awkward than cute. No. Python's syntax is too wordy to make a good shell. You need brackets and quote marks for everything: # bash ls foo/bar # Python ls("foo/bar") iPython is usable, by adding non-standard syntax to its REPL. I don't think it's a serious contender as replacement for bash, but you could give it a try. But the standard Python REPL? No. > A python shell would need a well-thought-out default import plus a way > to string together external commands. Maybe JSON or similar could be the > standard I/O framing format (instead of SPC-separated fields and > LF-separated records). You really want to be typing JSON by hand instead of space-separated fields/arguments? # Python using JSON ls('["-l", "foo/bar", "spam/ham"]') # bash ls -l foo/bar spam/ham Bugger that for a game of soldiers. -- Steven From rosuav at gmail.com Tue Mar 1 21:15:39 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Mar 2016 13:15:39 +1100 Subject: Everything good about Python except GUI IDE? In-Reply-To: <56d64730$0$1589$c3e8da3$5496439d@news.astraweb.com> References: <64a6599c-fae1-469d-bcee-875165b3cc7d@googlegroups.com> <56d294f8$0$1604$c3e8da3$5496439d@news.astraweb.com> <56d5c4b6$0$1591$c3e8da3$5496439d@news.astraweb.com> <87y4a2ax8g.fsf@elektro.pacujo.net> <56d64730$0$1589$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Mar 2, 2016 at 12:51 PM, Steven D'Aprano wrote: > On Wed, 2 Mar 2016 05:06 am, Marko Rauhamaa wrote: > >> Steven D'Aprano : >> >>> On Sun, 28 Feb 2016 11:38 pm, BartC wrote: >>>> It's the GUI users who are the Neanderthals, having to effectively >>>> point at things with sticks. Or have to physically move that rock >>>> themselves (ie. drag a file to a wastebasket). >>> >>> I haven't physically moved an icon to the wastebasket for years. I >>> point at the icon, right-click, and tell it "move yourself to the >>> trash". >> >> Do you find that interface convenient? Do you often find yourself >> clickety-clicking around to perform bulk file operations? > > Sometimes. Especially with media files which display a thumbnail, it is far > more convenient to be able to look at the icon and recognise the file than > to try to guess from the filename "x73nfh.jpg". And having recognised the > file visually, its often easier to drag it into the folder of your choice > than to type "mv x7 dir" in a separate window. > > But not always. It's much easier to do "mv foo* dir". Horses for > courses. Absolutely. Tab completion *ROCKS* when you know the file name - point-and-click is *SUPERB* when you want to identify things by some form of metadata that the GUI can pull out and display (image/video file thumbnails being one example; executable files can include their own icons, esp on Windows; etcetera). The downside of the GUI, here, is that it sometimes is quite costly to generate those thumbnails; tab completion is done by reading the directory, but thumbnailing a bunch of JPGs requires reading the file contents (even if you were actually planning on clicking on one of the text files in the same directory). Like you say, horses for courses; but in many cases, I'd recommend starting with the cheap option - the command line - and moving to the costlier one only in the situations where you know it's of value. >> What I'm thinking is, could Python turn into a serious competitor to >> bash? The standard shell suffers greatly from sloppy quoting, and many >> of the age-old list-processing idioms are more awkward than cute. > > No. Python's syntax is too wordy to make a good shell. You need brackets and > quote marks for everything: > > # bash > ls foo/bar > > # Python > ls("foo/bar") > > iPython is usable, by adding non-standard syntax to its REPL. I don't think > it's a serious contender as replacement for bash, but you could give it a > try. But the standard Python REPL? No. >> A python shell would need a well-thought-out default import plus a way >> to string together external commands. Maybe JSON or similar could be the >> standard I/O framing format (instead of SPC-separated fields and >> LF-separated records). I think the non-standard syntax plan is the way to do it. But the thing is, you either have a code-like structure where you delimit everything, or you have the messy rules involving quoting and interpolation. The well-established basic shell syntax of space-delimited parameters with optional quoting is a great balance between verbosity and complexity. Not sure what "LF-separated records" has to do with "SPC-separated fields", though. The latter is all about how you type a command, and the former is all about the way different commands interact via stdin and stdout. > You really want to be typing JSON by hand instead of space-separated > fields/arguments? > > # Python using JSON > ls('["-l", "foo/bar", "spam/ham"]') > > # bash > ls -l foo/bar spam/ham > > Bugger that for a game of soldiers. No kidding, but at least it's consistent. Maybe there's a middle-ground, where it's still perfectly consistent, while not being quite as verbose? ChrisA From ian.g.kelly at gmail.com Tue Mar 1 21:22:16 2016 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 1 Mar 2016 19:22:16 -0700 Subject: Reason for not allowing import twice but allowing reload() In-Reply-To: <56d63fb0$0$1618$c3e8da3$5496439d@news.astraweb.com> References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> <56d57aa4$0$1586$c3e8da3$5496439d@news.astraweb.com> <56d63fb0$0$1618$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Mar 1, 2016 at 6:19 PM, Steven D'Aprano wrote: > On Wed, 2 Mar 2016 09:29 am, Ian Kelly wrote: > >> There's a big difference between >> that and clocking a year of uptime just because you can, though. > > What other reason is there for having a year of uptime? > > It's not like it is difficult. My laptop doesn't actually go anywhere: for > historical reasons, it's a laptop but it is (mostly) used as a desktop. It > sits on my desk. If there's a power outage, the handy built-in UPS > (battery) keeps it alive for an hour or two. I come in, I nudge the mouse > to wake xscreensaver and authenticate; I do my work; then I run > xscreensaver to lock the screen and leave. > > If I need access to something from home, I can SSH into the office network, > and from there into the laptop. > > The OS is as stable as the surface of the moon, and simply doesn't crash or > go down ever. (If only Firefox was as good, alas, but when it does crash it > is nearly always because I've allowed Javascript to run on some popular, > multimedia-rich, information-free website.) I don't reboot because I don't > need to reboot. Why would you reboot just for the sake of rebooting? Software updates? The nice thing about *nix systems is that *most* updates don't require a reboot. I'm still going to reboot any time there's a kernel update though, and those are fairly frequent. I could read the patch notes to determine whether this new kernel version is actually important, but it takes less of my time just to go ahead and reboot. With my company-owned Macbook Air, the security policy will eventually schedule a *forced* reboot when there are "critical" updates to be installed. Thankfully the scheduler is pretty good about making sure it's not catching the user at an inopportune moment. From steve at pearwood.info Tue Mar 1 21:22:58 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Mar 2016 13:22:58 +1100 Subject: Everything good about Python except GUI IDE? References: <64a6599c-fae1-469d-bcee-875165b3cc7d@googlegroups.com> <56d294f8$0$1604$c3e8da3$5496439d@news.astraweb.com> <234a398e-1b0f-467b-a8cb-d7ca748f8062@googlegroups.com> <84922f24-3e00-4a23-b26d-5e6c0d8e7e04@googlegroups.com> <87y4a5c58i.fsf@elektro.pacujo.net> <87twksdg9c.fsf@elektro.pacujo.net> <87d1rgca58.fsf@elektro.pacujo.net> <87h9grorcb.fsf@elektro.pacujo.net> <56d5c6fa$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56d64e83$0$1588$c3e8da3$5496439d@news.astraweb.com> On Wed, 2 Mar 2016 05:07 am, Chris Angelico wrote: > On Wed, Mar 2, 2016 at 3:44 AM, Steven D'Aprano > wrote: >> A better analogy is: >> >> When I add cocaine to my stew, the result is a appallingly bad for those >> who eat it. Do you have any idea how rough cocaine is on the human body >> and brain? My wife likes the analogy, being on cocaine is like pressing >> the accelerator of your car all the way to the floor, ALL THE TIME, >> regardless of whether you are moving forward or stopped at the lights. >> And yet, for some reason, people seem to like the cocaine-riddled stew, >> and often ask me to add more cocaine. >> >> People cannot get enough of Javascript, no matter what it does to the >> security and stability of their browser, no matter how many pop-ups it >> launches or how much spyware and malware it installs, or how many times >> it kills their browser. > > s/cocaine/sriracha/ and I would agree with you, because there are > places where JS can majorly enhance a web site, and it isn't going to > kill you if you use it correctly. If by "kill" you mean "compromise your system", then JS absolutely can kill. Running somebody else's code on your machine could have *any* consequence, such as installing spyware, a spam-bot, ransomware, a keylogger that results in your bank account being emptied, or (if the spyware is being run by people who consider you an enemy of the state) literal death via a midnight visit from the secret police or a Hellfire missile fired through your window. https://community.rapid7.com/community/metasploit/blog/2014/01/23/firefox-privileged-payloads http://er.educause.edu/blogs/2016/2/fast-forward-javascript-api-exploits http://arstechnica.com/security/2013/08/attackers-wield-firefox-exploit-to-uncloak-anonymous-tor-users/ https://www.vidder.com/resources/attacks/javascript-device-exploit.html https://www.usenix.org/legacy/event/woot08/tech/full_papers/daniel/daniel_html/ http://www.mcafee.com/threat-intelligence/malware/default.aspx?id=1487635#vtab-characteristics (The last one typos the malware as "Java" code, but if you read on you'll see they actually mean Javascript.) As a web developer, if you host ads, your viewers at the mercy of malware: https://en.wikipedia.org/wiki/Malvertising Most malicious advertising is still written in Flash/ActionScript (a variant of Javascript), but some use Javascript: http://www.pcworld.com/article/3039816/security/malvertising-campaigns-are-becoming-harder-to-detect.html -- Steven From jfong at ms4.hinet.net Tue Mar 1 21:35:10 2016 From: jfong at ms4.hinet.net (jfong at ms4.hinet.net) Date: Tue, 1 Mar 2016 18:35:10 -0800 (PST) Subject: How to know if an object is still be referenced? Message-ID: <8e9f1a84-cced-435e-a379-e1e2ac03f483@googlegroups.com> Recently I was puzzled by a tkinter problem. The codes below (from a book) can display the picture correctly. gifdir = "../gifs/" from tkinter import * win = Tk() photo = PhotoImage(file=gifdir + "ora-pp.gif") Button(win, image=photo).pack() win.mainloop() And the codes below (from another book) will also work. class DrumMachine: .... .... def create_play_bar(self): .... .... photo = PhotoImage(file='images/signature.gif') label = Label(playbar_frame, image=photo) label.image = photo label.grid(row=start_row, column=50, padx=1, sticky='w') .... .... In the second example, I noticed that the "photo" was referenced two times and I think it might be a redundancy so I remove the line "label.image = photo". But it fails then. How can it be? one works and the other not. I search for answers on the web and here are some links talking about it: http://stackoverflow.com/questions/20812579/why-it-shows-blank-instead-of-picture-in-my-tkinter-program http://effbot.org/tkinterbook/photoimage.htm They all said that you have to keep a reference to the "photo" or else it will be garbage collected. Now, as I had learn Python so far, I know that a keyword argument passed in an object instantiation will bind this object to its attribute name, i.e. create a reference to this object. (and it should or the whole language will be in disaster) Can anyone help me out? From termim at gmail.com Tue Mar 1 22:46:26 2016 From: termim at gmail.com (Mike) Date: Tue, 1 Mar 2016 19:46:26 -0800 (PST) Subject: Everything good about Python except GUI IDE? In-Reply-To: <64a6599c-fae1-469d-bcee-875165b3cc7d@googlegroups.com> References: <64a6599c-fae1-469d-bcee-875165b3cc7d@googlegroups.com> Message-ID: <682982e7-33b5-4c6b-9757-3aeaf3f19c3b@googlegroups.com> On Saturday, February 27, 2016 at 6:19:21 AM UTC-5, wrong.a... at gmail.com wrote: > I have some VB forms with more than a hundred objects. If I cannot drag and drop text boxes, list boxes, labels, etc., it will be too much work to create that with several lines of code for each object. > > Isn't there any good GUI IDE like Visual Basic? I hope there are some less well known GUI IDEs which I did not come across. Thanks. I'd recommend PyQt/PySide and Eric as an IDE: http://eric-ide.python-projects.org/index.html Eric has good integration with QtDesigner - you can create forms in designer like in VB and it will automatically generate python code for it or you can load *.ui files dynamically. The project management and VCS integration is also very convenient. Regards, Mikhail From anthony at cajuntechie.org Tue Mar 1 23:29:08 2016 From: anthony at cajuntechie.org (Anthony Papillion) Date: Tue, 1 Mar 2016 22:29:08 -0600 Subject: Sending an email with a binary attachment In-Reply-To: References: <56D54B99.2020206@cajuntechie.org> Message-ID: <56D66C14.1090601@cajuntechie.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 On 03/01/2016 02:03 AM, Chris Angelico wrote: > On Tue, Mar 1, 2016 at 6:58 PM, Anthony Papillion > wrote: >> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 >> >> On 02/29/2016 11:13 AM, Chris Angelico wrote: >>> On Tue, Mar 1, 2016 at 4:08 AM, Peter Pearson >>> wrote: >>>> try: smtp.sendmail(message['From'], message['To'], >>>> message.as_string()) except: print "Message sending has >>>> failed" sys.exit(1) print "Message sending was successful" >>>> sys.exit(0) >>>> >>> >>> This is the problem, right here. Replace this code with: >>> >>> smtp.sendmail(message['From'], message['To'], >>> message.as_string()) >> >> Hmm, I'm a bit confused. Are you saying that the problem is that >> I'm enclosing the code in a Try/Except block? Besides that, I >> don't see anything different. If it's the Try/Except block, how >> do I catch the exception it might generate if I'm not using the >> exception block? >> > > That's exactly the difference. Why do you need to catch the > exception? All you're doing is destroying all the information, > rendering it down to a blunt "has failed". Mostly, I catch exceptions for two reasons: 1) because it's a habit that I've developed over the years and 2) I think unhandled exceptions make things look ugly. Mostly, I catch them from habit though. > > You should catch exceptions if you can actually handle them, but > if all you're doing is printing out a fixed message and aborting, > delete that code. Less code AND a better result. You make some very good points. It's going to take me some time to not catch exceptions by knee-jerk but I can see how doing so can cripple code and make debugging much harder. Thanks for the pointers. Anthony -----BEGIN PGP SIGNATURE----- iQIcBAEBCgAGBQJW1mwTAAoJEAKK33RTsEsV0L4P/jvRCX7w+8iqzlFub0CS35C6 KtuFXLEh+evKGhBecgToCA9eutuvCltknCxJz/Yyd56+QFsze1HHdDWGakuOP/1x gOwzZKr1vsjD4eMkoRRokIVkg437yOju0OReUOATKpYGgwnB6xW9RbOLwHRftXfa pmxg5k2KCBZ1omVLQ1BQcvM48Vi5J4k6IlFAVyM/L3Dzsyj9E1CtJ/VarTwkmAOf RbrBV7EH/k1ELM6yWsm0P00zhQkwZTdKt+Y3OGj7WaYoZXk7D3Q8wJqOJrHgInCr /JjbjX8yHtcVVaIRPKGVGt5PGNDdGvkmI5mJPXL+Io0k8faA4QLqjdCTFniyJ2t3 6HprovGQOJs64WN9RshcCwncJcWLC1wcLWZhZOj9nNZawTM6pWEDFpn1zmg6/lqu DmqhEeudjUtCjRJZr9xey47JJRRkjUrh/g1+VRW+aUfeuIc7xA6Nw7qvf3PqT6tH 8CtVwK9O2sHQ4y8lzAK3vCYY3Lw34qdO2zBC0ycxhMPbk1BqcL5U4WOTDZD/9H3h sh0E19pLYsAtoJpF2tnB2PcJaIWA9Zofz5/K6+5fs5B1wVW34Nu8wz6LMhUR1qSW yJH9Wv8Oznk99qiYUiOiduqGKwLM4+Fg0xYAX1muGNRvLfcYuGDFkyYhdZn9f7dM QdmK/dIaGT9l45hjDQTu =RlhP -----END PGP SIGNATURE----- From ethan at stoneleaf.us Tue Mar 1 23:37:55 2016 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 01 Mar 2016 20:37:55 -0800 Subject: convert Dbase (.dbf) files to SQLite databases In-Reply-To: References: <7c5n8kF25pc8bU1@mid.dfncis.de> <419cc0e0-3a78-4906-8420-c12ce2684bef@c36g2000yqn.googlegroups.com> <56D5C5B2.30106@stoneleaf.us> <56D5C804.9020103@stoneleaf.us> Message-ID: <56D66E23.6000106@stoneleaf.us> On 03/01/2016 06:08 PM, Dennis Lee Bieber wrote: > On Tue, 01 Mar 2016 08:49:08 -0800, Ethan Furman declaimed the following: >> Hmm, looks like that email was sent back in 2009. Sorry for the noise. >> I'm still not able to find a dbf module from John, though. >> > Is it one of: > > https://www.google.com/#q=dbf.py I only checked the first three pages: - 12 refer to mine - 4 refer to pydbf - various others The third page drifts off into non-English languages and non-Python links. A search for his name and dbf also did not reveal anything. Ah well (aka *sigh*). -- ~Ethan~ From marko at pacujo.net Wed Mar 2 00:41:41 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 02 Mar 2016 07:41:41 +0200 Subject: Everything good about Python except GUI IDE? References: <64a6599c-fae1-469d-bcee-875165b3cc7d@googlegroups.com> <56d294f8$0$1604$c3e8da3$5496439d@news.astraweb.com> <56d5c4b6$0$1591$c3e8da3$5496439d@news.astraweb.com> <87y4a2ax8g.fsf@elektro.pacujo.net> <56d64730$0$1589$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87egbtbfmy.fsf@elektro.pacujo.net> Steven D'Aprano : > On Wed, 2 Mar 2016 05:06 am, Marko Rauhamaa wrote: >> A python shell would need a well-thought-out default import plus a >> way to string together external commands. Maybe JSON or similar could >> be the standard I/O framing format (instead of SPC-separated fields >> and LF-separated records). > > You really want to be typing JSON by hand instead of space-separated > fields/arguments? > > # Python using JSON > ls('["-l", "foo/bar", "spam/ham"]') > > # bash > ls -l foo/bar spam/ham > > Bugger that for a game of soldiers. I was talking about JSON for the standard I/O, not the command-line arguments, as in: ps -ef | awk '/httpd/ { print $2 }' where "ps -ef" emits SPC-separated fields and LF-separated records, and awk parses and processes them. Marko From hongyi.zhao at gmail.com Wed Mar 2 00:48:47 2016 From: hongyi.zhao at gmail.com (Hongyi Zhao) Date: Wed, 2 Mar 2016 05:48:47 +0000 (UTC) Subject: Is it possiable to find the fastest ones of dns servers from a huge number of them fastly with python? Message-ID: Hi all, I've a huge number of dns servers, around +5000, and I want to find the top 50 fastest ones out of them for my location. Is it possible for this type of thing using python under my Debian Jessie box? Regards -- .: Hongyi Zhao [ hongyi.zhao AT gmail.com ] Free as in Freedom :. From rosuav at gmail.com Wed Mar 2 00:58:21 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Mar 2016 16:58:21 +1100 Subject: Everything good about Python except GUI IDE? In-Reply-To: <87egbtbfmy.fsf@elektro.pacujo.net> References: <64a6599c-fae1-469d-bcee-875165b3cc7d@googlegroups.com> <56d294f8$0$1604$c3e8da3$5496439d@news.astraweb.com> <56d5c4b6$0$1591$c3e8da3$5496439d@news.astraweb.com> <87y4a2ax8g.fsf@elektro.pacujo.net> <56d64730$0$1589$c3e8da3$5496439d@news.astraweb.com> <87egbtbfmy.fsf@elektro.pacujo.net> Message-ID: On Wed, Mar 2, 2016 at 4:41 PM, Marko Rauhamaa wrote: > Steven D'Aprano : > >> On Wed, 2 Mar 2016 05:06 am, Marko Rauhamaa wrote: >>> A python shell would need a well-thought-out default import plus a >>> way to string together external commands. Maybe JSON or similar could >>> be the standard I/O framing format (instead of SPC-separated fields >>> and LF-separated records). >> >> You really want to be typing JSON by hand instead of space-separated >> fields/arguments? >> >> # Python using JSON >> ls('["-l", "foo/bar", "spam/ham"]') >> >> # bash >> ls -l foo/bar spam/ham >> >> Bugger that for a game of soldiers. > > I was talking about JSON for the standard I/O, not the command-line > arguments, as in: > > ps -ef | awk '/httpd/ { print $2 }' > > where "ps -ef" emits SPC-separated fields and LF-separated records, and > awk parses and processes them. If you want to change that, you have to change the entire ecosystem, not just the shell. You would have to teach every single program to use a different structure. A lot of programs already do support NUL-separation - usually with a -z parameter or something. But you won't be able to magically get them all to use JSON. And I doubt it would be advantageous anyway. ChrisA From rosuav at gmail.com Wed Mar 2 00:59:24 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Mar 2016 16:59:24 +1100 Subject: Is it possiable to find the fastest ones of dns servers from a huge number of them fastly with python? In-Reply-To: References: Message-ID: On Wed, Mar 2, 2016 at 4:48 PM, Hongyi Zhao wrote: > I've a huge number of dns servers, around +5000, and I want to find > the top 50 fastest ones out of them for my location. > > Is it possible for this type of thing using python under my Debian Jessie > box? > Yep! Google "how to get busted for denial of service attacks". Why would you want to test that many DNS servers? ChrisA From hongyi.zhao at gmail.com Wed Mar 2 01:05:26 2016 From: hongyi.zhao at gmail.com (Hongyi Zhao) Date: Wed, 2 Mar 2016 06:05:26 +0000 (UTC) Subject: Is it possiable to find the fastest ones of dns servers from a huge number of them fastly with python? References: Message-ID: On Wed, 02 Mar 2016 16:59:24 +1100, Chris Angelico wrote: > Yep! Google "how to get busted for denial of service attacks". > > Why would you want to test that many DNS servers? I'm from China, and the GFW has blocked many DNS servers. So I must pick out some good for using. > > ChrisA -- .: Hongyi Zhao [ hongyi.zhao AT gmail.com ] Free as in Freedom :. From tjreedy at udel.edu Wed Mar 2 02:03:33 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 2 Mar 2016 02:03:33 -0500 Subject: How to know if an object is still be referenced? In-Reply-To: <8e9f1a84-cced-435e-a379-e1e2ac03f483@googlegroups.com> References: <8e9f1a84-cced-435e-a379-e1e2ac03f483@googlegroups.com> Message-ID: On 3/1/2016 9:35 PM, jfong at ms4.hinet.net wrote: > Recently I was puzzled by a tkinter problem. The codes below (from a book) can display the picture correctly. > > gifdir = "../gifs/" > from tkinter import * > win = Tk() > photo = PhotoImage(file=gifdir + "ora-pp.gif") > Button(win, image=photo).pack() > win.mainloop() Since photo is a global name, the binding remain until you explicitly delete it or exit the app. > And the codes below (from another book) will also work. > > class DrumMachine: > .... > .... > def create_play_bar(self): > .... > .... > photo = PhotoImage(file='images/signature.gif') > label = Label(playbar_frame, image=photo) > label.image = photo > label.grid(row=start_row, column=50, padx=1, sticky='w') > .... > .... Here photo is a local name and the binding disappears when the function exits. I would rewrite it to follow pattern 1. self.photo = PhotoImage(file='images/signature.gif') label = Label(playbar_frame, image=self.photo) To me, saving an attribute reference is not worth the extra line. > In the second example, I noticed that the "photo" was referenced two times > and I think it might be a redundancy so I remove the line "label.image = photo". But it fails then. On another question, I made the same suggestion. Oops. -- Terry Jan Reedy From dieter at handshake.de Wed Mar 2 03:16:14 2016 From: dieter at handshake.de (dieter) Date: Wed, 02 Mar 2016 09:16:14 +0100 Subject: rdflib subclass problem References: Message-ID: <8760x5b8hd.fsf@handshake.de> duncan smith writes: > I'm just getting to grips with RDF and rdflib, and I've hit > something I can't figure out. > > I have a graph with information on two people. (I haven't shown the > imports below because they're scattered around my interactive session > and I might reconstruct them incorrectly. Anyone familiar with rdflib > will probably know what they are.) > > >>>> G = Graph() >>>> mark = BNode() >>>> nat = BNode() >>>> G.add((mark, RDF.type, FOAF.Person)) >>>> G.add((mark, FOAF.firstName, Literal('mark'))) >>>> G.add((nat, RDF.type, URIRef('Professor'))) >>>> G.add((nat, FOAF.firstName, Literal('natalie'))) >>>> G.add((URIRef('Professor'), RDFS.subClassOf, FOAF.Person)) >>>> > > > So I have specified that mark is a Person, natalie is a Professor, and > that Professor is a subclass of Person. (I know that Professor is really > a FOAF.title, but I'm just tinkering ATM.) > > >>>> qres = G.query( > """SELECT DISTINCT ?aname > WHERE { > ?a rdf:type foaf:Person . > ?a foaf:firstName ?aname . > }""", initNs = {"rdf": RDF,"foaf": FOAF}) >>>> for row in qres: > print "%s is a person" % row > > > mark is a person >>>> qres = G.query( > """SELECT DISTINCT ?aname > WHERE { > ?a rdf:type ?prof . > ?a foaf:firstName ?aname . > }""", initNs = {"rdf": RDF,"foaf": FOAF, "prof": > URIRef('Professor')}) >>>> for row in qres: > print "%s is a Prof" % row > > > natalie is a Prof > mark is a Prof >>>> > > > But according to the above queries only mark is a Person, and each is a > Professor. I would have thought that both would be Persons and only > natalie would be a Professor. Can anyone spot where I'm going wrong > here? Thanks. What you observe would be consistent with "RDFS.subClassOf" working in the other direction than the one you expect; i.e. that URIRef('Professor'), RDFS.subClassOf, FOAF.Person means that "Person" is a subclass of "Professor" (not what you expect, that "Professor" is a subclass of "Person"). Carefully check whether "A rel B" means that "B" is in relation "rel" to "A" (I think that is the case) or that "A" is in relation "rel" to "B". From marko at pacujo.net Wed Mar 2 03:20:58 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 02 Mar 2016 10:20:58 +0200 Subject: Everything good about Python except GUI IDE? References: <64a6599c-fae1-469d-bcee-875165b3cc7d@googlegroups.com> <56d294f8$0$1604$c3e8da3$5496439d@news.astraweb.com> <56d5c4b6$0$1591$c3e8da3$5496439d@news.astraweb.com> <87y4a2ax8g.fsf@elektro.pacujo.net> <56d64730$0$1589$c3e8da3$5496439d@news.astraweb.com> <87egbtbfmy.fsf@elektro.pacujo.net> Message-ID: <878u21uw7p.fsf@elektro.pacujo.net> Chris Angelico : > On Wed, Mar 2, 2016 at 4:41 PM, Marko Rauhamaa wrote: >> I was talking about JSON for the standard I/O, not the command-line >> arguments, as in: >> >> ps -ef | awk '/httpd/ { print $2 }' >> >> where "ps -ef" emits SPC-separated fields and LF-separated records, and >> awk parses and processes them. > > If you want to change that, you have to change the entire ecosystem, > not just the shell. You would have to teach every single program to > use a different structure. Correct. There could be translation utilities in the interim. > A lot of programs already do support NUL-separation - usually with a > -z parameter or something. But you won't be able to magically get them > all to use JSON. And I doubt it would be advantageous anyway. The advantages are obvious. Barely any programs do proper escaping, and security problems abound. Maybe a starting point would be a Python Toybox (). Ecosystem intertia aside, key to the success of such an endeavor would be to find a Python equivalent for ps -ef | awk '/httpd/ { print $2 }' that would be at least as convenient for the fingers and the eye. Marko From salvatore.didio at gmail.com Wed Mar 2 03:32:13 2016 From: salvatore.didio at gmail.com (Salvatore DI DIO) Date: Wed, 2 Mar 2016 00:32:13 -0800 (PST) Subject: Explaining names vs variables in Python Message-ID: Hello, I know Python does not have variables, but names. Multiple names cant then be bound to the same objects. So this behavior >>> b = 234 >>> v = 234 >>> b is v True according to the above that is ok But where is the consistency ? if I try : >>> v = 890 >>> w = 890 >>> v is w False It is a little difficult to explain this behavior to a newcommer in Python Can someone give me the right argument to expose ? Regards From jesper at brogAAaard.eu Wed Mar 2 04:03:15 2016 From: jesper at brogAAaard.eu (Jesper K Brogaard) Date: Wed, 2 Mar 2016 10:03:15 +0100 Subject: Explaining names vs variables in Python In-Reply-To: References: Message-ID: <56d6ac61$0$23633$edfadb0f@dtext02.news.tele.dk> Den 02-03-2016 kl. 09:32 skrev Salvatore DI DIO: > Hello, > > I know Python does not have variables, but names. > Multiple names cant then be bound to the same objects. > > So this behavior > >>>> b = 234 >>>> v = 234 >>>> b is v > True > > according to the above that is ok > > > > But where is the consistency ? if I try : > >>>> v = 890 >>>> w = 890 >>>> v is w > False > > It is a little difficult to explain this behavior to a newcommer in Python > > Can someone give me the right argument to expose ? > > Regards > You may get an answer to your question here: http://stackoverflow.com/questions/2419701/python-object-identity-question As I understand it, when you use 'is', you are comparing addresses to objects, not the values contained in the objects. Use '==' instead. Take a look here as well: https://docs.python.org/3.5/reference/datamodel.html -- Venlig hilsen / Best regards Jesper K. Brogaard (remove upper case letters in my e-mail address) From antoon.pardon at rece.vub.ac.be Wed Mar 2 04:08:17 2016 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Wed, 2 Mar 2016 10:08:17 +0100 Subject: Explaining names vs variables in Python In-Reply-To: References: Message-ID: <56D6AD81.3000402@rece.vub.ac.be> On 02/03/2016 09:32, Salvatore DI DIO wrote: > Hello, > > I know Python does not have variables, but names. > Multiple names cant then be bound to the same objects. > > So this behavior Python has variables. They are just not the kind of variables you find in C and variations but more like variables in lisp, scheme and smalltalk. >>>> b = 234 >>>> v = 234 >>>> b is v > True > > according to the above that is ok No that is just a coincidence. A consequent of the particular implimentation, that has prepared a number of number objects beforehand. There is no guarantee in the language that the third statement above will produce True. > But where is the consistency ? if I try : > >>>> v = 890 >>>> w = 890 >>>> v is w > False > > It is a little difficult to explain this behavior to a newcommer in Python. This behaviour is undefined in the language. So there is nothing to explain except that it depends on implementation details. Any program that depends on two variable being the same or not the after similar code is wrong. -- Antoon Pardon From __peter__ at web.de Wed Mar 2 04:12:48 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 02 Mar 2016 10:12:48 +0100 Subject: Effects of caching frequently used objects, was Re: Explaining names vs variables in Python References: Message-ID: Salvatore DI DIO wrote: > Hello, > > I know Python does not have variables, but names. > Multiple names cant then be bound to the same objects. > > So this behavior > >>>> b = 234 >>>> v = 234 >>>> b is v > True > > according to the above that is ok > > > > But where is the consistency ? if I try : > >>>> v = 890 >>>> w = 890 >>>> v is w > False > > It is a little difficult to explain this behavior to a newcommer in Python > > Can someone give me the right argument to expose ? You should not bother with object identity for objects other than None. Some small integers are used a lot, e. g. Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.getrefcount(0) 606 >>> sys.getrefcount(1) 918 >>> sys.getrefcount(256) 31 >>> sys.getrefcount(-1) 51 therefore as an optimization the Python developers decided to put -5...256 (actual range may vary across interpreter versions) into a cache and reuse them rather than build a new object for every instance. This may save both time and memory, but is otherwise irrelevant. Something similar is done for strings: >>> a = "hello" >>> b = "hello" >>> a is b True >>> a = "hello, world" >>> b = "hello, world" >>> a is b False But: >>> a = "hello, world"; b = "hello, world" >>> a is b True Again this is an optimization (mostly targeted at attribute names) which should not affect the behaviour of a properly written Python program. From nomail at invalid.com Wed Mar 2 04:23:56 2016 From: nomail at invalid.com (ast) Date: Wed, 2 Mar 2016 10:23:56 +0100 Subject: What arguments are passed to the __new__ method ? In-Reply-To: <56d5d043$0$632$426a74cc@news.free.fr> References: <56d5d043$0$632$426a74cc@news.free.fr> Message-ID: <56d6b12f$0$3663$426a74cc@news.free.fr> "ast" a ?crit dans le message de news:56d5d043$0$632$426a74cc at news.free.fr... ty for the d?tailed explanations. An other question: What is the very first method launched when an instantiation is done ? e.g obj = MyClass(0, 5, 'xyz') is it __call__ (from object or MyClass if overriden) ? then _call__ launches __new__ and then __init__ This would be coherent with the language or is it __new__ then __init__ as said on courses I read ? From jussi.piitulainen at helsinki.fi Wed Mar 2 04:35:16 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Wed, 02 Mar 2016 11:35:16 +0200 Subject: Explaining names vs variables in Python References: Message-ID: Salvatore DI DIO writes: [- -] > But where is the consistency ? if I try : > >>>> v = 890 >>>> w = 890 >>>> v is w > False I think it goes as follows. Python keeps a cached pool of some numbers that may occur relatively often. When a numerical expression evaluates to a cached value, it returns the cached object instead. >>> 1 + 1 is 2 True >>> 800 + 90 + 0 is 890 False This way programs don't fill the memory with a large number of copies of frequently occurring numbers like 2, and also don't keep rare numbers like 890 around in the cache unnecessarily. Python doesn't keep track of how often numbers actually occur. I think it considers 0, 1, 2, ..., n, up to some rather small n, heuristically frequent, and that's it. Also, this is an implementation detail. Hm, -5, -4, -3, -2, -1 also seem cached when I try them, but -6 not. The following are too delicate for me. I suppose the answers could have been different, but I can't guess what mechanism actually leads to these results. Just idle curiosity on my part. >>> 890 is 890 True >>> id(890) == id(890) True >>> 890 is 891 False >>> id(890) == id(891) False Python 3.4.3 (default, Oct 14 2015, 20:33:09) [GCC 4.8.4] on linux From gordon at address.invalid Wed Mar 2 04:44:52 2016 From: gordon at address.invalid (Gordon Levi) Date: Wed, 02 Mar 2016 20:44:52 +1100 Subject: Everything good about Python except GUI IDE? References: <56d294f8$0$1604$c3e8da3$5496439d@news.astraweb.com> <234a398e-1b0f-467b-a8cb-d7ca748f8062@googlegroups.com> <84922f24-3e00-4a23-b26d-5e6c0d8e7e04@googlegroups.com> <87y4a5c58i.fsf@elektro.pacujo.net> <87twksdg9c.fsf@elektro.pacujo.net> <87d1rgca58.fsf@elektro.pacujo.net> Message-ID: <2gdddbdhdqtobtr21r9ss05m4a52su5efl@4ax.com> Marko Rauhamaa wrote: >Gordon Levi : > >> Nobody likes filling in forms but how do you suggest converting a form >> based app into something loveable. > >Straight HTML does forms just fine without CSS or JavaScript, yet few >can resist. > >> What interface would make you love adding a new contact to your >> address book? > >In my case, the address book is a ~/.mailrc file, which I edit using >emacs. I find it difficult to believe that you _love_ updating your contacts using Emacs even if it gives you an excuse to get some therapy from Eliza. It seems equally unlikely that you can do without phone numbers and addresses for your contacts. From rustompmody at gmail.com Wed Mar 2 05:15:11 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 2 Mar 2016 02:15:11 -0800 (PST) Subject: Reason for not allowing import twice but allowing reload() In-Reply-To: References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> <56d57aa4$0$1586$c3e8da3$5496439d@news.astraweb.com> <56d63fb0$0$1618$c3e8da3$5496439d@news.astraweb.com> Message-ID: <909e223a-c9e6-4161-92fc-74cd1644869e@googlegroups.com> On Wednesday, March 2, 2016 at 7:53:10 AM UTC+5:30, Ian wrote: > On Tue, Mar 1, 2016 at 6:19 PM, Steven D'Aprano wrote: > > On Wed, 2 Mar 2016 09:29 am, Ian Kelly wrote: > > > >> There's a big difference between > >> that and clocking a year of uptime just because you can, though. > > > > What other reason is there for having a year of uptime? > > > > It's not like it is difficult. My laptop doesn't actually go anywhere: for > > historical reasons, it's a laptop but it is (mostly) used as a desktop. It > > sits on my desk. If there's a power outage, the handy built-in UPS > > (battery) keeps it alive for an hour or two. I come in, I nudge the mouse > > to wake xscreensaver and authenticate; I do my work; then I run > > xscreensaver to lock the screen and leave. > > > > If I need access to something from home, I can SSH into the office network, > > and from there into the laptop. > > > > The OS is as stable as the surface of the moon, and simply doesn't crash or > > go down ever. (If only Firefox was as good, alas, but when it does crash it > > is nearly always because I've allowed Javascript to run on some popular, > > multimedia-rich, information-free website.) I don't reboot because I don't > > need to reboot. Why would you reboot just for the sake of rebooting? > > Software updates? The nice thing about *nix systems is that *most* > updates don't require a reboot. I'm still going to reboot any time > there's a kernel update though, and those are fairly frequent. I could > read the patch notes to determine whether this new kernel version is > actually important, but it takes less of my time just to go ahead and > reboot. Dunno what systems you folks use... My ubuntu(s) 15.10 seem to (my estimates not hard data) - update every couple of days - kernel/security updates every 2-3 weeks "Stable as the surface of the moon"?? Well thats strong The other day I - aptitude purge-d the kernel I was running on [I was trying to show off to someone that ubuntu would not allow that!] - machine kept running merrily but thereafter aptitude crashed - Until I rebooted an older kernel; installed the one I had removed and rebooted to that From steve at pearwood.info Wed Mar 2 05:16:38 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Mar 2016 21:16:38 +1100 Subject: Explaining names vs variables in Python References: Message-ID: <56d6bd88$0$22141$c3e8da3$5496439d@news.astraweb.com> On Wed, 2 Mar 2016 07:32 pm, Salvatore DI DIO wrote: > Hello, > > I know Python does not have variables, but names. > Multiple names cant then be bound to the same objects. Multiple names CAN be bound to the same object: py> x = y = [] py> x is y True py> z = x py> y.append("Hello world!") py> z ['Hello world!'] So that is *three* names bound to the same list object. > So this behavior > >>>> b = 234 >>>> v = 234 >>>> b is v > True > > according to the above that is ok When I try that in different versions of Python, I get different results: # Python 2.4 py> b = 234 py> v = 234 py> b is v False What you are seeing is a version-dependent optimization. Not all versions of Python will behave the same way. The reason you can do that is that integers are immutable objects and cannot be modified. So the Python interpreter will cache some integers, and avoid creating new objects. So: py> a, b = 50, 9999 py> c, d = 50, 9999 py> a is c # the same object is reused for 50 each time True py> c is d # new int objects are created for 9999 each time False In Python 2.7, I think that the interpreter caches small ints from -1 to 255. But do not rely on this, because it is just an optimization and can and will change from version to version. You should never use `is` to test for equality. Use == to test for equality. Use `is` *only* to test for object identity ("the same object"). -- Steven From rustompmody at gmail.com Wed Mar 2 05:19:14 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 2 Mar 2016 02:19:14 -0800 (PST) Subject: Reason for not allowing import twice but allowing reload() In-Reply-To: <909e223a-c9e6-4161-92fc-74cd1644869e@googlegroups.com> References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> <56d57aa4$0$1586$c3e8da3$5496439d@news.astraweb.com> <56d63fb0$0$1618$c3e8da3$5496439d@news.astraweb.com> <909e223a-c9e6-4161-92fc-74cd1644869e@googlegroups.com> Message-ID: On Wednesday, March 2, 2016 at 3:45:28 PM UTC+5:30, Rustom Mody wrote: > On Wednesday, March 2, 2016 at 7:53:10 AM UTC+5:30, Ian wrote: > > On Tue, Mar 1, 2016 at 6:19 PM, Steven D'Aprano wrote: > > > On Wed, 2 Mar 2016 09:29 am, Ian Kelly wrote: > > > > > >> There's a big difference between > > >> that and clocking a year of uptime just because you can, though. > > > > > > What other reason is there for having a year of uptime? > > > > > > It's not like it is difficult. My laptop doesn't actually go anywhere: for > > > historical reasons, it's a laptop but it is (mostly) used as a desktop. It > > > sits on my desk. If there's a power outage, the handy built-in UPS > > > (battery) keeps it alive for an hour or two. I come in, I nudge the mouse > > > to wake xscreensaver and authenticate; I do my work; then I run > > > xscreensaver to lock the screen and leave. > > > > > > If I need access to something from home, I can SSH into the office network, > > > and from there into the laptop. > > > > > > The OS is as stable as the surface of the moon, and simply doesn't crash or > > > go down ever. (If only Firefox was as good, alas, but when it does crash it > > > is nearly always because I've allowed Javascript to run on some popular, > > > multimedia-rich, information-free website.) I don't reboot because I don't > > > need to reboot. Why would you reboot just for the sake of rebooting? > > > > Software updates? The nice thing about *nix systems is that *most* > > updates don't require a reboot. I'm still going to reboot any time > > there's a kernel update though, and those are fairly frequent. I could > > read the patch notes to determine whether this new kernel version is > > actually important, but it takes less of my time just to go ahead and > > reboot. > > Dunno what systems you folks use... > My ubuntu(s) 15.10 seem to (my estimates not hard data) > - update every couple of days > - kernel/security updates every 2-3 weeks > > "Stable as the surface of the moon"?? > Well thats strong > The other day I > - aptitude purge-d the kernel I was running on > [I was trying to show off to someone that ubuntu would not allow that!] > - machine kept running merrily but thereafter aptitude crashed > - Until I rebooted an older kernel; installed the one I had removed and rebooted to that Right now as I write this a libssl security update. No suggested reboot But I should be rebooting if I were paranoid about security From steve at pearwood.info Wed Mar 2 05:32:36 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Mar 2016 21:32:36 +1100 Subject: Explaining names vs variables in Python References: <56d6ac61$0$23633$edfadb0f@dtext02.news.tele.dk> Message-ID: <56d6c146$0$1615$c3e8da3$5496439d@news.astraweb.com> On Wed, 2 Mar 2016 08:03 pm, Jesper K Brogaard wrote: > As I understand it, when you use 'is', you are comparing addresses to > objects, not the values contained in the objects. Use '==' instead. You should not think about addresses, because the location of objects is not part of the language. It is implementation-dependent. In CPython, objects are fixed to a single location in the heap, and will never move. But in Jython and IronPython, objects in the python layer are based on JVM (Java Virtual Machine) and CLR (Common Language Runtime) objects, which can move around in memory. Both the JVM and the CLR can move objects, so the location is not constant. Likewise for PyPy, which can delete and re-create objects behind the scenes, possibly in different memory locations. This is why the id() function is NOT documented as returning the address of an object, but of returning an ID number. Let's look at IDs in IronPython: >>> a, b, c = [], 10000, "Hello world!" >>> print id(a), id(b), id(c), id(None) 43 44 45 0 And in Jython: >>> a, b, c = [], 10000, "Hello world!" >>> print id(a), id(b), id(c), id(None) 1 2 3 4 -- Steven From salvatore.didio at gmail.com Wed Mar 2 05:51:08 2016 From: salvatore.didio at gmail.com (Salvatore DI DIO) Date: Wed, 2 Mar 2016 02:51:08 -0800 (PST) Subject: Explaining names vs variables in Python (follow) Message-ID: <4a2dcc0b-dfa7-437c-9f10-876becd9fca9@googlegroups.com> Thank you very much all of you. I better understand now Regards From nomail at invalid.com Wed Mar 2 05:52:54 2016 From: nomail at invalid.com (ast) Date: Wed, 2 Mar 2016 11:52:54 +0100 Subject: Explaining names vs variables in Python In-Reply-To: References: Message-ID: <56d6c608$0$663$426a74cc@news.free.fr> "Salvatore DI DIO" a ?crit dans le message de news:a894d5ed-d906-4ff7-a537-32bf0187e062 at googlegroups.com... > It is a little difficult to explain this behavior to a newcommer in Python > Can someone give me the right argument to expose ? It is explained with many details here: http://blog.lerner.co.il/why-you-should-almost-never-use-is-in-python/ From salvatore.didio at gmail.com Wed Mar 2 05:58:03 2016 From: salvatore.didio at gmail.com (Salvatore DI DIO) Date: Wed, 2 Mar 2016 02:58:03 -0800 (PST) Subject: Explaining names vs variables in Python In-Reply-To: <56d6c608$0$663$426a74cc@news.free.fr> References: <56d6c608$0$663$426a74cc@news.free.fr> Message-ID: <14e2ffdb-83ea-4241-b6ff-3978707798b0@googlegroups.com> Thank you very much ast and all of you. I better understant now Regards From steve at pearwood.info Wed Mar 2 06:02:37 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Mar 2016 22:02:37 +1100 Subject: What arguments are passed to the __new__ method ? References: <56d5d043$0$632$426a74cc@news.free.fr> <56d6b12f$0$3663$426a74cc@news.free.fr> Message-ID: <56d6c84f$0$1621$c3e8da3$5496439d@news.astraweb.com> On Wed, 2 Mar 2016 08:23 pm, ast wrote: > An other question: > > What is the very first method launched when an instantiation is done ? > e.g obj = MyClass(0, 5, 'xyz') > > is it __call__ (from object or MyClass if overriden) ? No, not object or MyClass. The *metaclass* __call__ is called. For most objects, the metaclass is `type`. The metaclass is the type of the class: classes are objects too, which means that like all objects, they have a class. That is the metaclass. *** WARNING *** Metaclasses are a very advanced technique. You are not expected to understand this. > then _call__ launches __new__ and then __init__ > This would be coherent with the language > > or is it __new__ then __init__ as said on courses I read ? Let us create a metaclass that inherits from `type`: class Meta(type): def __new__(meta, name, bases, namespace): print "**Creating new Meta instance" print "Metaclass:", meta print "New class name:", name print "Base classes used:", bases print "Namespace used as class dict:", namespace return type.__new__(meta, name, bases, namespace) def __init__(cls, *args): print "**Initialising Meta instance %s" % cls def __call__(cls): print "**Calling Meta instance %s" % cls return super(Meta, cls).__call__() Now let me use that metaclass to create a new class: class MyClass(object): __metaclass__ = Meta def __new__(cls): print "^^Creating new instance of %s" % cls return super(MyClass, cls).__new__(cls) def __init__(self): print "^^Initialising MyClass instance %s" % self def __call__(self): print "^^Calling MyClass instance %s" % self return "Hello World!" which prints: **Creating new Meta instance Metaclass: New class name: MyClass Base classes used: (,) Namespace used as class dict: {'__call__': , '__module__': '__main__', '__metaclass__': , '__new__': , '__init__': } **Initialising Meta instance Now let me create a new MyClass instance: instance = MyClass() which prints: **Calling Meta instance ^^Creating new instance of ^^Initialising MyClass instance <__main__.MyClass object at 0xb7cf2bec> Finally, let me call the instance: print instance() which prints: ^^Calling MyClass instance <__main__.MyClass object at 0xb7cf2bec> Hello World! -- Steven From jfong at ms4.hinet.net Wed Mar 2 06:35:11 2016 From: jfong at ms4.hinet.net (jfong at ms4.hinet.net) Date: Wed, 2 Mar 2016 03:35:11 -0800 (PST) Subject: How to know if an object is still be referenced? In-Reply-To: References: <8e9f1a84-cced-435e-a379-e1e2ac03f483@googlegroups.com> Message-ID: Terry Reedy at 2016/3/2 UTC+8 3:04:10PM wrote? > On 3/1/2016 9:35 PM, jfong at ms4.hinet.net wrote: > > Recently I was puzzled by a tkinter problem. The codes below (from a book) can display the picture correctly. > > > > gifdir = "../gifs/" > > from tkinter import * > > win = Tk() > > photo = PhotoImage(file=gifdir + "ora-pp.gif") > > Button(win, image=photo).pack() > > win.mainloop() > > Since photo is a global name, the binding remain until you explicitly > delete it or exit the app. > > > And the codes below (from another book) will also work. > > > > class DrumMachine: > > .... > > .... > > def create_play_bar(self): > > .... > > .... > > photo = PhotoImage(file='images/signature.gif') > > label = Label(playbar_frame, image=photo) > > label.image = photo > > label.grid(row=start_row, column=50, padx=1, sticky='w') > > .... > > .... > > Here photo is a local name and the binding disappears when the function > exits. I would rewrite it to follow pattern 1. > > self.photo = PhotoImage(file='images/signature.gif') > label = Label(playbar_frame, image=self.photo) > > To me, saving an attribute reference is not worth the extra line. > > > In the second example, I noticed that the "photo" was referenced two times > > and I think it might be a redundancy so I remove the line "label.image = photo". But it fails then. > > On another question, I made the same suggestion. Oops. > > -- > Terry Jan Reedy Thanks, Terry. After reading your reply I noticed that I had make a mistake. The "image" is not an attribute of the Button. It's an option. The "label.image=photo" does a different thing. But it didn't help on solving my puzzle. If the problem was caused by the "photo" is a local, then binding the "photo" to an local attribute ("label" is a local too) seems no meaning at all. But it did make difference! No idea how the underneath mechanism works. I run this example under the pdb and it can display the picture correctly even without the "label.image=photo" statement. Why it fails on running at real time? tk event scheduling? I don't know. --Jach From marko at pacujo.net Wed Mar 2 06:57:41 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 02 Mar 2016 13:57:41 +0200 Subject: Everything good about Python except GUI IDE? References: <56d294f8$0$1604$c3e8da3$5496439d@news.astraweb.com> <234a398e-1b0f-467b-a8cb-d7ca748f8062@googlegroups.com> <84922f24-3e00-4a23-b26d-5e6c0d8e7e04@googlegroups.com> <87y4a5c58i.fsf@elektro.pacujo.net> <87twksdg9c.fsf@elektro.pacujo.net> <87d1rgca58.fsf@elektro.pacujo.net> <2gdddbdhdqtobtr21r9ss05m4a52su5efl@4ax.com> Message-ID: <8737s9um6i.fsf@elektro.pacujo.net> Gordon Levi : > I find it difficult to believe that you _love_ updating your contacts > using Emacs even if it gives you an excuse to get some therapy from > Eliza. It seems equally unlikely that you can do without phone numbers > and addresses for your contacts. WP8 doesn't allow me to modify the contacts using emacs. And to my knowledge, emacs still doesn't have a phone-call-mode. I *love* using emacs for everything I can because the whole gamut of emacs' typing machinery is at my disposal. I readily admit that reading Wikipedia articles still works better with Firefox than emacs. Marko From marko at pacujo.net Wed Mar 2 07:34:36 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 02 Mar 2016 14:34:36 +0200 Subject: Explaining names vs variables in Python References: <56d6ac61$0$23633$edfadb0f@dtext02.news.tele.dk> <56d6c146$0$1615$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87y4a1t5wj.fsf@elektro.pacujo.net> Steven D'Aprano : > On Wed, 2 Mar 2016 08:03 pm, Jesper K Brogaard wrote: > >> As I understand it, when you use 'is', you are comparing addresses to >> objects, not the values contained in the objects. Use '==' instead. > > You should not think about addresses, because the location of objects > is not part of the language. It is implementation-dependent. The ontological question is, can two *distinct* objects with *identical* characteristics exist? The fermionic answer is, no. The bosonic answer is, sure. Set theory has fermionic ontology (it's called extensionality). Python sits on the fence on that one, allowing either ontology. > This is why the id() function is NOT documented as returning the > address of an object, but of returning an ID number. Let's look at IDs > in IronPython: > >>>> a, b, c = [], 10000, "Hello world!" >>>> print id(a), id(b), id(c), id(None) > 43 44 45 0 > > > And in Jython: > >>>> a, b, c = [], 10000, "Hello world!" >>>> print id(a), id(b), id(c), id(None) > 1 2 3 4 Python doesn't define or use the concept of an "address." Marko From rosuav at gmail.com Wed Mar 2 07:50:19 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 2 Mar 2016 23:50:19 +1100 Subject: Explaining names vs variables in Python In-Reply-To: <87y4a1t5wj.fsf@elektro.pacujo.net> References: <56d6ac61$0$23633$edfadb0f@dtext02.news.tele.dk> <56d6c146$0$1615$c3e8da3$5496439d@news.astraweb.com> <87y4a1t5wj.fsf@elektro.pacujo.net> Message-ID: On Wed, Mar 2, 2016 at 11:34 PM, Marko Rauhamaa wrote: > The ontological question is, can two *distinct* objects with *identical* > characteristics exist? > > The fermionic answer is, no. > > The bosonic answer is, sure. > > Set theory has fermionic ontology (it's called extensionality). > > Python sits on the fence on that one, allowing either ontology. Python defines that every object has an identity, which can be represented as an integer. Since this is an intrinsic part of the object, no two distinct objects can truly have identical characteristics. Python's objects are like rifles - there are many like it, but this one is mine. ChrisA From jussi.piitulainen at helsinki.fi Wed Mar 2 08:11:39 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Wed, 02 Mar 2016 15:11:39 +0200 Subject: Explaining names vs variables in Python References: <56d6ac61$0$23633$edfadb0f@dtext02.news.tele.dk> <56d6c146$0$1615$c3e8da3$5496439d@news.astraweb.com> <87y4a1t5wj.fsf@elektro.pacujo.net> Message-ID: Chris Angelico writes: > Python defines that every object has an identity, which can be > represented as an integer. Since this is an intrinsic part of the > object, no two distinct objects can truly have identical > characteristics. Python's objects are like rifles - there are many > like it, but this one is mine. Rifles are not mines. A rifle hurts you from a distance. A mine hurts you when you step on it. From marko at pacujo.net Wed Mar 2 08:39:36 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 02 Mar 2016 15:39:36 +0200 Subject: Explaining names vs variables in Python References: <56d6ac61$0$23633$edfadb0f@dtext02.news.tele.dk> <56d6c146$0$1615$c3e8da3$5496439d@news.astraweb.com> <87y4a1t5wj.fsf@elektro.pacujo.net> Message-ID: <87twkpt2w7.fsf@elektro.pacujo.net> Chris Angelico : > Python defines that every object has an identity, which can be > represented as an integer. Since this is an intrinsic part of the > object, no two distinct objects can truly have identical > characteristics. Python's objects are like rifles - there are many > like it, but this one is mine. How can you be sure Python isn't returning the same id value for two distinct objects? Marko From rosuav at gmail.com Wed Mar 2 08:48:35 2016 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 3 Mar 2016 00:48:35 +1100 Subject: Explaining names vs variables in Python In-Reply-To: <87twkpt2w7.fsf@elektro.pacujo.net> References: <56d6ac61$0$23633$edfadb0f@dtext02.news.tele.dk> <56d6c146$0$1615$c3e8da3$5496439d@news.astraweb.com> <87y4a1t5wj.fsf@elektro.pacujo.net> <87twkpt2w7.fsf@elektro.pacujo.net> Message-ID: On Thu, Mar 3, 2016 at 12:39 AM, Marko Rauhamaa wrote: > Chris Angelico : > >> Python defines that every object has an identity, which can be >> represented as an integer. Since this is an intrinsic part of the >> object, no two distinct objects can truly have identical >> characteristics. Python's objects are like rifles - there are many >> like it, but this one is mine. > > How can you be sure Python isn't returning the same id value for two > distinct objects? The same way I can be sure about anything else in Python. It's a language guarantee. If you're bothered by that, you should also be concerned that str(x) might not actually call x.__str__(), or that a+b*c might evaluate the addition before the multiplication. ChrisA From fabien.maussion at gmail.com Wed Mar 2 09:05:46 2016 From: fabien.maussion at gmail.com (Fabien) Date: Wed, 2 Mar 2016 15:05:46 +0100 Subject: urlopen, six, and py2 Message-ID: Hi, it seems that urlopen had no context manager for versions < 3. The following code therefore will crash on py2 but not on py3. from six.moves.urllib.request import urlopen with urlopen('http://www.google.com') as resp: _ = resp.read() Error: AttributeError: addinfourl instance has no attribute '__exit__' I actually wonder if this is not something that the six library should take care of upstream, but in the meantime I could simply do what is suggested on this stackoverflow post: http://stackoverflow.com/questions/30627937/tracebaclk-attributeerroraddinfourl-instance-has-no-attribute-exit My question is: why does the python3 version need a "with" block while the python2 version doesn't? Can I skip the "with" entirely, or should I rather do the following: from six.moves.urllib.request import urlopen try: with urlopen('http://www.google.com') as resp: _ = resp.read() except AttributeError: # python 2 resp = urlopen('http://www.google.com') _ = resp.read() (which is quite ugly). Thanks! Fabien From marko at pacujo.net Wed Mar 2 09:11:55 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 02 Mar 2016 16:11:55 +0200 Subject: Explaining names vs variables in Python References: <56d6ac61$0$23633$edfadb0f@dtext02.news.tele.dk> <56d6c146$0$1615$c3e8da3$5496439d@news.astraweb.com> <87y4a1t5wj.fsf@elektro.pacujo.net> <87twkpt2w7.fsf@elektro.pacujo.net> Message-ID: <87povdt1ec.fsf@elektro.pacujo.net> Chris Angelico : > On Thu, Mar 3, 2016 at 12:39 AM, Marko Rauhamaa wrote: >> Chris Angelico : >> >>> Python defines that every object has an identity, which can be >>> represented as an integer. Since this is an intrinsic part of the >>> object, no two distinct objects can truly have identical >>> characteristics. Python's objects are like rifles - there are many >>> like it, but this one is mine. >> >> How can you be sure Python isn't returning the same id value for two >> distinct objects? > > The same way I can be sure about anything else in Python. It's a > language guarantee. Actually, my question is (intentionally) nonsensical. The sameness or distinctness of two objects is not directly defined in Python. The definition is simply: Two objects X and Y are called identical if X is Y evaluates to a true value. Additionally, we have: If objects X and Y are identical, it is guaranteed that id(X) == id(Y) evaluates to a true value. Even more strongly, we have: For any objects X and Y, id(X) == id(Y) if X is Y else id(X) != id(Y) evaluates to a true value. What is missing is the rules that are obeyed by the "is" operator. Marko From m at funkyhat.org Wed Mar 2 09:35:20 2016 From: m at funkyhat.org (Matt Wheeler) Date: Wed, 2 Mar 2016 14:35:20 +0000 Subject: urlopen, six, and py2 In-Reply-To: References: Message-ID: On 2 March 2016 at 14:05, Fabien wrote: > [snip] > My question is: why does the python3 version need a "with" block while the > python2 version doesn't? Can I skip the "with" entirely, or should I rather > do the following: It's not a case of "need", using the "with" construction is an added feature, not a burden! > from six.moves.urllib.request import urlopen > > try: > with urlopen('http://www.google.com') as resp: > _ = resp.read() > except AttributeError: > # python 2 > resp = urlopen('http://www.google.com') > _ = resp.read() This is poor practise as you aren't closing "resp". This leaves state lying around that you don't need anymore, which is the whole purpose of the context manager that 3 provides. It will *usually* be cleaned up when leaving the current scope, but won't if there is an exception thrown. Using the context manager ensures resp is *always* cleaned up properly even if an exception is thrown. I agree that six should probably handle this, but in the meantime you could use contextlib.closing ([1]) rather than rolling your own. It even uses urlopen as an example. If you absolutely want to roll your own then don't bother with the context manager provided by 3 at all, just use: resp = urlopen('http://www.google.com') try: _ = resp.read() finally: resp.close() But as this is wordier and more fragile than using a context manager to clean up for you, I expect you won't bother :). [1] https://docs.python.org/2/library/contextlib.html#contextlib.closing -- Matt Wheeler http://funkyh.at From rosuav at gmail.com Wed Mar 2 09:53:05 2016 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 3 Mar 2016 01:53:05 +1100 Subject: urlopen, six, and py2 In-Reply-To: References: Message-ID: On Thu, Mar 3, 2016 at 1:35 AM, Matt Wheeler wrote: >> from six.moves.urllib.request import urlopen >> >> try: >> with urlopen('http://www.google.com') as resp: >> _ = resp.read() >> except AttributeError: >> # python 2 >> resp = urlopen('http://www.google.com') >> _ = resp.read() > > This is poor practise as you aren't closing "resp". > This leaves state lying around that you don't need anymore, which is > the whole purpose of the context manager that 3 provides. > It will *usually* be cleaned up when leaving the current scope, but > won't if there is an exception thrown. Using the context manager > ensures resp is *always* cleaned up properly even if an exception is > thrown. Not sure why you say it won't if there's an exception thrown. This code will do the same thing on both versions: def get_data(): resp = urlopen('http://www.google.com') return resp.read() Absent the context manager, this depends on object disposal for its cleanup. But whether this function returns normally or raises an exception, the response object goes out of scope at the same time. There's no guarantee that it'll be cleaned up immediately when the function exits, but it's the same for the exceptional and non-exceptional cases. Agreed that try/finally is the best way to do cross-platform code here: def get_data(): resp = urlopen('http://www.google.com') try: return resp.read() finally: resp.close() It's reasonably compact, and fairly clear. And it has the exact guarantee that the context manager has (before the function exits, the 'finally' block will be performed, and resources will be properly released). ChrisA From rustompmody at gmail.com Wed Mar 2 10:08:19 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 2 Mar 2016 07:08:19 -0800 (PST) Subject: Explaining names vs variables in Python In-Reply-To: <87povdt1ec.fsf@elektro.pacujo.net> References: <56d6ac61$0$23633$edfadb0f@dtext02.news.tele.dk> <56d6c146$0$1615$c3e8da3$5496439d@news.astraweb.com> <87y4a1t5wj.fsf@elektro.pacujo.net> <87twkpt2w7.fsf@elektro.pacujo.net> <87povdt1ec.fsf@elektro.pacujo.net> Message-ID: On Wednesday, March 2, 2016 at 7:42:09 PM UTC+5:30, Marko Rauhamaa wrote: > Chris Angelico : > > > On Thu, Mar 3, 2016 at 12:39 AM, Marko Rauhamaa wrote: > >> Chris Angelico : > >> > >>> Python defines that every object has an identity, which can be > >>> represented as an integer. Since this is an intrinsic part of the > >>> object, no two distinct objects can truly have identical > >>> characteristics. Python's objects are like rifles - there are many > >>> like it, but this one is mine. > >> > >> How can you be sure Python isn't returning the same id value for two > >> distinct objects? > > > > The same way I can be sure about anything else in Python. It's a > > language guarantee. > > Actually, my question is (intentionally) nonsensical. > > The sameness or distinctness of two objects is not directly defined in > Python. The definition is simply: > > Two objects X and Y are called identical if > > X is Y > > evaluates to a true value. > > Additionally, we have: > > If objects X and Y are identical, it is guaranteed that > > id(X) == id(Y) > > evaluates to a true value. > > Even more strongly, we have: > > For any objects X and Y, > > id(X) == id(Y) if X is Y else id(X) != id(Y) > > evaluates to a true value. > > What is missing is the rules that are obeyed by the "is" operator. is is not is is is was [fermionic or bosonic?] From ian.g.kelly at gmail.com Wed Mar 2 10:13:16 2016 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 2 Mar 2016 08:13:16 -0700 Subject: Explaining names vs variables in Python In-Reply-To: References: Message-ID: On Wed, Mar 2, 2016 at 2:35 AM, Jussi Piitulainen wrote: > The following are too delicate for me. I suppose the answers could have > been different, but I can't guess what mechanism actually leads to these > results. Just idle curiosity on my part. > >>>> 890 is 890 > True >>>> id(890) == id(890) > True This has to do with the way code blocks are compiled. In the interactive interpreter, a single line like '890 is 890' is compiled to a single code object. The constant 890 appears twice in the same code block, so the optimizer uses the same constant for both. Note in the following that the same index appears for both, so they're actually the same object reference. >>> import dis >>> dis.dis('890 is 890') 1 0 LOAD_CONST 0 (890) 3 LOAD_CONST 0 (890) 6 COMPARE_OP 8 (is) 9 RETURN_VALUE >>> compile('890 is 890', '', 'exec').co_consts (890, None) As for the earlier example of: >>>> 1 + 1 is 2 > True >>>> 800 + 90 + 0 is 890 > False This one actually surprises me a little, because the optimizer is also smart enough to evaluate '800 + 90 + 0' and just store a constant of 890: >>> dis.dis('800 + 90 + 0 is 890') 1 0 LOAD_CONST 5 (890) 3 LOAD_CONST 3 (890) 6 COMPARE_OP 8 (is) 9 RETURN_VALUE >>> compile('800 + 90 + 0 is 890', '', 'exec').co_consts (800, 90, 0, 890, None, 890, 890) Not smart enough to reuse the existing reference in this case apparently, or even to prune out the original constants that are no longer used in the code. From invalid at invalid.invalid Wed Mar 2 10:15:29 2016 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 2 Mar 2016 15:15:29 +0000 (UTC) Subject: Reason for not allowing import twice but allowing reload() References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> <56d57aa4$0$1586$c3e8da3$5496439d@news.astraweb.com> <56d63fb0$0$1618$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2016-03-02, Ian Kelly wrote: > Software updates? The nice thing about *nix systems is that *most* > updates don't require a reboot. I'm still going to reboot any time > there's a kernel update though, and those are fairly frequent. I could > read the patch notes to determine whether this new kernel version is > actually important, but it takes less of my time just to go ahead and > reboot. I try to remember to reboot every couple weeks or so even without a kernel update. There sometimes updates to things like the "rc" stuff or udev or whatnot which occasionally cause boot-time problems. If you let too much time go by between reboots, and something that happend several months ago is going to cause a problem at boot time, that reboot is guaranteed to happen when it's the most inconvenient. And it's a lot easier to figure out the problem when it's due to a recent update. > With my company-owned Macbook Air, the security policy will > eventually schedule a *forced* reboot when there are "critical" > updates to be installed. Thankfully the scheduler is pretty good > about making sure it's not catching the user at an inopportune > moment. -- Grant Edwards grant.b.edwards Yow! Let's all show human at CONCERN for REVERAND MOON's gmail.com legal difficulties!! From rustompmody at gmail.com Wed Mar 2 10:22:12 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 2 Mar 2016 07:22:12 -0800 (PST) Subject: Correct IDLE usage (was Reason for not allowing import twice but allowing reload()) In-Reply-To: References: <645cdd46-d4a4-49b3-a0d8-848608d70d73@googlegroups.com> <075122af-1a9c-44b6-97bb-521ebcb3e4ae@googlegroups.com> Message-ID: <0815b19e-ded3-4dc2-8d83-54bc6ed2f42d@googlegroups.com> On Tuesday, March 1, 2016 at 12:23:02 PM UTC+5:30, Terry Reedy wrote: > On 2/29/2016 7:42 AM, Rustom Mody wrote: > > > Is import needed at all when trying out in Idle? > ... > > So it does appear that > > 1. import not necessary with(in) idle > > 2. However import and f5 (ie is run as main) are different > > > > May some idle experts elaborate on this? Whats the idle idiom of import-ing? > > Rustom, since I know that you are not a rank beginner, I have trouble > understanding what you are asking. Heh! I know some things; dont know many things > F5 when editing foo.py is equivalent > to running "python -i foo.py" on a command line while 'in' the directory > containing foo.py. In both cases, foo.py is run as a main module, with > __name__ == '__main__'. The difference is that F5 runs foo.py under > IDLE supervision, with results going into and interactive inputs coming > from IDLE shell instead of the console interpreter. > > Imports are used in a module to access objects within the imported module. Let me try to explain again There is import and import. There is the formal meaning of the import keyword in python -- call it import-f There is the informal expectation and need of programmers to 'pull something into python' -- call it import-i That there is some cognitive dissonance between import-f and import-i is seen in the OP's question itself; also Chris' "I dont believe the language should be changed" So the question is around: What is the best practice for doing import-i in python? As the OP finds import-f works once and fails thereafter In idle one can get the desired result of import-i with F5 Is that right? Also in general is there good usecases for import-f at that interpreter prompt in idle? I think not but not sure of it From fabien.maussion at gmail.com Wed Mar 2 10:36:51 2016 From: fabien.maussion at gmail.com (Fabien) Date: Wed, 2 Mar 2016 16:36:51 +0100 Subject: urlopen, six, and py2 References: Message-ID: On 03/02/2016 03:35 PM, Matt Wheeler wrote: > I agree that six should probably handle this, Thank you Matt and Chris for your answers. Do you think I should open an issue on six? It sounds unlikely that I am the first one having this problem... (until this difference with urlopen I have found six to be extremely good at helping not caring about python versions at all) From jussi.piitulainen at helsinki.fi Wed Mar 2 10:37:57 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Wed, 02 Mar 2016 17:37:57 +0200 Subject: Explaining names vs variables in Python References: Message-ID: Ian Kelly writes: > On Wed, Mar 2, 2016 at 2:35 AM, Jussi Piitulainen wrote: >> The following are too delicate for me. I suppose the answers could have >> been different, but I can't guess what mechanism actually leads to these >> results. Just idle curiosity on my part. >> >>>>> 890 is 890 >> True >>>>> id(890) == id(890) >> True > > This has to do with the way code blocks are compiled. In the > interactive interpreter, a single line like '890 is 890' is compiled > to a single code object. The constant 890 appears twice in the same > code block, so the optimizer uses the same constant for both. Note in > the following that the same index appears for both, so they're > actually the same object reference. No wonder my guesses failed. This is different. >>>> import dis >>>> dis.dis('890 is 890') > 1 0 LOAD_CONST 0 (890) > 3 LOAD_CONST 0 (890) > 6 COMPARE_OP 8 (is) > 9 RETURN_VALUE >>>> compile('890 is 890', '', 'exec').co_consts > (890, None) > > > As for the earlier example of: > >>>>> 1 + 1 is 2 >> True >>>>> 800 + 90 + 0 is 890 >> False > > This one actually surprises me a little, because the optimizer is also > smart enough to evaluate '800 + 90 + 0' and just store a constant of > 890: > >>>> dis.dis('800 + 90 + 0 is 890') > 1 0 LOAD_CONST 5 (890) > 3 LOAD_CONST 3 (890) > 6 COMPARE_OP 8 (is) > 9 RETURN_VALUE >>>> compile('800 + 90 + 0 is 890', '', 'exec').co_consts > (800, 90, 0, 890, None, 890, 890) > > Not smart enough to reuse the existing reference in this case > apparently, or even to prune out the original constants that are no > longer used in the code. So it has access to three 890-objects and compares two of them :) Thanks. From rosuav at gmail.com Wed Mar 2 11:17:16 2016 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 3 Mar 2016 03:17:16 +1100 Subject: urlopen, six, and py2 In-Reply-To: References: Message-ID: On Thu, Mar 3, 2016 at 2:36 AM, Fabien wrote: > On 03/02/2016 03:35 PM, Matt Wheeler wrote: >> >> I agree that six should probably handle this, > > > Thank you Matt and Chris for your answers. Do you think I should open an > issue on six? It sounds unlikely that I am the first one having this > problem... > > (until this difference with urlopen I have found six to be extremely good at > helping not caring about python versions at all) What happens if you use 'requests' rather than urlopen? My guess is that requests will already have dealt with this. ChrisA From duncan at invalid.invalid Wed Mar 2 11:27:41 2016 From: duncan at invalid.invalid (duncan smith) Date: Wed, 2 Mar 2016 16:27:41 +0000 Subject: rdflib subclass problem In-Reply-To: References: Message-ID: <4wEBy.1373$X_.923@fx04.iad> On 02/03/16 08:16, dieter wrote: > duncan smith writes: > >> I'm just getting to grips with RDF and rdflib, and I've hit >> something I can't figure out. >> >> I have a graph with information on two people. (I haven't shown the >> imports below because they're scattered around my interactive session >> and I might reconstruct them incorrectly. Anyone familiar with rdflib >> will probably know what they are.) >> >> >>>>> G = Graph() >>>>> mark = BNode() >>>>> nat = BNode() >>>>> G.add((mark, RDF.type, FOAF.Person)) >>>>> G.add((mark, FOAF.firstName, Literal('mark'))) >>>>> G.add((nat, RDF.type, URIRef('Professor'))) >>>>> G.add((nat, FOAF.firstName, Literal('natalie'))) >>>>> G.add((URIRef('Professor'), RDFS.subClassOf, FOAF.Person)) >>>>> >> >> >> So I have specified that mark is a Person, natalie is a Professor, and >> that Professor is a subclass of Person. (I know that Professor is really >> a FOAF.title, but I'm just tinkering ATM.) >> >> >>>>> qres = G.query( >> """SELECT DISTINCT ?aname >> WHERE { >> ?a rdf:type foaf:Person . >> ?a foaf:firstName ?aname . >> }""", initNs = {"rdf": RDF,"foaf": FOAF}) >>>>> for row in qres: >> print "%s is a person" % row >> >> >> mark is a person >>>>> qres = G.query( >> """SELECT DISTINCT ?aname >> WHERE { >> ?a rdf:type ?prof . >> ?a foaf:firstName ?aname . >> }""", initNs = {"rdf": RDF,"foaf": FOAF, "prof": >> URIRef('Professor')}) >>>>> for row in qres: >> print "%s is a Prof" % row >> >> >> natalie is a Prof >> mark is a Prof >>>>> >> >> >> But according to the above queries only mark is a Person, and each is a >> Professor. I would have thought that both would be Persons and only >> natalie would be a Professor. Can anyone spot where I'm going wrong >> here? Thanks. > > What you observe would be consistent with "RDFS.subClassOf" working > in the other direction than the one you expect; i.e. that > > URIRef('Professor'), RDFS.subClassOf, FOAF.Person > > means that "Person" is a subclass of "Professor" (not what > you expect, that "Professor" is a subclass of "Person"). > > Carefully check whether "A rel B" means that "B" is in relation "rel" to "A" > (I think that is the case) or that "A" is in relation "rel" to "B". > According to https://www.w3.org/TR/rdf-schema/#ch_class - A triple of the form: C1 rdfs:subClassOf C2 states that C1 is an instance of rdfs:Class, C2 is an instance of rdfs:Class and C1 is a subclass of C2. I might report it as a bug, but I'm not yet 100% convinced I haven't got something wrong. Cheers. Duncan From rustompmody at gmail.com Wed Mar 2 12:02:44 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 2 Mar 2016 09:02:44 -0800 (PST) Subject: [Off-topic] Requests author discusses MentalHealthError exception In-Reply-To: <56d5cbef$0$22142$c3e8da3$5496439d@news.astraweb.com> References: <56d16e6a$0$1593$c3e8da3$5496439d@news.astraweb.com> <56d5cbef$0$22142$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tuesday, March 1, 2016 at 10:36:02 PM UTC+5:30, Steven D'Aprano wrote: > On Tue, 1 Mar 2016 04:08 am, Rustom Mody wrote: > > > And who is the last arbiter on that 'reality'? > > I'll give you the benefit of the doubt that this is a genuine question, and > not just an attempt to ask a rhetorical question to demonstrate your > profundity. > > You should not assume that there is any such thing as "the last arbiter" of > reality. There is no arbiter at all, let alone a final one. But what we > have are various ways of managing and uncertainty and error. One of which > is consensus. For instance, there are seven billion people on earth who > think they are people, and one who thinks he may be a butterfly. Which is > more likely to be correct? > > https://en.wikiquote.org/wiki/Zhuangzi > > To quote Terry Pratchett: > > 'The poet Hoha once dreamed he was a butterfly, and then he > awoke and said, "Am I a man who dreamed he was a butterfly or > am I a butterfly dreaming he is a man?"' said Lobsang, trying > to join in. > 'Really?' said Susan briskly. 'And which was he?' > 'What? Well...who knows?' > 'How did he write his poems?' said Susan. > 'With a brush, of course.' > 'He didn't flap around making information-rich patterns in > the air or laying eggs on cabbage leaves?' > 'No one ever mentioned it.' > 'Then he was probably a man,' said Susan. > > > Because there are limitations on how we observe reality, there are limits to > how objective we can be. We have an imperfect ability to observe the world > around us (including our own mental states) and are prone to errors. But, > over a wide range of conditions (although not *all* conditions) we can > eliminate many classes of error by comparing notes with our fellows, so to > speak. If I think I am a butterfly, and my wife thinks I'm a man, and my > co-workers think I'm a man, and my neighbours think I'm a man, chances are > good that it is me who is mistaken, not them. > > Consequently reality is a shared construct -- or rather, our understanding > of reality is at least partly a shared construct. > > In principle, at least, *everything* is subject to disproof. But in practice > some things are more certain than others. I wouldn't bet $100 on quarks > still being considered the fundamental building block of matter in 200 > years, but I would bet a million dollars on the sun still seeming to rise > in the east every 24 hours. > > As Isaac Asimov put it: > > When people thought the earth was flat, they were wrong. > When people thought the earth was spherical, they were > wrong. But if you think that thinking the earth is > spherical is just as wrong as thinking the earth is flat, > then your view is wronger than both of them put together. > > > https://en.wikipedia.org/wiki/Wronger_than_wrong > > http://chem.tufts.edu/AnswersInScience/RelativityofWrong.htm > > It's not that reality itself is subject to change (except in the trivial > sense that we can take actions that modify the state of the world: I can > pick this cup up and move it over there, you can eat that apple) but that > our understanding of reality is subject to change. Sometimes our > understanding is full of uncertainty and doubt, sometimes it is subject to > re-interpretation, and sometimes our understanding is almost certainly > correct: it is difficult to imagine any credible or believable > reinterpretation that would change the facts as we know them. A thousand > years from now, the sun will still appear to be rising in the east. Consensus? Um lets see... Here are two writings: [1] http://www.poetryloverspage.com/poets/blake/to_see_world.html [2] http://www.bartleby.com/101/536.html If you see [2] around line 75 it almost verbatim echoes Larry's complaint of what 'they' did to Kennneth And how is [1]'s starting different from Kenneth's finding his weight to be the weight of the universe? Maybe the authors of these need the services of a psychiatrist? If not you may find some appeal in this modernized version: http://blog.languager.org/2011/10/vagaries-of-intelligence.html As for Asimov, yeah he's right perhaps in distinguishing wrong wronger and wrongest Not so much in underestimating the time for humans to autocorrect their errors A collection [inspired by earlier comments of yours :-) ]: http://blog.languager.org/2016/01/how-long.html From steve at pearwood.info Wed Mar 2 12:05:33 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 03 Mar 2016 04:05:33 +1100 Subject: Speaking of Javascript [was Re: Everything good about Python except GUI IDE?] References: <64a6599c-fae1-469d-bcee-875165b3cc7d@googlegroups.com> <56d294f8$0$1604$c3e8da3$5496439d@news.astraweb.com> <234a398e-1b0f-467b-a8cb-d7ca748f8062@googlegroups.com> <84922f24-3e00-4a23-b26d-5e6c0d8e7e04@googlegroups.com> <87y4a5c58i.fsf@elektro.pacujo.net> <87twksdg9c.fsf@elektro.pacujo.net> <87d1rgca58.fsf@elektro.pacujo.net> <87h9grorcb.fsf@elektro.pacujo.net> <56d5c6fa$0$1595$c3e8da3$5496439d@news.astraweb.com> <56d64e83$0$1588$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56d71d5f$0$1619$c3e8da3$5496439d@news.astraweb.com> Speaking of Javascript exploits: http://thedailywtf.com/articles/bidding-on-security This is a real exploit, and Ebay have refused to fix it. Yay them! More here: http://blog.checkpoint.com/2016/02/02/ebay-platform-exposed-to-severe-vulnerability/ -- Steven From steve at pearwood.info Wed Mar 2 12:10:17 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 03 Mar 2016 04:10:17 +1100 Subject: Explaining names vs variables in Python References: <56d6ac61$0$23633$edfadb0f@dtext02.news.tele.dk> <56d6c146$0$1615$c3e8da3$5496439d@news.astraweb.com> <87y4a1t5wj.fsf@elektro.pacujo.net> <87twkpt2w7.fsf@elektro.pacujo.net> Message-ID: <56d71e7b$0$1610$c3e8da3$5496439d@news.astraweb.com> On Thu, 3 Mar 2016 12:48 am, Chris Angelico wrote: > On Thu, Mar 3, 2016 at 12:39 AM, Marko Rauhamaa wrote: >> Chris Angelico : >> >>> Python defines that every object has an identity, which can be >>> represented as an integer. Since this is an intrinsic part of the >>> object, no two distinct objects can truly have identical >>> characteristics. Python's objects are like rifles - there are many >>> like it, but this one is mine. >> >> How can you be sure Python isn't returning the same id value for two >> distinct objects? The language is entitled to re-use IDs provided the objects do not exist at the same time. So there certainly will be times that Python will return the same ID for different objects: py> id([1]) 3083419340L py> id([2]) 3083419340L > The same way I can be sure about anything else in Python. It's a > language guarantee. If you're bothered by that, you should also be > concerned that str(x) might not actually call x.__str__(), Technically, it doesn't, it calls type(x).__str__() (at least in Python 3 and new-style classes in 2) :-) But your point is broadly correct: you trust the language to do what it promises, or you look for evidence that it doesn't and report a bug if you find it. -- Steven From steve at pearwood.info Wed Mar 2 12:23:19 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 03 Mar 2016 04:23:19 +1100 Subject: Explaining names vs variables in Python References: <56d6ac61$0$23633$edfadb0f@dtext02.news.tele.dk> <56d6c146$0$1615$c3e8da3$5496439d@news.astraweb.com> <87y4a1t5wj.fsf@elektro.pacujo.net> <87twkpt2w7.fsf@elektro.pacujo.net> <87povdt1ec.fsf@elektro.pacujo.net> Message-ID: <56d7218c$0$1587$c3e8da3$5496439d@news.astraweb.com> On Thu, 3 Mar 2016 01:11 am, Marko Rauhamaa wrote: > What is missing is the rules that are obeyed by the "is" operator. I think what is actually missing is some common bloody sense. The Python docs are written in English, and don't define *hundreds*, possible *thousands* of words because they are using their normal English meaning. The docs for `is` say: 6.10.3. Identity comparisons The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value. https://docs.python.org/3/reference/expressions.html#is-not In this case, "same object" carries the normal English meaning of "same" and the normal computer science meaning of "object" in the sense of "Object Oriented Programming". There's no mystery here, no circular definition. -- Steven From rustompmody at gmail.com Wed Mar 2 12:28:04 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 2 Mar 2016 09:28:04 -0800 (PST) Subject: Explaining names vs variables in Python In-Reply-To: <56d7218c$0$1587$c3e8da3$5496439d@news.astraweb.com> References: <56d6ac61$0$23633$edfadb0f@dtext02.news.tele.dk> <56d6c146$0$1615$c3e8da3$5496439d@news.astraweb.com> <87y4a1t5wj.fsf@elektro.pacujo.net> <87twkpt2w7.fsf@elektro.pacujo.net> <87povdt1ec.fsf@elektro.pacujo.net> <56d7218c$0$1587$c3e8da3$5496439d@news.astraweb.com> Message-ID: <40f149ea-4e0d-4e6e-a414-b14a158fd5ba@googlegroups.com> On Wednesday, March 2, 2016 at 10:53:40 PM UTC+5:30, Steven D'Aprano wrote: > On Thu, 3 Mar 2016 01:11 am, Marko Rauhamaa wrote: > > > What is missing is the rules that are obeyed by the "is" operator. > > I think what is actually missing is some common bloody sense. The Python > docs are written in English, and don't define *hundreds*, possible > *thousands* of words because they are using their normal English meaning. > > The docs for `is` say: > > 6.10.3. Identity comparisons > > The operators is and is not test for object identity: x is y is true if and > only if x and y are the same object. x is not y yields the inverse truth > value. > > https://docs.python.org/3/reference/expressions.html#is-not > > > In this case, "same object" carries the normal English meaning of "same" and > the normal computer science meaning of "object" in the sense of "Object > Oriented Programming". There's no mystery here, no circular definition. > http://plato.stanford.edu/entries/identity/ From pkpearson at nowhere.invalid Wed Mar 2 12:40:17 2016 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 2 Mar 2016 17:40:17 GMT Subject: What arguments are passed to the __new__ method ? References: <56d5d043$0$632$426a74cc@news.free.fr> Message-ID: On Tue, 1 Mar 2016 18:24:12 +0100, ast wrote: > > It's not clear to me what arguments are passed to the > __new__ method. Here is a piece of code: > > > class Premiere: > > def __new__(cls, price): > return object.__new__(cls) > > def __init__(self, price): > pass [snip] Of course, maybe you don't need to define a __new__ method at all. Personally, I find that __init__ suffices for my simple needs. -- To email me, substitute nowhere->runbox, invalid->com. From rosuav at gmail.com Wed Mar 2 12:46:48 2016 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 3 Mar 2016 04:46:48 +1100 Subject: Speaking of Javascript [was Re: Everything good about Python except GUI IDE?] In-Reply-To: <56d71d5f$0$1619$c3e8da3$5496439d@news.astraweb.com> References: <64a6599c-fae1-469d-bcee-875165b3cc7d@googlegroups.com> <56d294f8$0$1604$c3e8da3$5496439d@news.astraweb.com> <234a398e-1b0f-467b-a8cb-d7ca748f8062@googlegroups.com> <84922f24-3e00-4a23-b26d-5e6c0d8e7e04@googlegroups.com> <87y4a5c58i.fsf@elektro.pacujo.net> <87twksdg9c.fsf@elektro.pacujo.net> <87d1rgca58.fsf@elektro.pacujo.net> <87h9grorcb.fsf@elektro.pacujo.net> <56d5c6fa$0$1595$c3e8da3$5496439d@news.astraweb.com> <56d64e83$0$1588$c3e8da3$5496439d@news.astraweb.com> <56d71d5f$0$1619$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Mar 3, 2016 at 4:05 AM, Steven D'Aprano wrote: > Speaking of Javascript exploits: > > http://thedailywtf.com/articles/bidding-on-security > > > This is a real exploit, and Ebay have refused to fix it. Yay them! > > More here: > > http://blog.checkpoint.com/2016/02/02/ebay-platform-exposed-to-severe-vulnerability/ To be fair, this isn't a JS exploit; it's a trusting-of-trust issue - eBay has declared that you can trust them to sanitize their sellers' listings, and so you trust eBay, but this exploit gets past the filter. You're no more vulnerable looking at one of those listings than you would be going to a web site entirely controlled by the attacker, save that (particularly on mobile devices) there are a lot of people out there who'll say "Oh, it'e eBay, I'm safe". ChrisA From ben+python at benfinney.id.au Wed Mar 2 12:53:36 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 03 Mar 2016 04:53:36 +1100 Subject: Explaining names vs variables in Python References: Message-ID: <85r3fsvk9r.fsf@benfinney.id.au> Salvatore DI DIO writes: > I know Python does not have variables, but names. In addition to the other food answers in this thread, you will want to watch Ned Batchelder's presentation on ?Facts and myths about Python names and values?. -- \ ?Members of the general public commonly find copyright rules | `\ implausible, and simply disbelieve them.? ?Jessica Litman, | _o__) _Digital Copyright_ | Ben Finney From rgaddi at highlandtechnology.invalid Wed Mar 2 12:57:01 2016 From: rgaddi at highlandtechnology.invalid (Rob Gaddi) Date: Wed, 2 Mar 2016 17:57:01 -0000 (UTC) Subject: What arguments are passed to the __new__ method ? References: <56d5d043$0$632$426a74cc@news.free.fr> Message-ID: Peter Pearson wrote: > On Tue, 1 Mar 2016 18:24:12 +0100, ast wrote: >> >> It's not clear to me what arguments are passed to the >> __new__ method. Here is a piece of code: >> >> >> class Premiere: >> >> def __new__(cls, price): >> return object.__new__(cls) >> >> def __init__(self, price): >> pass > [snip] > > Of course, maybe you don't need to define a __new__ method at all. > Personally, I find that __init__ suffices for my simple needs. > I tend to need __init__ on about half of the classes I write. I think I've needed __new__ all of twice in the years I've been writing Python. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From marko at pacujo.net Wed Mar 2 13:12:06 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 02 Mar 2016 20:12:06 +0200 Subject: Explaining names vs variables in Python References: <56d6ac61$0$23633$edfadb0f@dtext02.news.tele.dk> <56d6c146$0$1615$c3e8da3$5496439d@news.astraweb.com> <87y4a1t5wj.fsf@elektro.pacujo.net> <87twkpt2w7.fsf@elektro.pacujo.net> <87povdt1ec.fsf@elektro.pacujo.net> <56d7218c$0$1587$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87mvqgagw9.fsf@elektro.pacujo.net> Steven D'Aprano : > In this case, "same object" carries the normal English meaning of > "same" and the normal computer science meaning of "object" in the > sense of "Object Oriented Programming". There's no mystery here, no > circular definition. I see three possible ways of defining "is" / object identity (and other concepts): 1. hand waving ("normal English") 2. reduction to an underlying model (a real / conceptual computer) 3. formal semantics All methods are in use. Experienced programmers have #2 in mind but are embarrassed to admit they understand Python through C. Thus, they offer explanation #1 to newbies, who are too embarrassed to admit they don't get the explanation. I think #3 could be tried more often. It is analogous to providing the BNF of Python's syntax (which *is* done: ). Marko From ian.g.kelly at gmail.com Wed Mar 2 13:26:30 2016 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 2 Mar 2016 11:26:30 -0700 Subject: What arguments are passed to the __new__ method ? In-Reply-To: References: <56d5d043$0$632$426a74cc@news.free.fr> Message-ID: On Wed, Mar 2, 2016 at 10:57 AM, Rob Gaddi wrote: > Peter Pearson wrote: > >> On Tue, 1 Mar 2016 18:24:12 +0100, ast wrote: >>> >>> It's not clear to me what arguments are passed to the >>> __new__ method. Here is a piece of code: >>> >>> >>> class Premiere: >>> >>> def __new__(cls, price): >>> return object.__new__(cls) >>> >>> def __init__(self, price): >>> pass >> [snip] >> >> Of course, maybe you don't need to define a __new__ method at all. >> Personally, I find that __init__ suffices for my simple needs. >> > > I tend to need __init__ on about half of the classes I write. I think > I've needed __new__ all of twice in the years I've been writing Python. Typically there are only two reasons to override __new__: you potentially want to return an object of a different class than the class that was called, or you're subclassing an immutable type and need to handle the superclass arguments before they get passed to the constructor. From jon+usenet at unequivocal.co.uk Wed Mar 2 13:29:33 2016 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Wed, 2 Mar 2016 18:29:33 -0000 (UTC) Subject: Speaking of Javascript [was Re: Everything good about Python except GUI IDE?] References: <64a6599c-fae1-469d-bcee-875165b3cc7d@googlegroups.com> <56d294f8$0$1604$c3e8da3$5496439d@news.astraweb.com> <234a398e-1b0f-467b-a8cb-d7ca748f8062@googlegroups.com> <84922f24-3e00-4a23-b26d-5e6c0d8e7e04@googlegroups.com> <87y4a5c58i.fsf@elektro.pacujo.net> <87twksdg9c.fsf@elektro.pacujo.net> <87d1rgca58.fsf@elektro.pacujo.net> <87h9grorcb.fsf@elektro.pacujo.net> <56d5c6fa$0$1595$c3e8da3$5496439d@news.astraweb.com> <56d64e83$0$1588$c3e8da3$5496439d@news.astraweb.com> <56d71d5f$0$1619$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2016-03-02, Chris Angelico wrote: > To be fair, this isn't a JS exploit; it's a trusting-of-trust issue - > eBay has declared that you can trust them to sanitize their sellers' > listings, and so you trust eBay, but this exploit gets past the > filter. This is true. It sounds like their filter is frankly bizarre, I can't imagine why it works the way that has been described. > You're no more vulnerable looking at one of those listings > than you would be going to a web site entirely controlled by the > attacker, save that (particularly on mobile devices) there are a lot > of people out there who'll say "Oh, it'e eBay, I'm safe". This however I don't think is true at all. eBay already has a great deal of data about its customers, if an attacker can hijack sessions and steal this data just from a user visiting a listings page then that isn't anything like visiting a random malicious site. From skip.montanaro at gmail.com Wed Mar 2 15:43:38 2016 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Wed, 2 Mar 2016 14:43:38 -0600 Subject: Continuing indentation Message-ID: Running flake8 over some code which has if statements with multiple conditions like this: if (some_condition and some_other_condition and some_final_condition): play_bingo() the tool complains that the indentation of the conditions is the same as the next block. In this particular case, the overall conditions are too long to string together on a single line. I tried placing a second space after the if keyword: if (some_condition and some_other_condition and some_final_condition): play_bingo() which solves the matching indentation problem, but creates a multiple spaces after keyword problem. My guess is that adding a space after the open paren would provoke a message as well. I use GNU Emacs as my text editor, and its python mode. I'm pretty happy with everything (been using it in its current state for several years). Aside from manually or configure-ologically suppressing E129, is there a better way to break lines I'm missing which will make flake8 happy? Thx, Skip From marko at pacujo.net Wed Mar 2 15:50:02 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 02 Mar 2016 22:50:02 +0200 Subject: Continuing indentation References: Message-ID: <8760x4bo5h.fsf@elektro.pacujo.net> Skip Montanaro : > Running flake8 over some code which has if statements with multiple > conditions like this: > > if (some_condition and > some_other_condition and > some_final_condition): > play_bingo() > [...] > > is there a better way to break lines I'm missing which will make > flake8 happy? This is the idiomatic way: if some_condition and \ some_other_condition and \ some_final_condition: play_bingo() Marko From rosuav at gmail.com Wed Mar 2 15:55:32 2016 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 3 Mar 2016 07:55:32 +1100 Subject: Speaking of Javascript [was Re: Everything good about Python except GUI IDE?] In-Reply-To: References: <64a6599c-fae1-469d-bcee-875165b3cc7d@googlegroups.com> <56d294f8$0$1604$c3e8da3$5496439d@news.astraweb.com> <234a398e-1b0f-467b-a8cb-d7ca748f8062@googlegroups.com> <84922f24-3e00-4a23-b26d-5e6c0d8e7e04@googlegroups.com> <87y4a5c58i.fsf@elektro.pacujo.net> <87twksdg9c.fsf@elektro.pacujo.net> <87d1rgca58.fsf@elektro.pacujo.net> <87h9grorcb.fsf@elektro.pacujo.net> <56d5c6fa$0$1595$c3e8da3$5496439d@news.astraweb.com> <56d64e83$0$1588$c3e8da3$5496439d@news.astraweb.com> <56d71d5f$0$1619$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Mar 3, 2016 at 5:29 AM, Jon Ribbens wrote: > On 2016-03-02, Chris Angelico wrote: >> To be fair, this isn't a JS exploit; it's a trusting-of-trust issue - >> eBay has declared that you can trust them to sanitize their sellers' >> listings, and so you trust eBay, but this exploit gets past the >> filter. > > This is true. It sounds like their filter is frankly bizarre, > I can't imagine why it works the way that has been described. Agreed. I also don't understand why they can't simply say "no {% endblock %} {% block share %} {% endblock %} {% block google_style %} {% endblock %} From challakarthik at gmail.com Tue Mar 22 06:37:03 2016 From: challakarthik at gmail.com (Karthik Reddy) Date: Tue, 22 Mar 2016 03:37:03 -0700 (PDT) Subject: GAPI -- Sharing a post to Social Networking Pages from my App In-Reply-To: References: <0a9353af-8179-4e33-ac36-fce8a3160465@googlegroups.com> Message-ID: <6588aa57-52b8-45e9-86e1-16647e4a89f7@googlegroups.com> On Tuesday, March 22, 2016 at 9:54:53 AM UTC+5:30, Mark Lawrence wrote: > On 22/03/2016 04:14, Karthik Reddy wrote: > > Hi Experts, > > > > I am trying to post on facebook and google plus page from my application. I am using facebook-sdk an d I am able to post using local machine but I am not able to post from dev server. > > > > Can Anyone Please help me on this. > > > > Thanks, > > Karthik > > > > Please state your OS and Python version, the code that you've tried and > exactly what went wrong, including the full traceback if there is one. > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence The error I am getting is "Uncaught ReferenceError: gapi is not defined" From steve at pearwood.info Tue Mar 22 06:49:00 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 22 Mar 2016 21:49:00 +1100 Subject: Convert list to another form but providing same information References: <1010f2cb-21f9-495b-8af4-03ad209b4c1e@googlegroups.com> <87twjzz44v.fsf@jester.gateway.pace.com> Message-ID: <56f12322$0$1607$c3e8da3$5496439d@news.astraweb.com> On Tue, 22 Mar 2016 12:35 pm, Paul Rubin wrote: > Maurice writes: >> I have a list such [6,19,19,21,21,21] >> Therefore the resulting list should be: >> [0,0,0,0,0,0,1,0,0,0...,2,0,3,0...0] > > Rather than a sparse list you'd typically want a dictionary (untested): > > from collections import defaultdict > the_list = [0,0,0,0,0,0,1,0,0,0...,2,0,3,0...0] > ... > days = defaultdict(int) > for t in the_list: > days[t] += 1 > > this results in days being the defaultdict { 6:1, 19:2, 21:3 }. For just 3 items out of 32, doing this as an optimisation is barely worth it. Using Python 3.4, I get 168 bytes for the list solution and 152 bytes for a default dict solution: py> print(days) [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] py> sys.getsizeof(days) 168 py> from collections import defaultdict py> d = defaultdict(int) py> d.update({ 6:1, 19:2, 21:3 }) py> sys.getsizeof(d) 152 By all means use whichever solution suits you best, but don't expect to save much memory in a "spare array" of only 32 items :-) -- Steven From bc at freeuk.com Tue Mar 22 07:05:01 2016 From: bc at freeuk.com (BartC) Date: Tue, 22 Mar 2016 11:05:01 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 22/03/2016 01:01, Steven D'Aprano wrote: > On Tue, 22 Mar 2016 06:43 am, BartC wrote: > >> This code was adapted from a program that used: >> >> readstrfile(filename) >> >> which either returned the contents of the file as a string, or 0. > > What an interesting function. And I don't mean that in a good way. > > So if it returns 0, how do you know what the problem is? Mistyped file name? > Permission denied? File doesn't actually exist? Disk corruption and you > can't open the file? Some weird OS problem where you can't *close* the > file? (That can actually happen, although it's never happened to me.) How > do you debug any problems, given only "0" as a result? > > What happens if you read (let's say) a 20GB Blue-Ray disk image? I think you're making far too much of a throwaway function to grab a file off disk and into memory. But out of interest, how would /you/ write a function that takes a file-spec and turns it into an in-memory string? And what would its use look like? > Pythonic code probably uses a lot of iterables: > > for value in something: > ... > in preference to Pascal code written in Python: > > for index in range(len(something)): > value = something[index] (Suppose you need both the value and its index in the loop? Then the one-line for above won't work. For example, 'something' is [10,20,30] and you want to print: 0: 10 1: 20 2: 30 ) > ... > or worse: > > index = 0 > while index < len(something): > value = something[index] > ... > index += 1 > (I don't know where that while-loop idiom comes from. C? Assembly? Penitent > monks living in hair shirts in the desert and flogging themselves with > chains every single night to mortify the accursed flesh? But I'm seeing it > a lot in code written by beginners. I presume somebody, or some book, is > teaching it to them. "Learn Python The Hard Way" perhaps?) Are you suggesting 'while' is not needed? Not everything fits into a for-loop you know! Why, take my own readtoken() function: symbol = anything_other_than_skip_sym while symbol != skip_sym: symbol = readnextsymbol() Of course, a repeat-until or repeat-while would suit this better (but I don't know how it fits into Python syntax). So there's a case here for increasing the number of loop statements not reducing them. -- Bartc From rustompmody at gmail.com Tue Mar 22 07:15:21 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 22 Mar 2016 04:15:21 -0700 (PDT) Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> Message-ID: <6a1c72a0-7a44-4e00-8aa6-8649aa7e5d5d@googlegroups.com> On Tuesday, March 22, 2016 at 7:32:13 AM UTC+5:30, Mark Lawrence wrote: > On 22/03/2016 00:49, BartC wrote: > > > > I was surprised at one time that slices don't create 'views', but I've > > since implemented view-slices and I can appreciate the problems.) > > > > Why, the docs are quite clear on how Python works? Of course you can > always use memoryviews > https://docs.python.org/3/library/stdtypes.html#typememoryview Interesting! Can you show/point me to a recipe for getting a copyless view of any arbitrary (not necessarily byte) array? From rosuav at gmail.com Tue Mar 22 07:15:40 2016 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 22 Mar 2016 22:15:40 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Mar 22, 2016 at 10:05 PM, BartC wrote: > But out of interest, how would /you/ write a function that takes a file-spec > and turns it into an in-memory string? And what would its use look like? def read_file(fn, *a, **kw): with open(fn, *a, **kw) as f: return f.read() Usage: script = read_file(".bashrc") data = read_file("Ellalune_AlicePortrait.jpg", "rb") decoded = read_file("greek.srt", encoding="ISO-8859-7") If there's any problem with reading the file, an exception will be raised. Also, thanks to the 'with' block, I'm guaranteed that the file will have been closed before read_file() returns, which means I can immediately go and write to the file without a conflict. ChrisA From steve at pearwood.info Tue Mar 22 07:18:23 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 22 Mar 2016 22:18:23 +1100 Subject: GAPI -- Sharing a post to Social Networking Pages from my App References: <0a9353af-8179-4e33-ac36-fce8a3160465@googlegroups.com> <6588aa57-52b8-45e9-86e1-16647e4a89f7@googlegroups.com> Message-ID: <56f12a00$0$22142$c3e8da3$5496439d@news.astraweb.com> On Tue, 22 Mar 2016 09:37 pm, Karthik Reddy wrote: > The error I am getting is "Uncaught ReferenceError: gapi is not defined" Have you tried googling for it? That's a Javascript error: https://duckduckgo.com/html/?q=uncaught+reference+error+gapi+is+not+defined -- Steven From ned at nedbatchelder.com Tue Mar 22 07:23:40 2016 From: ned at nedbatchelder.com (Ned Batchelder) Date: Tue, 22 Mar 2016 04:23:40 -0700 (PDT) Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tuesday, March 22, 2016 at 7:05:20 AM UTC-4, BartC wrote: > On 22/03/2016 01:01, Steven D'Aprano wrote: > > Pythonic code probably uses a lot of iterables: > > > > for value in something: > > ... > > > in preference to Pascal code written in Python: > > > > for index in range(len(something)): > > value = something[index] > > (Suppose you need both the value and its index in the loop? Then the > one-line for above won't work. For example, 'something' is [10,20,30] > and you want to print: > > 0: 10 > 1: 20 > 2: 30 ) Then you use enumerate: for index, value in enumerate(something): print("{}: {}".format(index, value)) Python has a number of iteration features that you don't find in other languages. You might find this introduction to them helpful: Loop Like a Native: http://nedbatchelder.com/text/iter.html > > > ... > > or worse: > > > > index = 0 > > while index < len(something): > > value = something[index] > > ... > > index += 1 > > > (I don't know where that while-loop idiom comes from. C? Assembly? Penitent > > monks living in hair shirts in the desert and flogging themselves with > > chains every single night to mortify the accursed flesh? But I'm seeing it > > a lot in code written by beginners. I presume somebody, or some book, is > > teaching it to them. "Learn Python The Hard Way" perhaps?) > > Are you suggesting 'while' is not needed? Not everything fits into a > for-loop you know! Steven wasn't saying 'while' is not needed. He was wondering about the idiom of manually maintaining an integer count of the number of times around a while loop ("I don't know where *that* while-loop idiom comes from"). While-loops are still useful in Python, but for-loops are much more common. --Ned. From challakarthik at gmail.com Tue Mar 22 07:25:16 2016 From: challakarthik at gmail.com (Karthik Reddy) Date: Tue, 22 Mar 2016 04:25:16 -0700 (PDT) Subject: GAPI -- Sharing a post to Social Networking Pages from my App In-Reply-To: <56f12a00$0$22142$c3e8da3$5496439d@news.astraweb.com> References: <0a9353af-8179-4e33-ac36-fce8a3160465@googlegroups.com> <6588aa57-52b8-45e9-86e1-16647e4a89f7@googlegroups.com> <56f12a00$0$22142$c3e8da3$5496439d@news.astraweb.com> Message-ID: <0302047b-19db-4aa2-84d0-fd4b1d593558@googlegroups.com> On Tuesday, March 22, 2016 at 4:48:37 PM UTC+5:30, Steven D'Aprano wrote: > On Tue, 22 Mar 2016 09:37 pm, Karthik Reddy wrote: > > > The error I am getting is "Uncaught ReferenceError: gapi is not defined" > > > Have you tried googling for it? That's a Javascript error: > > https://duckduckgo.com/html/?q=uncaught+reference+error+gapi+is+not+defined > > > > -- > Steven Yup I googled it I am not getting where I need to modify From ian at feete.org Tue Mar 22 07:27:57 2016 From: ian at feete.org (Ian Foote) Date: Tue, 22 Mar 2016 11:27:57 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56F12C3D.8060006@feete.org> On 22/03/16 11:05, BartC wrote: > On 22/03/2016 01:01, Steven D'Aprano wrote: > >> Pythonic code probably uses a lot of iterables: >> >> for value in something: >> ... > >> in preference to Pascal code written in Python: >> >> for index in range(len(something)): >> value = something[index] > > (Suppose you need both the value and its index in the loop? Then the > one-line for above won't work. For example, 'something' is [10,20,30] > and you want to print: > > 0: 10 > 1: 20 > 2: 30 ) > The builtin enumerate function is the idiomatic way: for index, item in enumerate(something): ... Regards, Ian F From challakarthik at gmail.com Tue Mar 22 07:44:08 2016 From: challakarthik at gmail.com (Karthik Reddy) Date: Tue, 22 Mar 2016 04:44:08 -0700 (PDT) Subject: GAPI -- Sharing a post to Social Networking Pages from my App In-Reply-To: <0302047b-19db-4aa2-84d0-fd4b1d593558@googlegroups.com> References: <0a9353af-8179-4e33-ac36-fce8a3160465@googlegroups.com> <6588aa57-52b8-45e9-86e1-16647e4a89f7@googlegroups.com> <56f12a00$0$22142$c3e8da3$5496439d@news.astraweb.com> <0302047b-19db-4aa2-84d0-fd4b1d593558@googlegroups.com> Message-ID: <2a63d7fb-74d4-4975-b073-25173db3c43c@googlegroups.com> On Tuesday, March 22, 2016 at 4:55:40 PM UTC+5:30, Karthik Reddy wrote: > On Tuesday, March 22, 2016 at 4:48:37 PM UTC+5:30, Steven D'Aprano wrote: > > On Tue, 22 Mar 2016 09:37 pm, Karthik Reddy wrote: > > > > > The error I am getting is "Uncaught ReferenceError: gapi is not defined" > > > > > > Have you tried googling for it? That's a Javascript error: > > > > https://duckduckgo.com/html/?q=uncaught+reference+error+gapi+is+not+defined > > > > > > > > -- > > Steven > Yup I googled it I am not getting where I need to modify Is my approach is correct or if not Is there any other approach Please help me with this..... From rosuav at gmail.com Tue Mar 22 07:55:17 2016 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 22 Mar 2016 22:55:17 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Mar 22, 2016 at 10:45 PM, Dennis Lee Bieber wrote: > On Tue, 22 Mar 2016 11:05:01 +0000, BartC declaimed the > following: > >> >>But out of interest, how would /you/ write a function that takes a >>file-spec and turns it into an in-memory string? And what would its use >>look like? >> > At the basics -- and letting the garbage collector get the file handle > later... > > imstr = open(fileName, "r").read() > > If you want a separate function... (the name here stinks, but...) > > def fn2str(fileName): > fin = open(fileName, "r") > imstr = fin.read() > fin.close() > return imstr > > ... > data = fn2str("some.file") > > letting any exceptions propagate upwards. While we're on the subject of Pythonic ways to read files, this is NOT. http://thedailywtf.com/articles/finding-the-file It's also not idiomatic C# code either, though... ChrisA From srkunze at mail.de Tue Mar 22 08:01:27 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Tue, 22 Mar 2016 13:01:27 +0100 Subject: monkey patching __code__ In-Reply-To: References: <56EBEB5A.7050207@mail.de> <56EED3DE.7050101@mail.de> Message-ID: <56F13417.8060108@mail.de> On 21.03.2016 21:42, Matt Wheeler wrote: > On 20 March 2016 at 16:46, Sven R. Kunze wrote: >> On 19.03.2016 00:58, Matt Wheeler wrote: >>> I know you have a working solution now with updating the code & >>> defaults of the function, but what about just injecting your function >>> into the modules that had already imported it after the >>> monkeypatching? >>> >>> Seems perhaps cleaner, unless you'd end up having to do it to lots of >>> modules... >> Why do you consider it cleaner? > I think it would be more explicit and understandable for someone > reading your code. > > I suppose it's quite subjective :) As far as I can see, the code replacement approach solves the problem once and for all. Thus is far more stable. Manually finding out every single module that might or might not have imported "reverse" before we could monkeypatch it might result in a maintenance nightmare (just think about a Django upgrade). It reminds me of list replacement: mylist = newlist mylist[:] = newlist The latter keeps the reference stable whereas the former does not. Same with monkeypatching. Best, Sven From steve at pearwood.info Tue Mar 22 08:03:45 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 22 Mar 2016 23:03:45 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f134a3$0$1612$c3e8da3$5496439d@news.astraweb.com> On Tue, 22 Mar 2016 10:05 pm, BartC wrote: > On 22/03/2016 01:01, Steven D'Aprano wrote: >> On Tue, 22 Mar 2016 06:43 am, BartC wrote: >> >>> This code was adapted from a program that used: >>> >>> readstrfile(filename) >>> >>> which either returned the contents of the file as a string, or 0. >> >> What an interesting function. And I don't mean that in a good way. >> >> So if it returns 0, how do you know what the problem is? Mistyped file >> name? Permission denied? File doesn't actually exist? Disk corruption and >> you can't open the file? Some weird OS problem where you can't *close* >> the file? (That can actually happen, although it's never happened to me.) >> How do you debug any problems, given only "0" as a result? >> >> What happens if you read (let's say) a 20GB Blue-Ray disk image? > > I think you're making far too much of a throwaway function to grab a > file off disk and into memory. > > But out of interest, how would /you/ write a function that takes a > file-spec and turns it into an in-memory string? And what would its use > look like? I already told you. For a quick and dirty script where I didn't care much about reliability, I would use: the_text = open(filename).read() and leave it at that. There's a hierarchy of less- to more-reliable. Next would be: with open(filename) as f: the_text = f.read() which guarantees to close the file promptly. Better still would be to avoid dealing with the entire file in one (potentially enormous) chunk, and process it line by line: with open(filename) as f: for line in f: process line If for some reason I *had* to process it as one big chunk of text, where I knew that there was a chance that it could be bigger than what I could comfortably hold in memory in one go, I would research mmap. But I don't really know anything about how that works. I've been lucky enough to never need to care. Dealing with out-of-memory errors on modern OSes is one of the hardest things to get right. In some ways, we're lucky, because the OS will try really hard to give the illusion that you have an infinite amount of memory. But the illusion is never perfect, and the abstraction of "virtual memory plus real memory = infinite memory" can break down. I once foolishly tried to create an *enormous* list, something like [0]*10**100, and my OS very kindly started swapping applications in and out of memory trying to free up 40 000 000 billion billion billion billion billion billion billion billion billion petabytes of memory (estimated). Not only did Python lock up, but so did the OS. I decided to leave it overnight to see if it would recover, but 16 hours later it was still locked up and frantically trying to swap memory. I'm not sure why the OOM-Killer didn't trigger. I ended up having to do a hard power-down to recover. So virtual memory is a mixed blessing. >> Pythonic code probably uses a lot of iterables: >> >> for value in something: >> ... > >> in preference to Pascal code written in Python: >> >> for index in range(len(something)): >> value = something[index] > > (Suppose you need both the value and its index in the loop? Then the > one-line for above won't work. For example, 'something' is [10,20,30] > and you want to print: > > 0: 10 > 1: 20 > 2: 30 ) for index, n in enumerate([10, 20, 30]): print(index, ":", n) >> or worse: >> >> index = 0 >> while index < len(something): >> value = something[index] >> ... >> index += 1 > >> (I don't know where that while-loop idiom comes from. C? Assembly? >> Penitent monks living in hair shirts in the desert and flogging >> themselves with chains every single night to mortify the accursed flesh? >> But I'm seeing it a lot in code written by beginners. I presume somebody, >> or some book, is teaching it to them. "Learn Python The Hard Way" >> perhaps?) > > Are you suggesting 'while' is not needed? Of course not. Use while loops for when you need a while loop. But *writing a for-loop using while* is an abuse of while. -- Steven From jcasale at activenetwerx.com Tue Mar 22 08:12:20 2016 From: jcasale at activenetwerx.com (Joseph L. Casale) Date: Tue, 22 Mar 2016 12:12:20 +0000 Subject: Static caching property In-Reply-To: <87wpouap9w.fsf@handshake.de> References: <35a5c4206a0c40e584d62d5d37b068b3@activenetwerx.com> <87wpouap9w.fsf@handshake.de> Message-ID: <6690a027fa46423d80d71a1d7e861572@activenetwerx.com> > If a method call on any instance defines the return value for > all instances, then this method likely should be a class method -- > and use a class attribute to store the result -- something like this: > > class C(object): > > _cache = {} > > @classmethod > def f(cls, ...): > ... determine cache key `key` ... > v = cls._cache.get(key) > if v is None: > v = cls._cache[key] = ... > return v > > It will work also without the "@classmethod". Ok, classmethod has advantages when considering OOP, but this is flawed. Ethan was spot on (aside from the typo in the return statement), if the expensive API call returns None, since it is a singleton your code will continue to invoke it. This implementation also invokes additional hashing and lookups. Ethan's implementation also supports inheritance. jlc From steve at pearwood.info Tue Mar 22 08:15:21 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 22 Mar 2016 23:15:21 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f1375c$0$1600$c3e8da3$5496439d@news.astraweb.com> On Tue, 22 Mar 2016 10:55 pm, Chris Angelico wrote: > While we're on the subject of Pythonic ways to read files, this is NOT. > > http://thedailywtf.com/articles/finding-the-file > > It's also not idiomatic C# code either, though... Obviously not. They should have used a switch. I like the comment from "PWolff": A loop might be faster to write (for a human) and easier to maintain, but it takes significantly longer to run. (Several ppm in this case, I assume.) (PPM? Parts per million?) Unless PWolff is being too-ironic-by-half, I expect to see his work featured on The Daily WTF soon. I like this one: http://thedailywtf.com/articles/string-cheese -- Steven From bgailer at gmail.com Tue Mar 22 08:49:54 2016 From: bgailer at gmail.com (Bob Gailer) Date: Tue, 22 Mar 2016 08:49:54 -0400 Subject: need help With understanding In-Reply-To: References: Message-ID: On Mar 21, 2016 5:40 PM, "Peter Pearson" wrote: > > On Mon, 21 Mar 2016 11:18:57 +0000, mohamed mohamud wrote: > > hey im new at Learning Python, and i have an issue which i would like > > som help With. > > > > i have currently installed Python, and im Reading this book which > > tells me i have to have IDLE, but i cant find it on my computer. do i > > need to install it? and if so where do/can i find it.? > I believe IDLE is part of the Python distribution. Do a search for idle from the python directory. From jussi.piitulainen at helsinki.fi Tue Mar 22 08:52:47 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Tue, 22 Mar 2016 14:52:47 +0200 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: BartC writes: > Not everything fits into a for-loop you know! Why, take my own > readtoken() function: > > symbol = anything_other_than_skip_sym > > while symbol != skip_sym: > symbol = readnextsymbol() > > Of course, a repeat-until or repeat-while would suit this better (but > I don't know how it fits into Python syntax). So there's a case here > for increasing the number of loop statements not reducing them. Not sure why nobody seems to respond to this part. Perhaps I just missed it? It's true that while has its uses, or at least I think I've used it in Python once or twice. But there's more fun to be had by turning your data into a stream-like object. stream = iter(' /* this is C! */') # <-- produces a character at a time Now you can ask for the next item that satisfies a condition using a generator expression: next(symbol for symbol in stream if not symbol.isspace()) ---> '/' next(symbol for symbol in stream if not symbol.isspace()) ---> '*' Or collect the remaining items: list(symbol for symbol in stream if not symbol.isspace()) ---> ['t', 'h', 'i', 's', 'i', 's', 'C', '!', '*', '/'] You could also say: for symbol in stream: if symbol.isspace(): continue ... But this particular stream is empty by now. I work with long streams of tokenized and annotated sentences (which for me are streams of tokens) that sometimes come packed in streams of paragraphs packed in streams of texts. I build whatever stream I happen to want by nesting generator functions and generator expressions and some related machinery. (You could build on a character stream or a byte stream that you obtain by opening a file for reading; I tend to read line by line through itertools.groupby, because that's what I do.) These things compose well. From steve at pearwood.info Tue Mar 22 08:57:56 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 22 Mar 2016 23:57:56 +1100 Subject: exec inside functions in Python 3 Message-ID: <56f14156$0$1619$c3e8da3$5496439d@news.astraweb.com> Anyone have any idea what is going on here? def test(): spam = 1 exec("spam = 2; print('inside exec: %d' % spam)") print('outside exec: %d' % spam) In Python 2.7: py> test() inside exec: 2 outside exec: 2 In Python 3.4: outside exec: 1 py> test() inside exec: 2 outside exec: 1 What happened to spam? -- Steven From bc at freeuk.com Tue Mar 22 08:59:22 2016 From: bc at freeuk.com (BartC) Date: Tue, 22 Mar 2016 12:59:22 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 22/03/2016 11:15, Chris Angelico wrote: > On Tue, Mar 22, 2016 at 10:05 PM, BartC wrote: >> But out of interest, how would /you/ write a function that takes a file-spec >> and turns it into an in-memory string? And what would its use look like? > > def read_file(fn, *a, **kw): > with open(fn, *a, **kw) as f: > return f.read() > > Usage: > > script = read_file(".bashrc") > data = read_file("Ellalune_AlicePortrait.jpg", "rb") > decoded = read_file("greek.srt", encoding="ISO-8859-7") > > If there's any problem with reading the file, an exception will be > raised. Also, thanks to the 'with' block, I'm guaranteed that the file > will have been closed before read_file() returns, which means I can > immediately go and write to the file without a conflict. I'm not sure I follow. Your solution to dealing with the scenarios raised by Steven D'Aprano is to: (1) Not bother with exceptions at all inside the function (2) Not bother with them in the user code either (3) Let any errors just crash out (raise a Python system error) (just like I did in my original jpeg program which I was called out on) (4) Or if the user code does want to check for certain errors (like, File Not Found, by far the most likely, and so that it can deal with that and continue executing), it now has to go and dig out docs for ... what? The user code needs to know what is going on inside the supposedly opaque function it's calling. -- Bartc From rosuav at gmail.com Tue Mar 22 09:00:25 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 00:00:25 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Mar 22, 2016 at 11:52 PM, Jussi Piitulainen wrote: > Now you can ask for the next item that satisfies a condition using a > generator expression: > > next(symbol for symbol in stream if not symbol.isspace()) > ---> '/' > > next(symbol for symbol in stream if not symbol.isspace()) > ---> '*' Or use filter(), which is sometimes clearer: # You probably want a more sophisticated function here def nonspace(ch): return not ch.isspace() next(filter(nonspace, stream)) ChrisA From lws4art at gmail.com Tue Mar 22 09:10:41 2016 From: lws4art at gmail.com (Jonathan N. Little) Date: Tue, 22 Mar 2016 09:10:41 -0400 Subject: crash while using PyCharm / Python3 In-Reply-To: References: <56f03080$0$5924$e4fe514c@news.xs4all.nl> Message-ID: Adam wrote: > Thanks, but why fix if it ain't broke?:-) No reason to. -- Take care, Jonathan ------------------- LITTLE WORKS STUDIO http://www.LittleWorksStudio.com From rosuav at gmail.com Tue Mar 22 09:13:48 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 00:13:48 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Mar 22, 2016 at 11:59 PM, BartC wrote: > (1) Not bother with exceptions at all inside the function > > (2) Not bother with them in the user code either > > (3) Let any errors just crash out (raise a Python system error) (just like I > did in my original jpeg program which I was called out on) > > (4) Or if the user code does want to check for certain errors (like, File > Not Found, by far the most likely, and so that it can deal with that and > continue executing), it now has to go and dig out docs for ... what? The > user code needs to know what is going on inside the supposedly opaque > function it's calling. Yes, yes, at first, and try it. The first step in any program is to write it in the very simplest way possible. That usually means ignoring all error handling. And yes, this is true in EVERY language - C, PHP, Pike, DeScribe Macro Language, you name it. Then you try it, and you find one of two things: 1) The code you've written is encountering error conditions that it can't handle, and has to pass upstream; or 2) The code you've written is getting passed error conditions that it knows how to deal with. The first one is a time to raise an exception. The second is a time to catch one. And since, by default, Python prints those exceptions to the console, you should [1] have all the information you need to catch the ones you understand, because you've seen them in testing. Note, though, that "deal with" really means "deal with", and NOT "print oops to the console and terminate". If all you're going to do with an exception is print and terminate, *let it go*, unless it's a user-triggered failure, in which case you catch it right at the very highest level, and basically fall off the end of your program. The number of times you have sys.exit() in an except clause should be vanishingly small. ChrisA [1] Some libraries force you to dig around a bit to figure out how you're supposed to import those exception classes. But that's usually *one* thing to look up in the docs - "oh, so I import foobarbletch.exceptions.OutOfBeerException". From jussi.piitulainen at helsinki.fi Tue Mar 22 09:15:09 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Tue, 22 Mar 2016 15:15:09 +0200 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: Chris Angelico writes: > On Tue, Mar 22, 2016 at 11:52 PM, Jussi Piitulainen wrote: >> Now you can ask for the next item that satisfies a condition using a >> generator expression: >> >> next(symbol for symbol in stream if not symbol.isspace()) >> ---> '/' >> >> next(symbol for symbol in stream if not symbol.isspace()) >> ---> '*' > > Or use filter(), which is sometimes clearer: > > # You probably want a more sophisticated function here > def nonspace(ch): return not ch.isspace() > > next(filter(nonspace, stream)) Sure. # But there's more fun hiding in the standard library. next(itertools.filterfalse(operator.methodcaller('isspace'), stream)) From rosuav at gmail.com Tue Mar 22 09:24:20 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 00:24:20 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Mar 23, 2016 at 12:15 AM, Jussi Piitulainen wrote: > Chris Angelico writes: > >> On Tue, Mar 22, 2016 at 11:52 PM, Jussi Piitulainen wrote: >>> Now you can ask for the next item that satisfies a condition using a >>> generator expression: >>> >>> next(symbol for symbol in stream if not symbol.isspace()) >>> ---> '/' >>> >>> next(symbol for symbol in stream if not symbol.isspace()) >>> ---> '*' >> >> Or use filter(), which is sometimes clearer: >> >> # You probably want a more sophisticated function here >> def nonspace(ch): return not ch.isspace() >> >> next(filter(nonspace, stream)) > > Sure. > > # But there's more fun hiding in the standard library. > next(itertools.filterfalse(operator.methodcaller('isspace'), stream)) ... at that point, the genexp is miles ahead in readability :) Although I do sometimes yearn for a "filterout" function that does the same thing as filter() but negates its predicate. Then you could use: next(filterout(str.isspace, stream)) to say "give me the next from the stream, filtering out those which are spaces". It's not hard to write, of course. ChrisA From ian.g.kelly at gmail.com Tue Mar 22 09:30:33 2016 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 22 Mar 2016 07:30:33 -0600 Subject: Static caching property In-Reply-To: <56f08c59$0$1590$c3e8da3$5496439d@news.astraweb.com> References: <35a5c4206a0c40e584d62d5d37b068b3@activenetwerx.com> <56f0230e$0$1616$c3e8da3$5496439d@news.astraweb.com> <56f08c59$0$1590$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Mar 21, 2016 at 6:05 PM, Steven D'Aprano wrote: > On Tue, 22 Mar 2016 04:48 am, Ian Kelly wrote: > >> You don't actually need a metaclass for this: >> >>>>> class Desc: >> ... def __get__(self, obj, type=None): >> ... if not type._cached_value: >> ... type._cached_value = compute_value(type) >> ... return type._cached_value > > > This won't quite work. What if the cached value happens to be falsey, yet > still expensive to compute? You should compare it to a known sentinel which > the expensive function will never return (possibly None). Or use a hasattr > test: if not hasattr(type, '_cached_value'). Sure. This was just a quick-and-dirty demonstration that I threw together in 30 seconds. > Also, you don't need the default type=None. The descriptor protocol should > never call __get__ without supplying the type. The obj may be None, but I > don't believe there are any circumstances where type will be None. Why do the examples in the Python docs use type=None? I literally just copy-pasted the method signature from there, since I can never remember which argument comes first. From rosuav at gmail.com Tue Mar 22 09:31:45 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 00:31:45 +1100 Subject: exec inside functions in Python 3 In-Reply-To: <56f14156$0$1619$c3e8da3$5496439d@news.astraweb.com> References: <56f14156$0$1619$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Mar 22, 2016 at 11:57 PM, Steven D'Aprano wrote: > Anyone have any idea what is going on here? > > > def test(): > spam = 1 > exec("spam = 2; print('inside exec: %d' % spam)") > print('outside exec: %d' % spam) > > > In Python 2.7: > > py> test() > inside exec: 2 > outside exec: 2 > > > > In Python 3.4: > > outside exec: 1 > py> test() > inside exec: 2 > outside exec: 1 > > > > What happened to spam? In Python 2, exec is magical. In Python 3, it's a function like any other, so it doesn't have access to local variables; what it gets is locals(), which is a one-way representation of current locals - changes don't propagate back. It'd maybe be nice to be able to tell Python to compile a function with a "real locals dictionary", which would then be mutated by locals() changes (as locals() would simply return it as-is). That'd fix this "problem", if problem it indeed is. ChrisA From jussi.piitulainen at helsinki.fi Tue Mar 22 09:32:05 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Tue, 22 Mar 2016 15:32:05 +0200 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: Chris Angelico writes: > On Wed, Mar 23, 2016 at 12:15 AM, Jussi Piitulainen wrote: >> Chris Angelico writes: >> >>> Or use filter(), which is sometimes clearer: >>> >>> # You probably want a more sophisticated function here >>> def nonspace(ch): return not ch.isspace() >>> >>> next(filter(nonspace, stream)) >> >> Sure. >> >> # But there's more fun hiding in the standard library. >> next(itertools.filterfalse(operator.methodcaller('isspace'), stream)) > > ... at that point, the genexp is miles ahead in readability :) ;) > Although I do sometimes yearn for a "filterout" function that does the > same thing as filter() but negates its predicate. Then you could use: > > next(filterout(str.isspace, stream)) > > to say "give me the next from the stream, filtering out those which > are spaces". It's not hard to write, of course. from itertools import filterfalse as filterout next(filterout(str.isspace, """ I didn't know str.isspace works like that! """)) ---> 'I' From rosuav at gmail.com Tue Mar 22 09:38:52 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 00:38:52 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Mar 23, 2016 at 12:32 AM, Jussi Piitulainen wrote: >> Although I do sometimes yearn for a "filterout" function that does the >> same thing as filter() but negates its predicate. Then you could use: >> >> next(filterout(str.isspace, stream)) >> >> to say "give me the next from the stream, filtering out those which >> are spaces". It's not hard to write, of course. > > from itertools import filterfalse as filterout > > next(filterout(str.isspace, """ > > I didn't know str.isspace works like that! > > """)) > ---> 'I' str.isspace(s) <-> s.isspace(), as long as type(s) is str. Very handy for this sort of thing. And yeah, the import is an option, but if I'm trying to explain stuff to people, it's usually easier to grab a genexp (full flexibility, but the complexity) than to play around with importing. When the function you want exists and returns true for the things you want, filter() has a big win; for any other situation, it's not worth reaching to itertools for a specific solution when the generic one will cover this and every other case. ChrisA From jon+usenet at unequivocal.co.uk Tue Mar 22 09:46:55 2016 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Tue, 22 Mar 2016 13:46:55 -0000 (UTC) Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2016-03-22, Chris Angelico wrote: > The first step in any program is to write it in the very simplest way > possible. That usually means ignoring all error handling. And yes, > this is true in EVERY language - C, PHP, Pike, DeScribe Macro > Language, you name it. I'm afraid I have to say I think this is absolutely terrible advice. If you write code in a language that does not have exceptions (e.g. C) and get it working with no error handling, the chances are approximately 100% that it will stay that way and be shipped without error handling, until that lack causes someone a major problem. From jussi.piitulainen at helsinki.fi Tue Mar 22 09:49:12 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Tue, 22 Mar 2016 15:49:12 +0200 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: Chris Angelico writes: > And yeah, the import is an option, but if I'm trying to explain stuff > to people, it's usually easier to grab a genexp (full flexibility, but > the complexity) than to play around with importing. When the function > you want exists and returns true for the things you want, filter() has > a big win; for any other situation, it's not worth reaching to > itertools for a specific solution when the generic one will cover this > and every other case. True. Filtering is so simple. The big win for me has been itertools.groupby. The other stuff I mostly play with for amusement. But hey, nothing frivolous in amusement! From bc at freeuk.com Tue Mar 22 10:02:25 2016 From: bc at freeuk.com (BartC) Date: Tue, 22 Mar 2016 14:02:25 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 22/03/2016 13:13, Chris Angelico wrote: > On Tue, Mar 22, 2016 at 11:59 PM, BartC wrote: > The first step in any program is to write it in the very simplest way > possible. That usually means ignoring all error handling. And yes, > this is true in EVERY language - C, PHP, Pike, DeScribe Macro > Language, you name it. Then you try it, and you find one of two > things: (Not in C; you can cause serious damage! But when I tried that approach in my experimental Python programs, it wasn't popular, I recall.) > Note, though, that "deal with" really means "deal with", and NOT > "print oops to the console and terminate". If all you're going to do > with an exception is print and terminate, *let it go*, unless it's a > user-triggered failure, in which case you catch it right at the very > highest level, and basically fall off the end of your program. The > number of times you have sys.exit() in an except clause should be > vanishingly small. So code like the following is consigned to history? while 1: | file = input ("Filename (press enter to quit)? ") | if file == "": break | print ("Trying to open:",file,"...") | s = readstrfile(file) | if s != 0: | | print (" ",file,"has",len(s),"characters") | else: | | print (" There was a problem opening:",file) (Oops, ignore the bars.) And, forgetting file input for a minute, what about function return values in general; should they still be allowed to return some status or error codes, or does it all have to be exceptions now? I mean, is a function allowed to still return True or False, or just False? (Or perhaps just nothing if the exception mechanism can signal either.) -- Bartc From rosuav at gmail.com Tue Mar 22 10:02:28 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 01:02:28 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Mar 23, 2016 at 12:46 AM, Jon Ribbens wrote: > On 2016-03-22, Chris Angelico wrote: >> The first step in any program is to write it in the very simplest way >> possible. That usually means ignoring all error handling. And yes, >> this is true in EVERY language - C, PHP, Pike, DeScribe Macro >> Language, you name it. > > I'm afraid I have to say I think this is absolutely terrible advice. > If you write code in a language that does not have exceptions (e.g. C) > and get it working with no error handling, the chances are > approximately 100% that it will stay that way and be shipped without > error handling, until that lack causes someone a major problem. There are languages in which it's inadvisable. But can you honestly say that you've never written a C program with even a single error check omitted, first time? (The trivial case of having never written a C program counts only because smart people leave C to other people.) And PHP's strpos function is not an abomination because it's impossible to distinguish FALSE from 0, but because *most* PHP programs are written without the mandatory check for FALSE after every strpos. So yes, it does happen, a lot. The difference with languages like Python is that this actually *is* good advice in Python. Due to a mistake in editing, the parentheses around the "true in EVERY language" sentence were lost, which would have made it clearer that this is in two distinct parts: 1) This IS what happens, whatever language you use 2) This is the right thing to do in Python, but not always elsewhere. My apologies for the confusion. ChrisA From ned at nedbatchelder.com Tue Mar 22 10:15:21 2016 From: ned at nedbatchelder.com (Ned Batchelder) Date: Tue, 22 Mar 2016 07:15:21 -0700 (PDT) Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tuesday, March 22, 2016 at 10:02:41 AM UTC-4, BartC wrote: > On 22/03/2016 13:13, Chris Angelico wrote: > > On Tue, Mar 22, 2016 at 11:59 PM, BartC wrote: > > > The first step in any program is to write it in the very simplest way > > possible. That usually means ignoring all error handling. And yes, > > this is true in EVERY language - C, PHP, Pike, DeScribe Macro > > Language, you name it. Then you try it, and you find one of two > > things: > > (Not in C; you can cause serious damage! But when I tried that approach > in my experimental Python programs, it wasn't popular, I recall.) > > > Note, though, that "deal with" really means "deal with", and NOT > > "print oops to the console and terminate". If all you're going to do > > with an exception is print and terminate, *let it go*, unless it's a > > user-triggered failure, in which case you catch it right at the very > > highest level, and basically fall off the end of your program. The > > number of times you have sys.exit() in an except clause should be > > vanishingly small. > > So code like the following is consigned to history? > > while 1: > | file = input ("Filename (press enter to quit)? ") > | if file == "": break > | print ("Trying to open:",file,"...") > | s = readstrfile(file) > | if s != 0: > | | print (" ",file,"has",len(s),"characters") > | else: > | | print (" There was a problem opening:",file) > > (Oops, ignore the bars.) We can certainly improve on this: while True: filename = input("Filename (press enter to quit)? ") if not filename: break print("Trying to open: {}...".format(filename)) try: s = readstrfile(filename) except Exception as e: print(" There was a problem opening {}: {}".format(filename, e)) else: print(" {} has {} characters".format(filename, len(s))) Some detail of the problem is now displayed. In your code, there's no information about what was wrong with the filename. Was it an invalid filename for the OS? Was the file there but the permissions prevented you from reading it? There's no way to know. With the exception-based code, we have the message from the exception itself to provide the details. > And, forgetting file input for a minute, what about function return > values in general; should they still be allowed to return some status or > error codes, or does it all have to be exceptions now? It doesn't *have* to be exceptions. But they are greatly preferred. They don't clutter the semantics of your return value, and they prevent accidents by omission. > I mean, is a function allowed to still return True or False, or just > False? (Or perhaps just nothing if the exception mechanism can signal > either.) Of course a function can still return True or False, if that's a reasonable semantic. For example, os.path.exists(filename) returns a True or False. --Ned. From anantguptadbl at gmail.com Tue Mar 22 10:23:58 2016 From: anantguptadbl at gmail.com (anantguptadbl at gmail.com) Date: Tue, 22 Mar 2016 07:23:58 -0700 (PDT) Subject: Convert list to another form but providing same information In-Reply-To: References: <1010f2cb-21f9-495b-8af4-03ad209b4c1e@googlegroups.com> Message-ID: <1ec91e1c-9d0e-448b-a7b6-194ac105f8e2@googlegroups.com> On Tuesday, March 22, 2016 at 12:01:10 AM UTC+5:30, Maurice wrote: > Just figured why: > > If I type this on the kernel: > > weirdList = [[0]*3]*5 > > weirdList > Out[257]: [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] > > weirdList[0][0] = 1 > > weirdList > Out[259]: [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]] > > All first elements of the sublists also changes. I dunno why... When we write [[0] * 3] * 5, the [0] * 3 list is repeated 5 times its something like list,list,list,list,list if we change the 1st element of list, it gets reflected on all the 5 copies From rosuav at gmail.com Tue Mar 22 10:31:37 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 01:31:37 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Mar 23, 2016 at 1:02 AM, BartC wrote: >> Note, though, that "deal with" really means "deal with", and NOT >> "print oops to the console and terminate". If all you're going to do >> with an exception is print and terminate, *let it go*, unless it's a >> user-triggered failure, in which case you catch it right at the very >> highest level, and basically fall off the end of your program. The >> number of times you have sys.exit() in an except clause should be >> vanishingly small. > > > So code like the following is consigned to history? > > while 1: > | file = input ("Filename (press enter to quit)? ") > | if file == "": break > | print ("Trying to open:",file,"...") > | s = readstrfile(file) > | if s != 0: > | | print (" ",file,"has",len(s),"characters") > | else: > | | print (" There was a problem opening:",file) > > (Oops, ignore the bars.) Your "else" clause there conceals the fact that it's actually *recovering* from an error condition, by reporting it and then returning to the main loop. So here's how I'd write it: while "moar files": filename = input("Filename (blank to quit): ") if not filename: break print("Reading %s..." % filename, end="\r") try: print(" %s has %d characters." % (filename, len(readfile(filename)))) except (IOError, OSError) as e: print(" Cannot read %s: %s" % (filename, e)) Aside from a few trivial changes to names and text strings and such, the one significant change is that I catch just two types of error (I/O and OS), and *I print out the error message*. In this case, the traceback wouldn't be very helpful, so it's dropped; but the text message is useful *to the user*, not just the programmer. If I were using a program like this and it didn't distinguish between "file not found", "permission denied", "is a directory", and "disk read failure", I would be extremely displeased. Note that I didn't catch UnicodeDecodeError here. If the file you're trying to read isn't a text file, the exception will terminate the process. Perhaps you decide that this should be handled too; all you have to do is add it to the existing except clause, or add a second one to handle this differently (maybe just "except UnicodeDecodeError: print('is binary')"). That's the beauty of exception handling; you handle as many or as few types as make sense for you to handle. > And, forgetting file input for a minute, what about function return values > in general; should they still be allowed to return some status or error > codes, or does it all have to be exceptions now? > > I mean, is a function allowed to still return True or False, or just False? > (Or perhaps just nothing if the exception mechanism can signal either.) Depends on what those return values mean! If they mean exceptional conditions, perhaps they should be changed; if they mean return values, of course they shouldn't. ChrisA From jon+usenet at unequivocal.co.uk Tue Mar 22 11:07:26 2016 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Tue, 22 Mar 2016 15:07:26 -0000 (UTC) Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2016-03-22, Chris Angelico wrote: > On Wed, Mar 23, 2016 at 12:46 AM, Jon Ribbens > wrote: >> On 2016-03-22, Chris Angelico wrote: >>> The first step in any program is to write it in the very simplest way >>> possible. That usually means ignoring all error handling. And yes, >>> this is true in EVERY language - C, PHP, Pike, DeScribe Macro >>> Language, you name it. >> >> I'm afraid I have to say I think this is absolutely terrible advice. >> If you write code in a language that does not have exceptions (e.g. C) >> and get it working with no error handling, the chances are >> approximately 100% that it will stay that way and be shipped without >> error handling, until that lack causes someone a major problem. > > There are languages in which it's inadvisable. But can you honestly > say that you've never written a C program with even a single error > check omitted, first time? No, quite the opposite - having done it is how I know that what tends to happen is that the error handling never gets added ;-) > So yes, it does happen, a lot. The difference with languages like > Python is that this actually *is* good advice in Python. Indeed, this is why I think that exceptions are a vital part of a high-level language (and why Java's mandatory exception-declarations are an abomination). > Due to a mistake in editing, the parentheses around the "true in > EVERY language" sentence were lost, which would have made it clearer > that this is in two distinct parts: > > 1) This IS what happens, whatever language you use > 2) This is the right thing to do in Python, but not always elsewhere. > > My apologies for the confusion. Ah yes with the clarification I now agree with you ;-) From rosuav at gmail.com Tue Mar 22 11:18:27 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 02:18:27 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Mar 23, 2016 at 2:07 AM, Jon Ribbens wrote: >> Due to a mistake in editing, the parentheses around the "true in >> EVERY language" sentence were lost, which would have made it clearer >> that this is in two distinct parts: >> >> 1) This IS what happens, whatever language you use >> 2) This is the right thing to do in Python, but not always elsewhere. >> >> My apologies for the confusion. > > Ah yes with the clarification I now agree with you ;-) This is why we have multiple people on the list :) I detest places that basically have "here, send a message to this address and one person will respond" - I wouldn't have noticed my lack of clarity, and the recipient would have received duff advice. Thanks for ensuring the quality of the final result :) ChrisA From tjreedy at udel.edu Tue Mar 22 11:30:47 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Mar 2016 11:30:47 -0400 Subject: need help With understanding In-Reply-To: References: Message-ID: On 3/22/2016 8:49 AM, Bob Gailer wrote: > On Mar 21, 2016 5:40 PM, "Peter Pearson" wrote: >>> i have currently installed Python, What version, on what system? >>> and im Reading this book which >>> tells me i have to have IDLE, but i cant find it on my computer. do i >>> need to install it? and if so where do/can i find it.? > I believe IDLE is part of the Python distribution. Do a search for idle > from the python directory. On Windows, the installer has a checkbox, default checked, to install tcl/tk, tkinter, and idle. There is an IDLE icon in the Python x.y group in the Start menu. I don't know the details for other systems. -- Terry Jan Reedy From dmw at yubasolutions.com Tue Mar 22 12:32:53 2016 From: dmw at yubasolutions.com (Daniel Wilcox) Date: Tue, 22 Mar 2016 09:32:53 -0700 Subject: crash while using PyCharm / Python3 In-Reply-To: References: <56f03080$0$5924$e4fe514c@news.xs4all.nl> Message-ID: Now as for *why* you needed to reinstall your graphics driver... did the graphics driver get updated before the crash? Or do we think something in the java runtime for PyCharm ate libglx or friends? I did find this PyCharm crash in which Java ate itself -- though didn't eat any library files (as that is *very* special) -- going on out a limb here maybe the crash was something like this, sans the markdown plugin: https://github.com/nicoulaj/idea-markdown/issues/247 7f7b38dd9000 r-xp 00000000 08:06 926862 /usr/lib/x86_64-linux-gnu/libxcb-glx.so.0.0.0 7f7b38dd9000-7f7b38fd8000 ---p 00015000 08:06 926862 /usr/lib/x86_64-linux-gnu/libxcb-glx.so.0.0.0 7f7b38fd8000-7f7b38fda000 r--p 00014000 08:06 926862 /usr/lib/x86_64-linux-gnu/libxcb-glx.so.0.0.0 7f7b38fda000-7f7b38fdb000 rw-p 00016000 08:06 926862 /usr/lib/x86_64-linux-gnu/libxcb-glx.s So some xcb libraries do get mapped -- but that doesn't say much really -- after all paging a library in shouldn't lead to writing to it, corrupting it -- but copy-on-write and all that crap... so maybe. Also from some quick reading on XCD it doesn't sound like it has anything to do with initializing the graphics system, which is still GLX+Xlib's job. So whether this could even affect you at startup isn't clear to me. https://xcb.freedesktop.org/opengl/ Late to the party but glad to hear everything worked out. It's been literally a decade since I worried about having working 3d graphics in Linux, so nouveau for me. Cheers! On Tue, Mar 22, 2016 at 6:10 AM, Jonathan N. Little wrote: > Adam wrote: > >> Thanks, but why fix if it ain't broke?:-) >> > > No reason to. > > > -- > Take care, > > Jonathan > ------------------- > LITTLE WORKS STUDIO > http://www.LittleWorksStudio.com > -- > https://mail.python.org/mailman/listinfo/python-list > From BigBadBob-at-mrp3-dot-com at testing.local Tue Mar 22 12:39:37 2016 From: BigBadBob-at-mrp3-dot-com at testing.local (Big Bad Bob) Date: Tue, 22 Mar 2016 09:39:37 -0700 Subject: crash while using PyCharm / Python3 In-Reply-To: References: <56f03080$0$5924$e4fe514c@news.xs4all.nl> Message-ID: On 03/21/16 17:23, Adam so wittily quipped: > "Adam" wrote in message > news:ncprqb$tl9$1 at news.albasani.net... >> >> "Jonathan N. Little" wrote in message >> news:ncpjj0$7ug$1 at dont-email.me... >>> Adam wrote: >>>> There ought to be a way to just reinstall the graphics subsystem rather >>>> than >>>> an all-or-none installation approach. >>> >>> Yes you can. Did it for a borked install of the nVidia driver. reference >>> this: >>> >>> >> >> Thanks, even after doing the following... >> >> Problem: Need to purge -fglrx >> >> Typically, the following manual commands will properly uninstall -fglrx: >> >> $ sudo apt-get remove --purge xorg-driver-fglrx fglrx* >> $ sudo apt-get install --reinstall libgl1-mesa-glx libgl1-mesa-dri >> xserver-xorg-core >> $ sudo dpkg-reconfigure xserver-xorg >> >> I still get that dreaded "The system is running in low-graphics mode" >> error. >> And, recovery mode failsafeX and Ctrl+Alt+F1 hangs with the following... >> >> >> Initializing built-in extension MIT-SCREEN-SAVER >> Initializing built-in extension DOUBLE-BUFFER >> Initializing built-in extension RECORD >> Initializing built-in extension DPMS >> Initializing built-in extension Present >> Initializing built-in extension DRI3 >> Initializing built-in extension X-Resource >> Initializing built-in extension XVideo >> Initializing built-in extension XVideo-MotionCompensation >> Initializing built-in extension SELinux >> Initializing built-in extension XFree86-VidModeExtension >> Initializing built-in extension XFree86-DGA >> Initializing built-in extension XFree86-DRI >> Initializing built-in extension DRI2 >> Loading extension GLX >> >> > > After trying the following... > > http://askubuntu.com/questions/577093/how-to-install-gnome-desktop > > $ sudo apt-get update > $ sudo apt-get install gnome-shell > > > http://tipsonubuntu.com/2014/06/06/change-display-manager-ubuntu-14-04/ > > $ sudo dpkg-reconfigure lightdm > > I am now able to login. But, > not sure what happened to the "lightdm" display manager. > I am now using "gdm" display manager. if you're able to boot up by changing things *like* the display manager, you might want to take a look at the X11 configuration directly. Adding "more cruft" to your system (i.e. gdm) isn't necessarily going to 'fix' a problem that's related to the X11 configuration. [it's one reason why I generally prefer to boot to command line rather than into a GUI for a typical linux install] as an example, you could save your xorg.conf file /etc/X11/xorg.conf and generate a new one, using 'xorg -configure' (as root). I'm guessing that when you installed the 'PyCharm' package, "some other dependent package" did something undesirable to your xorg.conf file. That would MOST CERTAINLY cause a hang during the desktop startup. it might also be fixable by re-configuring your installed packages, rather than a full-blown re-install from scratch. dpkg-reconfigure -a [the man page warns "it may take a long time" - yeah, probably will] Keep in mind that adding gdm afterwards *might* have done the 'reconfigure' on the problem package(s) already. So adding 'gdm' instead of whatever login manager you were using before [along with all of its dependent packages] would most likely have forced "the problem package" to re-configure. That very well might have "fixed" the problem on its own. So my suggestion here would be to remove this 'new' package and see if the problem comes back. Most likely it won't. From torriem at gmail.com Tue Mar 22 15:43:45 2016 From: torriem at gmail.com (Michael Torrie) Date: Tue, 22 Mar 2016 13:43:45 -0600 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56F1A071.1000506@gmail.com> On 03/22/2016 06:59 AM, BartC wrote: > I'm not sure I follow. Your solution to dealing with the scenarios > raised by Steven D'Aprano is to: > > (1) Not bother with exceptions at all inside the function Correct, if your function is not equipped to handle this exceptional circumstance and do the right thing, the right thing to do is let the caller deal with it. Otherwise debugging is very hard if not impossible. In your former example, a 0 return code means what exactly? File not found? File exists but permission is denied? > > (2) Not bother with them in the user code either Again, it depends on whether the user code is equipped to react to the exception and do the right thing. I probably would catch file and i/o errors like file-not-found and print a specific message out (or a dialog box). Or loop back to try again if the user was picking a file to work with. And despite the impression you may have gotten, it is appropriate to look before you leap. Using os.exists() and other pre-flight checks are appropriate. > (3) Let any errors just crash out (raise a Python system error) (just > like I did in my original jpeg program which I was called out on) Any exceptions your program is not explicitly equipped to deal with should indeed bubble up to the OS and crash out. After all it's by definition an exceptional event and the state of your program and data after this point is not reliable if such an event is ignored. And it provides valuable information an end user can pass back to you as a developer to find bugs you missed. > (4) Or if the user code does want to check for certain errors (like, > File Not Found, by far the most likely, and so that it can deal with > that and continue executing), it now has to go and dig out docs for ... > what? The user code needs to know what is going on inside the supposedly > opaque function it's calling. Good documentation should describe exactly what exceptions a function or library raises and why. I tend to try to follow the example of Python's standard library. I keep my exception classes few, and raise a good error message with it. But often times the exceptions we're talking about are standard Python exceptions arising from things like I/O, not custom library classes. From mail.python.org at marco.sulla.e4ward.com Tue Mar 22 15:54:40 2016 From: mail.python.org at marco.sulla.e4ward.com (Marco S.) Date: Tue, 22 Mar 2016 20:54:40 +0100 Subject: Suggestion: make sequence and map interfaces more similar Message-ID: I noticed that the sequence types does not have these methods that the map types has: get(), items(), keys(), values(). It could seem useless to have them for sequences, but I think it will ease the creation of functions and methods that allow you to input a generic iterable as parameter, but needs to use one of these methods in case the parameter is a map. In one word, it will facilitate duck typing. For the same reason, I would suggest the introduction of a new map type, vdict, a dict that by default iterates over values instead over keys. So a vdict object "d" wiil have iter(d) == iter(d.values()), and should also have a count() method, like sequence types. Indeed sequences are, in my humble opinion, a specialized case of maps, when keys are numeric only, are always contiguous without gaps and start from 0. This way we will have a simpler way to let people to use sequences or maps indifferently, and let the code untouched. From sourav524.itscient at gmail.com Tue Mar 22 16:41:41 2016 From: sourav524.itscient at gmail.com (sourav524.itscient at gmail.com) Date: Tue, 22 Mar 2016 13:41:41 -0700 (PDT) Subject: !! Immediate Interview: BizTalk/Consultanta at (Princeton, NJ) Message-ID: Hi , Please go through the below job description and let me know your interest. Please revert me: Sourav.P at itscient.com. Position: BizTalk/ Consultant Location: Princeton, NJ Duration: 6+ Months Skills: * Mandatory Skill (List out all Technical Skills required along with domain skill required) o Experience in technologies like MS BIZTALK 2010/13(At least 6+ yrs.), Microsoft SharePoint, .NET, and Visual Studio * Non Mandatory Skill * Knowledgeable with integrating SAP business partner. * Strong knowledge and deep understanding on ACORD RLC messages, AMS Gateway implementation, EBOT, ECOT * Experience with Xerox EIP for MFD, experience with configuring XEROX MFD and customize the MFD display. * Experience with Exchange server and outlook add-in * Non-Technical Requirements Required Experience (Same as Relevant Experience): * Strong programming skills with BizTalk server. Proficient with BizTalk orchestration, mapper, adapters. Proficiency in creating pipeline components * Able to apply BizTalk design patterns * Strong understanding of Object oriented programming. Able to apply Design patterns * Ability to work with limited supervision * Able to provide good quality design spec and documentation * Analytical and communication skills. Quickly understand business requirements and provide optimal solution * Programming skills in WCF, web services, XSLT, XML, XSD * SQL programming skills. Able to optimize and tune queries. Proficient in creating complex stored procedures and views. * ASP.net, C#, CSS, ADO.net * Installations, Deployment and troubleshooting * Strong experience with SharePoint services and creating web parts * Experience with CAML query. * BAM, BAM API, BAM Portal knowledge and experience * Strong understanding of BizTalk server / performance tuning * SOA architecture design and extensive ESB Toolkit knowledge and experience. Job Responsibilities: * Responsible for Solution, Estimation; * Solution Proposition to Clients; * Build client relationships in existing accounts; * Review Statement of Work; * Drive Solution / Framework Creation initiatives for customer; * Provide Architecture Guidelines, Integration roadmap and Governance to all Integration projects in the organization. Thanks & Regards Sourav Paul | Technical Recruiter IT-SCIENT LLC, Fremont, CA, USA Email: sourav524.itscient at gmail.com Phone: 510-972-5265 | Fax: 877-701-5240 |web: www.itscient.com From srkunze at mail.de Tue Mar 22 17:33:27 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Tue, 22 Mar 2016 22:33:27 +0100 Subject: how to cache invalidation Message-ID: <56F1BA27.6000101@mail.de> Hi everybody, I got another module up and running: xcache Background described here: http://srkunze.blogspot.com/2016/03/safe-cache-invalidation.html We needed a way to safely invalidate rlu_caches once a Web request has been finished. So, we came up with a solution using garbage collection and extended this to context managers for other purposes. Maybe, it can be useful to other Python devs as well. :-) Let me know if you need help with it. Best, Sven From adam at no_thanks.com Tue Mar 22 17:52:06 2016 From: adam at no_thanks.com (Adam) Date: Tue, 22 Mar 2016 14:52:06 -0700 Subject: crash while using PyCharm / Python3 References: <56f03080$0$5924$e4fe514c@news.xs4all.nl> Message-ID: "Big Bad Bob" wrote in message news:mp6dnaVAhbnh6GzLnZ2dnUU7-Y_NnZ2d at earthlink.com... > On 03/21/16 17:23, Adam so wittily quipped: >> "Adam" wrote in message >> news:ncprqb$tl9$1 at news.albasani.net... >>> >>> "Jonathan N. Little" wrote in message >>> news:ncpjj0$7ug$1 at dont-email.me... >>>> Adam wrote: >>>>> There ought to be a way to just reinstall the graphics subsystem >>>>> rather >>>>> than >>>>> an all-or-none installation approach. >>>> >>>> Yes you can. Did it for a borked install of the nVidia driver. >>>> reference >>>> this: >>>> >>>> >>> >>> Thanks, even after doing the following... >>> >>> Problem: Need to purge -fglrx >>> >>> Typically, the following manual commands will properly uninstall -fglrx: >>> >>> $ sudo apt-get remove --purge xorg-driver-fglrx fglrx* >>> $ sudo apt-get install --reinstall libgl1-mesa-glx libgl1-mesa-dri >>> xserver-xorg-core >>> $ sudo dpkg-reconfigure xserver-xorg >>> >>> I still get that dreaded "The system is running in low-graphics mode" >>> error. >>> And, recovery mode failsafeX and Ctrl+Alt+F1 hangs with the following... >>> >>> >>> Initializing built-in extension MIT-SCREEN-SAVER >>> Initializing built-in extension DOUBLE-BUFFER >>> Initializing built-in extension RECORD >>> Initializing built-in extension DPMS >>> Initializing built-in extension Present >>> Initializing built-in extension DRI3 >>> Initializing built-in extension X-Resource >>> Initializing built-in extension XVideo >>> Initializing built-in extension XVideo-MotionCompensation >>> Initializing built-in extension SELinux >>> Initializing built-in extension XFree86-VidModeExtension >>> Initializing built-in extension XFree86-DGA >>> Initializing built-in extension XFree86-DRI >>> Initializing built-in extension DRI2 >>> Loading extension GLX >>> >>> >> >> After trying the following... >> >> http://askubuntu.com/questions/577093/how-to-install-gnome-desktop >> >> $ sudo apt-get update >> $ sudo apt-get install gnome-shell >> >> >> http://tipsonubuntu.com/2014/06/06/change-display-manager-ubuntu-14-04/ >> >> $ sudo dpkg-reconfigure lightdm >> >> I am now able to login. But, >> not sure what happened to the "lightdm" display manager. >> I am now using "gdm" display manager. > > if you're able to boot up by changing things *like* the display manager, > you might want to take a look at the X11 configuration directly. Adding > "more cruft" to your system (i.e. gdm) isn't necessarily going to 'fix' > a problem that's related to the X11 configuration. > > [it's one reason why I generally prefer to boot to command line rather > than into a GUI for a typical linux install] > > as an example, you could save your xorg.conf file > /etc/X11/xorg.conf No such file on my system. Is it even needed ? > > and generate a new one, using 'xorg -configure' (as root). > > I'm guessing that when you installed the 'PyCharm' package, "some other > dependent package" did something undesirable to your xorg.conf file. I no longer think PyCharm / Python3 is the cause of the crash. It was just a coincidence. Search for "lightdm problem ubuntu 14.04" > > That would MOST CERTAINLY cause a hang during the desktop startup. lightdm was failing. > > it might also be fixable by re-configuring your installed packages, > rather than a full-blown re-install from scratch. > > dpkg-reconfigure -a > > [the man page warns "it may take a long time" - yeah, probably will] > > > Keep in mind that adding gdm afterwards *might* have done the > 'reconfigure' on the problem package(s) already. So adding 'gdm' > instead of whatever login manager you were using before [along with all > of its dependent packages] would most likely have forced "the problem > package" to re-configure. That very well might have "fixed" the problem > on its own. So my suggestion here would be to remove this 'new' package > and see if the problem comes back. Most likely it won't. > Thanks, but it's working fine now. :-) From adam at no_thanks.com Tue Mar 22 17:52:58 2016 From: adam at no_thanks.com (Adam) Date: Tue, 22 Mar 2016 14:52:58 -0700 Subject: crash while using PyCharm / Python3 References: <56f03080$0$5924$e4fe514c@news.xs4all.nl> Message-ID: "Jonathan N. Little" wrote in message news:ncrg2v$jo$2 at dont-email.me... > Adam wrote: >> Thanks, but why fix if it ain't broke? :-) > > No reason to. Yup, I agree. > > -- > Take care, > > Jonathan > ------------------- > LITTLE WORKS STUDIO > http://www.LittleWorksStudio.com From rosuav at gmail.com Tue Mar 22 18:23:12 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 09:23:12 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <56F1A071.1000506@gmail.com> References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> <56F1A071.1000506@gmail.com> Message-ID: On Wed, Mar 23, 2016 at 6:43 AM, Michael Torrie wrote: > And despite the impression you may have gotten, it is appropriate to > look before you leap. Using os.exists() and other pre-flight checks are > appropriate. Hmm, can you justify this? Remember, as soon as any other process has done anything, your LBYL is invalid. You check that the file exists, then it gets deleted. Or you check that it doesn't, and bam, suddenly it does. The only way to be certain is to do an operation that enforces it on the hard disk itself - either open the file (after that, deletion can't affect you - on some OSes, deletion can't happen), or create it and hold it open exclusively (nobody else can create a file with that name). >> (4) Or if the user code does want to check for certain errors (like, >> File Not Found, by far the most likely, and so that it can deal with >> that and continue executing), it now has to go and dig out docs for ... >> what? The user code needs to know what is going on inside the supposedly >> opaque function it's calling. > > Good documentation should describe exactly what exceptions a function or > library raises and why. I tend to try to follow the example of Python's > standard library. I keep my exception classes few, and raise a good > error message with it. > > But often times the exceptions we're talking about are standard Python > exceptions arising from things like I/O, not custom library classes. If you have documentation like this, it should list only the exceptions that you explicitly raise, not those that can bubble up through it - this is where Java gets it wrong, IMO. If you attempt to read from a file that gets passed in as an argument, AttributeError could get raised, but you shouldn't document that; but if you have a line of code that says "raise InconsistentDNSRecordError", then yes, that's something worth documenting. ChrisA From steve at pearwood.info Tue Mar 22 21:14:39 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 23 Mar 2016 12:14:39 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f1ee00$0$1608$c3e8da3$5496439d@news.astraweb.com> On Wed, 23 Mar 2016 01:02 am, BartC wrote: > And, forgetting file input for a minute, what about function return > values in general; should they still be allowed to return some status or > error codes, or does it all have to be exceptions now? It doesn't *have to* be exceptions, but exceptions are considered to be a generally better approach. Some people disagree, must famously Rob Pike, the highly respected creator of Go (the language, not the ancient Chinese board game). But Go's approach of returning error codes is most certainly not Pythonic. (It might be Go-thonic :-) > I mean, is a function allowed to still return True or False, or just > False? (Or perhaps just nothing if the exception mechanism can signal > either.) You can answer this question yourself by looking at what functions are provided in the standard library and built-ins: py> "hello world".find("goodbye") -1 py> "hello world".startswith("goodbye") False -- Steven From rosuav at gmail.com Tue Mar 22 21:21:50 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 12:21:50 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <56f1ee00$0$1608$c3e8da3$5496439d@news.astraweb.com> References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> <56f1ee00$0$1608$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Mar 23, 2016 at 12:14 PM, Steven D'Aprano wrote: >> I mean, is a function allowed to still return True or False, or just >> False? (Or perhaps just nothing if the exception mechanism can signal >> either.) > > > You can answer this question yourself by looking at what functions are > provided in the standard library and built-ins: > > py> "hello world".find("goodbye") > -1 > py> "hello world".startswith("goodbye") > False To add to the "experiment" advice, a general rule of thumb: Any function/method that appears to be asking a yes/no question should be happy to return True/False for the two answers. It can still raise if the question doesn't make sense: >>> "hello world".startswith(3.14159) Traceback (most recent call last): File "", line 1, in TypeError: startswith first arg must be str or a tuple of str, not float >>> "hello world".startswith(b"\x41") Traceback (most recent call last): File "", line 1, in TypeError: startswith first arg must be str or a tuple of str, not bytes ChrisA From best_lay at yahoo.com Tue Mar 22 22:46:14 2016 From: best_lay at yahoo.com (Wildman) Date: Tue, 22 Mar 2016 21:46:14 -0500 Subject: Key Binding Problem Message-ID: Platform: Linux Python: v.2.7.9 Tkinter: v.8.6.2 My program has some buttons for file operations, load_image, save_image, and quit. I would like to bind a key that will execute the procedures for each of the buttons. The binding for the quit button was easy... root.bind("", quit) root.bind("", quit) That works but it not executing a quit button procedure. It is merely executing an internal command. My problem is calling an actual button procedure. Over the last several hours I have tried many different syntax arrangements and I keep getting "object not defined" errors. I also tried placing the bind statements into other places in the code. I have run out of ideas. Below is a basic skeleton of my code. Any help appreciated. #!/usr/bin/env python try: import Tkinter as tk from Tkinter import Tk except ImportError: import tkinter as tk from tkinter import Tk import tkFileDialog, tkMessageBox import Image, ImageTk import base64, io, os, subprocess class cv(): # global variables class Window(tk.Frame): def __init__(self, master = None): tk.Frame.__init__(self,master) self.master = master self.init_window() def init_window(self): self.master.title("My Program") self.pack(fill=tk.BOTH, expand=1) self.quitButton = tk.Button(self, text="Quit", underline=0, width=10, command=self.quit) self.quitButton.place(x=224, y=422) self.loadButton = tk.Button(self, text="Load Image", underline=0, width = 10, command=self.load_image) self.loadButton.place(x=138, y=46) # create the rest of the widgets def load_image(self): # load image file def save_image(self): # save the image def other procedure definitions root = Tk() root.bind("", quit) # these two work root.bind("", quit) root.bind("", load_image) # these do not work root.bind("", load_image) # object not defined errors root.bind("", save_image) root.bind("", save_image) root.minsize(width=554, height=462) root.maxsize(width=554, height=462) app = Window(root) root.mainloop() My question is how do I coax bind into executing the button procedures? Or is there a way to generate the button click event from the binding? -- GNU/Linux user #557453 "Be at war with your vices, at peace with your neighbors, and let every new year find you a better man." -Benjamin Franklin From python at mrabarnett.plus.com Tue Mar 22 23:02:51 2016 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 23 Mar 2016 03:02:51 +0000 Subject: Key Binding Problem In-Reply-To: References: Message-ID: <56F2075B.2060408@mrabarnett.plus.com> On 2016-03-23 02:46, Wildman via Python-list wrote: > Platform: Linux > Python: v.2.7.9 > Tkinter: v.8.6.2 > > My program has some buttons for file operations, load_image, > save_image, and quit. I would like to bind a key that will > execute the procedures for each of the buttons. The binding > for the quit button was easy... > > root.bind("", quit) > root.bind("", quit) > > That works but it not executing a quit button procedure. > It is merely executing an internal command. My problem is > calling an actual button procedure. Over the last several > hours I have tried many different syntax arrangements and > I keep getting "object not defined" errors. I also tried > placing the bind statements into other places in the code. > I have run out of ideas. > > Below is a basic skeleton of my code. Any help appreciated. > > #!/usr/bin/env python > > try: > import Tkinter as tk > from Tkinter import Tk > except ImportError: > import tkinter as tk > from tkinter import Tk > import tkFileDialog, tkMessageBox > import Image, ImageTk > import base64, io, os, subprocess > > class cv(): > > # global variables > > class Window(tk.Frame): > > def __init__(self, master = None): > tk.Frame.__init__(self,master) > self.master = master > self.init_window() > > def init_window(self): > self.master.title("My Program") > self.pack(fill=tk.BOTH, expand=1) > self.quitButton = tk.Button(self, > text="Quit", > underline=0, > width=10, > command=self.quit) > self.quitButton.place(x=224, y=422) > > self.loadButton = tk.Button(self, > text="Load Image", > underline=0, > width = 10, > command=self.load_image) > self.loadButton.place(x=138, y=46) > > # create the rest of the widgets > > def load_image(self): > # load image file > > def save_image(self): > # save the image > > def other procedure definitions > > root = Tk() > root.bind("", quit) # these two work > root.bind("", quit) > root.bind("", load_image) # these do not work > root.bind("", load_image) # object not defined errors > root.bind("", save_image) > root.bind("", save_image) > root.minsize(width=554, height=462) > root.maxsize(width=554, height=462) > app = Window(root) > root.mainloop() > > My question is how do I coax bind into executing the > button procedures? Or is there a way to generate the > button click event from the binding? > It won't let you bind to a function called "load_image" because there isn't a function called "load_image"! The "Window" class, however, does have a method with that name. Try binding the keys in Window.__init__ or Window.init_window: def init_window(self): ... root.bind("", self.load_image) From nickeubank at gmail.com Tue Mar 22 23:17:07 2016 From: nickeubank at gmail.com (Nick Eubank) Date: Wed, 23 Mar 2016 03:17:07 +0000 Subject: No subject Message-ID: Hello All, Found an odd behavior I'd never known about today, not sure if it's a bug or known. Python 3.4.4 (anaconda). True, False, 0, 1 can all be used as dictionary keys. But Apparently True and 1 hash to the same item and False and 0 hash to the same item, so they can easily overwrite (which I spent a while banging my head over today). In other words: In[1]: d = {True: 'a', False: 'b'} d[0] = 'z' d[False] Out[1]: 'z' I understand that True and False are sub-types of ints, but it's not clear to me why (i.e. certainly didn't feel intuitive) that they would be treated the same as keys. Relatedly, if this is a desired behavior, any advice one how best to work with dictionaries when one wants "True" and 1 to be different? I'm working on a function that accepts arguments that may be "True" or 1 (meaning very different things) and am seeking a pythonic solution... From tjreedy at udel.edu Tue Mar 22 23:52:57 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Mar 2016 23:52:57 -0400 Subject: Key Binding Problem In-Reply-To: References: Message-ID: On 3/22/2016 10:46 PM, Wildman via Python-list wrote: > Platform: Linux > Python: v.2.7.9 > Tkinter: v.8.6.2 > > My program has some buttons for file operations, load_image, > save_image, and quit. I would like to bind a key that will > execute the procedures for each of the buttons. The binding > for the quit button was easy... > > root.bind("", quit) > root.bind("", quit) > > That works but it not executing a quit button procedure. > It is merely executing an internal command. My problem is > calling an actual button procedure. Over the last several > hours I have tried many different syntax arrangements and > I keep getting "object not defined" errors. I also tried > placing the bind statements into other places in the code. > I have run out of ideas. > > Below is a basic skeleton of my code. Any help appreciated. > > #!/usr/bin/env python > > try: > import Tkinter as tk > from Tkinter import Tk The second import is not needed. tk.Tk is short and should be called just once. > except ImportError: > import tkinter as tk > from tkinter import Tk ditto. > import tkFileDialog, tkMessageBox These are 2.x only and should be after the Tkinter import. For 3.x, import tk.filedialog, tk.messagebox -- Terry Jan Reedy From challakarthik at gmail.com Wed Mar 23 00:13:06 2016 From: challakarthik at gmail.com (Karthik Reddy) Date: Tue, 22 Mar 2016 21:13:06 -0700 (PDT) Subject: GAPI -- Sharing a post to Social Networking Pages from my App In-Reply-To: <56f12a00$0$22142$c3e8da3$5496439d@news.astraweb.com> References: <0a9353af-8179-4e33-ac36-fce8a3160465@googlegroups.com> <6588aa57-52b8-45e9-86e1-16647e4a89f7@googlegroups.com> <56f12a00$0$22142$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9e1a445f-79e4-4d44-af28-bc19be4e9555@googlegroups.com> On Tuesday, March 22, 2016 at 4:48:37 PM UTC+5:30, Steven D'Aprano wrote: > On Tue, 22 Mar 2016 09:37 pm, Karthik Reddy wrote: > > > The error I am getting is "Uncaught ReferenceError: gapi is not defined" > > > Have you tried googling for it? That's a Javascript error: > > https://duckduckgo.com/html/?q=uncaught+reference+error+gapi+is+not+defined > > > > -- > Steven Hi I resolved the error but I am not able to post my post . I tried https://developers.google.com/+/domains/authentication/#authorizing_requests_with_oauth_20 I am getting the below error When i copied the url. Error: invalid_client The OAuth client was not found. Even i gave Client_id correctly Thanks, Karthik From best_lay at yahoo.com Wed Mar 23 00:28:32 2016 From: best_lay at yahoo.com (Wildman) Date: Tue, 22 Mar 2016 23:28:32 -0500 Subject: Key Binding Problem References: Message-ID: On Wed, 23 Mar 2016 03:02:51 +0000, MRAB wrote: > On 2016-03-23 02:46, Wildman via Python-list wrote: >> My question is how do I coax bind into executing the >> button procedures? Or is there a way to generate the >> button click event from the binding? >> > It won't let you bind to a function called "load_image" because there > isn't a function called "load_image"! > > The "Window" class, however, does have a method with that name. > > Try binding the keys in Window.__init__ or Window.init_window: > > def init_window(self): > ... > root.bind("", self.load_image) Here is what I tried: class Window(tk.Frame): def __init__(self, master = None): tk.Frame.__init__(self,master) self.master = master root.bind("l", self.load_image) I get this error and it doesn't make any sense to me: Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1535, in __call__ return self.func(*args) TypeError: load_image() takes exactly 1 argument (2 given) -- GNU/Linux user #557453 The cow died so I don't need your bull! From best_lay at yahoo.com Wed Mar 23 00:30:09 2016 From: best_lay at yahoo.com (Wildman) Date: Tue, 22 Mar 2016 23:30:09 -0500 Subject: Key Binding Problem References: Message-ID: On Tue, 22 Mar 2016 23:52:57 -0400, Terry Reedy wrote: > On 3/22/2016 10:46 PM, Wildman via Python-list wrote: >> Platform: Linux >> Python: v.2.7.9 >> Tkinter: v.8.6.2 >> >> My program has some buttons for file operations, load_image, >> save_image, and quit. I would like to bind a key that will >> execute the procedures for each of the buttons. The binding >> for the quit button was easy... >> >> root.bind("", quit) >> root.bind("", quit) >> >> That works but it not executing a quit button procedure. >> It is merely executing an internal command. My problem is >> calling an actual button procedure. Over the last several >> hours I have tried many different syntax arrangements and >> I keep getting "object not defined" errors. I also tried >> placing the bind statements into other places in the code. >> I have run out of ideas. >> >> Below is a basic skeleton of my code. Any help appreciated. >> >> #!/usr/bin/env python >> >> try: >> import Tkinter as tk >> from Tkinter import Tk > > The second import is not needed. tk.Tk is short and should be called > just once. > >> except ImportError: >> import tkinter as tk >> from tkinter import Tk > > ditto. > >> import tkFileDialog, tkMessageBox > > These are 2.x only and should be after the Tkinter import. > For 3.x, import tk.filedialog, tk.messagebox Thanks for the info. Making the changes... -- GNU/Linux user #557453 The cow died so I don't need your bull! From orgnut at yahoo.com Wed Mar 23 01:17:13 2016 From: orgnut at yahoo.com (Larry Hudson) Date: Tue, 22 Mar 2016 22:17:13 -0700 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> Message-ID: <3LidnZ0Tl9REu2_LnZ2dnUU7-K3NnZ2d@giganews.com> I didn't see anyone responding to this, so I'll pop in here... On 03/22/2016 04:05 AM, BartC wrote: [...] > (Suppose you need both the value and its index in the loop? Then the one-line for above won't > work. For example, 'something' is [10,20,30] and you want to print: > > 0: 10 > 1: 20 > 2: 30 ) > Your lack of knowledge of Python is showing again... Python has "enumerate" just for this purpose. Your example would be written as: for i, val in enumerate(something): print('{}: {}'.format(i, val)) However, in this specific example, the i is not used as an actual index but rather a line-number. So you can change "enumerate(something)" to "enumerate(something, 1)" to set the starting number to 1 instead of the default 0, and the lines will be numbered 1, 2 and 3 rather than 0, 1 and 2. As always, the choice is yours. ;-) From patrick.rugamba at 365.elmhurst.edu Wed Mar 23 01:28:16 2016 From: patrick.rugamba at 365.elmhurst.edu (Patrick Rugamba) Date: Wed, 23 Mar 2016 05:28:16 +0000 Subject: Pop ups. Message-ID: Hello, This thing is making me run crazy. Am having these pop ups as I try using pycharm saying modify setup, and it is really annoying. I have no clue what is causing it but if it can?t be fixed I?d rather uninstall the programs because I may end up destroying my pc. I hope you guys can help. Thanks. Sent from Mail for Windows 10 From steve+comp.lang.python at pearwood.info Wed Mar 23 02:07:00 2016 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 23 Mar 2016 17:07 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> <56F1A071.1000506@gmail.com> Message-ID: <56f23287$0$1607$c3e8da3$5496439d@news.astraweb.com> On Wednesday 23 March 2016 09:23, Chris Angelico wrote: > On Wed, Mar 23, 2016 at 6:43 AM, Michael Torrie wrote: >> And despite the impression you may have gotten, it is appropriate to >> look before you leap. Using os.exists() and other pre-flight checks are >> appropriate. > > Hmm, can you justify this? Remember, as soon as any other process has > done anything, your LBYL is invalid. "Time of check to time of use": https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use Fortunately, not all such "bugs" are of equal severity. In this case, there are two failure modes. Consider a *false positive* bug: we think the file exists when it actually doesn't. if os.path.exists(filename): os.unlink(filename) # some other process does this open(filename) This is probably bad. At best, we get some sort of unhandled exception. At worst, we get some sort of TOCTTOU security vulnerability. Consider a *false negative* bug: we think the file doesn't exist, when it actually does, and report an error: if os.path.exists(filename): ... else: open(filename, 'w').write('stuff') # some other process does this print("No such file, please try again.") This is probably trivial. The user simply tries again, or refreshes the application's "file open" selector, or something similar. No harm done. Or consider scripting a file rename: for old, new in zip(oldnames, newnames): if os.path.exists(new): print("skipping...") os.rename(old, new) Is it safe? Strictly speaking, no, but for a single user computer, it's probably safe enough. If I'm busy saving new files to a directory at the same time as I'm running a bulk rename of the files in that same directory, I probably deserve to have data loss :-) (But having said that, if someone can give a recipe for the right way to do a file rename without overwriting existing files, I'd love to see it.) -- Steve From ben+python at benfinney.id.au Wed Mar 23 02:09:19 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 23 Mar 2016 17:09:19 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> Message-ID: <85h9fxene8.fsf@benfinney.id.au> Steven D'Aprano writes: > On Mon, 21 Mar 2016 06:47 pm, Ben Finney wrote: > > > Bart can show good faith by *learning* idiomatic Python, with the > > humility of a beginner. And also by refraining from rhetoric about > > how bad Python's performance is, until he gains experience to make > > those claims. > > "Humility of a beginner"... what a strange phrase to use about > somebody who has been programming for decades. What a strange reading of what I wrote. Clearly I'm referring to the fact Bart is a beginner in Python. To show good faith in learning Python ? if indeed that is what Bart wants, which I'm not convinced of given how much he prefers to talk about a different private programming language instead ? then he should be taking advantage of the teaching resources that have been offered numerous times. > What exactly is the problem here? Is it that Bart hasn't earned the > right to say what we all know, that Python is slow, because he's an > outsider? The problem is that Bart simultaneously is a beginner at Python, and expresses astonishment that everyone shrugs when Bart's dreadfully-written code performs so badly. Good faith is contradicted by asserting knowledge of Python, complaining about how some deliberately non-idiomatic Python code is performing poorly, dismissing suggestions for improvement ? specifically in the context of someone who admittedly knows so little about Python. -- \ ?? one of the main causes of the fall of the Roman Empire was | `\ that, lacking zero, they had no way to indicate successful | _o__) termination of their C programs.? ?Robert Firth | Ben Finney From challakarthik at gmail.com Wed Mar 23 02:09:24 2016 From: challakarthik at gmail.com (Karthik Reddy) Date: Tue, 22 Mar 2016 23:09:24 -0700 (PDT) Subject: GAPI -- Sharing a post to Social Networking Pages from my App In-Reply-To: <9e1a445f-79e4-4d44-af28-bc19be4e9555@googlegroups.com> References: <0a9353af-8179-4e33-ac36-fce8a3160465@googlegroups.com> <6588aa57-52b8-45e9-86e1-16647e4a89f7@googlegroups.com> <56f12a00$0$22142$c3e8da3$5496439d@news.astraweb.com> <9e1a445f-79e4-4d44-af28-bc19be4e9555@googlegroups.com> Message-ID: <1ccb2d20-5862-440a-9713-298a738c80de@googlegroups.com> On Wednesday, March 23, 2016 at 9:43:21 AM UTC+5:30, Karthik Reddy wrote: > On Tuesday, March 22, 2016 at 4:48:37 PM UTC+5:30, Steven D'Aprano wrote: > > On Tue, 22 Mar 2016 09:37 pm, Karthik Reddy wrote: > > > > > The error I am getting is "Uncaught ReferenceError: gapi is not defined" > > > > > > Have you tried googling for it? That's a Javascript error: > > > > https://duckduckgo.com/html/?q=uncaught+reference+error+gapi+is+not+defined > > > > > > > > -- > > Steven > > Hi I resolved the error but I am not able to post my post . > I tried https://developers.google.com/+/domains/authentication/#authorizing_requests_with_oauth_20 > > I am getting the below error When i copied the url. > > Error: invalid_client > > The OAuth client was not found. > > Even i gave Client_id correctly > > Thanks, > Karthik Hi Steven I resolved this error also Now I am getting a pop up for google sharing but If click on share button its not sharing.Any help please From rosuav at gmail.com Wed Mar 23 02:28:45 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 17:28:45 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <56f23287$0$1607$c3e8da3$5496439d@news.astraweb.com> References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56f09973$0$1601$c3e8da3$5496439d@news.astraweb.com> <56F1A071.1000506@gmail.com> <56f23287$0$1607$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Mar 23, 2016 at 5:07 PM, Steven D'Aprano wrote: > Fortunately, not all such "bugs" are of equal severity. In this case, there > are two failure modes. Consider a *false positive* bug: we think the file > exists when it actually doesn't. > > if os.path.exists(filename): > os.unlink(filename) # some other process does this > open(filename) > > > This is probably bad. At best, we get some sort of unhandled exception. Yes - and it's exactly why it's not worth bothering with the 'exists' check. Your code would end up looking like this: if os.path.exists(filename): try: open(filename) except FileNotFoundError: # file got deleted out from under you else: # file doesn't exist Which is exactly why error handling (whether with structured exceptions or error codes) is better than LBYL for anything involving the file system, or shared resources and concurrency, or anything with a potential TOCTTOU discrepancy. All the other situations (apart from renaming) are handled the same way - sure, the consequences aren't as serious, but it's just as easy to use the same technique everywhere. I don't know of a cross-platform way to rename without overwriting, but the "mv" command on my system has a --no-clobber option, and the underlying rename system call seems to have a non-standard flags parameter that can be set to RENAME_NOREPLACE to prevent overwriting. This is generally the way to fix it; it's only in the system call that this can actually be done reliably (hence things like temp file creation are done with flags to the file-open syscall). ChrisA From tjreedy at udel.edu Wed Mar 23 02:47:47 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 23 Mar 2016 02:47:47 -0400 Subject: Key Binding Problem In-Reply-To: References: Message-ID: On 3/23/2016 12:28 AM, Wildman via Python-list wrote: > On Wed, 23 Mar 2016 03:02:51 +0000, MRAB wrote: > >> On 2016-03-23 02:46, Wildman via Python-list wrote: >>> My question is how do I coax bind into executing the >>> button procedures? Or is there a way to generate the >>> button click event from the binding? >>> >> It won't let you bind to a function called "load_image" because there >> isn't a function called "load_image"! >> >> The "Window" class, however, does have a method with that name. >> >> Try binding the keys in Window.__init__ or Window.init_window: >> >> def init_window(self): >> ... >> root.bind("", self.load_image) > > Here is what I tried: > > class Window(tk.Frame): > > def __init__(self, master = None): > tk.Frame.__init__(self,master) > self.master = master > root.bind("l", self.load_image) > > I get this error and it doesn't make any sense to me: > > Exception in Tkinter callback > Traceback (most recent call last): > File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1535, in __call__ > return self.func(*args) > TypeError: load_image() takes exactly 1 argument (2 given) Event handlers must have one parameter (other than 'self' for methods), the event, as that is what they will be passed. You defined load_image like this. def load_image(self): # load image file It should be this def load_image(self, event): # load image file You are free to ignore the event object and some people then name the parameter '_' (or dummy) to signify that it will be ignored. def load_image(self, _): # load image file You must pass the bound method, as you did, and not the function itself (which has two parameters). -- Terry Jan Reedy From hongyi.zhao at gmail.com Wed Mar 23 03:12:16 2016 From: hongyi.zhao at gmail.com (Hongyi Zhao) Date: Wed, 23 Mar 2016 07:12:16 +0000 (UTC) Subject: Obtain the variable in bash. Message-ID: Hi all, I exported a variable in my .bashrc as follows: export MY_VAR="fdsfads" Then I soured the .bashrc and do the testing as follows: werner at debian-01:~$ python -c "import os; print os.environ['MY_VAR']" fdsfads But, when I run the same commands in pycharm and wing ide, I failed the obtain the value of this variable. I'm very confused with this issue. Any hints? Regards -- .: Hongyi Zhao [ hongyi.zhao AT gmail.com ] Free as in Freedom :. From rosuav at gmail.com Wed Mar 23 03:19:04 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 18:19:04 +1100 Subject: Obtain the variable in bash. In-Reply-To: References: Message-ID: On Wed, Mar 23, 2016 at 6:12 PM, Hongyi Zhao wrote: > I exported a variable in my .bashrc as follows: > > export MY_VAR="fdsfads" > > Then I soured the .bashrc and do the testing as follows: > > werner at debian-01:~$ python -c "import os; print os.environ['MY_VAR']" > fdsfads > > But, when I run the same commands in pycharm and wing ide, I failed the > obtain the value of this variable. > > I'm very confused with this issue. > Did you start pycharm/wing from the same session in which you sourced .bashrc? If not, they won't see that change. My guess is that you started the IDEs from your GUI in some way (the Applications menu or something). If that's the case, they'll inherit their environment from your GUI. You _may_ be able to have them "notice" your change to .bashrc by logging out and in again, or rebooting; it depends how your system is configured. ChrisA From ben+python at benfinney.id.au Wed Mar 23 04:08:46 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 23 Mar 2016 19:08:46 +1100 Subject: Obtain the variable in bash. References: Message-ID: <858u19ehv5.fsf@benfinney.id.au> Hongyi Zhao writes: > I exported a variable in my .bashrc as follows: > > export MY_VAR="fdsfads" That ?export? means that child processes of this one (i.e., the shell in which that command executed) will inherit that variable in their environment. Processes that are not children of this one, will not be affected. > Then I soured the .bashrc and do the testing as follows: > > werner at debian-01:~$ python -c "import os; print os.environ['MY_VAR']" > fdsfads Yes. Because that ?python? process is started from a process which has that exported variable, that ?python? process inherits the variable in its environment. > But, when I run the same commands in pycharm and wing ide, I failed the > obtain the value of this variable. Were they started as child processes from the shell that is exporting the variable? See for a discussion of how the process environment variables are inherited. -- \ ?Every man would like to be God, if it were possible; some few | `\ find it difficult to admit the impossibility.? ?Bertrand | _o__) Russell, _Power: A New Social Analysis_, 1938 | Ben Finney From dieter at handshake.de Wed Mar 23 04:24:16 2016 From: dieter at handshake.de (dieter) Date: Wed, 23 Mar 2016 09:24:16 +0100 Subject: monkey patching __code__ References: <56EBEB5A.7050207@mail.de> <56EED3DE.7050101@mail.de> <56F13417.8060108@mail.de> Message-ID: <87egb1vbyn.fsf@handshake.de> "Sven R. Kunze" writes: > ... > As far as I can see, the code replacement approach solves the problem > once and for all. Thus is far more stable. > > Manually finding out every single module that might or might not have > imported "reverse" before we could monkeypatch it might result in a > maintenance nightmare (just think about a Django upgrade). But you have observed that you cannot do everything with a code substitution: a function call does not only depend on the code but also on other properties of the function object: e.g. the parameter processing. You might be able to change them in a similar way as "__code__" (i.e. direct modification). Otherwise, you would need to construct a new "function object" -- and lose the possibility to completely change the function object in place. From hongyi.zhao at gmail.com Wed Mar 23 04:35:43 2016 From: hongyi.zhao at gmail.com (Hongyi Zhao) Date: Wed, 23 Mar 2016 08:35:43 +0000 (UTC) Subject: Obtain the variable in bash. References: Message-ID: On Wed, 23 Mar 2016 18:19:04 +1100, Chris Angelico wrote: > Did you start pycharm/wing from the same session in which you sourced > .bashrc? If not, they won't see that change. Thanks a lot for this explanations. It does behaves as you said which I previously not noticed. > > My guess is that you started the IDEs from your GUI in some way (the > Applications menu or something). If that's the case, they'll inherit > their environment from your GUI. You _may_ be able to have them "notice" > your change to .bashrc by logging out and in again, or rebooting; it > depends how your system is configured. I tried and find that I must set the variable in .profile file, instead of .bashrc, in order to let the IDEs started from my GUI to recognize them after I logged out and in again. Regards > > ChrisA -- .: Hongyi Zhao [ hongyi.zhao AT gmail.com ] Free as in Freedom :. From rosuav at gmail.com Wed Mar 23 04:43:39 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 19:43:39 +1100 Subject: No subject In-Reply-To: References: Message-ID: On Wed, Mar 23, 2016 at 2:17 PM, Nick Eubank wrote: > But Apparently True and 1 hash to the same item and False and 0 hash to the > same item, so they can easily overwrite (which I spent a while banging my > head over today). > > In other words: > > In[1]: > d = {True: 'a', False: 'b'} > d[0] = 'z' > d[False] > > Out[1]: > 'z' > > I understand that True and False are sub-types of ints, but it's not clear > to me why (i.e. certainly didn't feel intuitive) that they would be treated > the same as keys. > > Relatedly, if this is a desired behavior, any advice one how best to work > with dictionaries when one wants "True" and 1 to be different? I'm working > on a function that accepts arguments that may be "True" or 1 (meaning very > different things) and am seeking a pythonic solution... (Presumably everywhere that you write "True" you mean the boolean value True, not the string "True", which would be completely separate.) Dictionary keys are defined on the basis of equality, so anything that compares equal will match: >>> d = {True: 'a', False: 'b'} >>> d[0] 'b' >>> d[0.0] 'b' Since you have True and 1 meaning very different things, your program is already somewhat non-Pythonic. So your best solution is probably going to be something messy, like having your dictionary keys incorporate the type of the object. This isn't going to be easy or clean, but if that's what you have to work with, so be it. (It's not half as bad as the mess I was helping one of my students with; she's coping with a Python module that's a hyper-thin layer over an HTTP/XML request, and it simply takes the returned XML blob and naively converts it into a Python dictionary. Makes for some ugly code - but that's not her fault.) ChrisA From rosuav at gmail.com Wed Mar 23 04:45:08 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 19:45:08 +1100 Subject: Obtain the variable in bash. In-Reply-To: References: Message-ID: On Wed, Mar 23, 2016 at 7:35 PM, Hongyi Zhao wrote: >> My guess is that you started the IDEs from your GUI in some way (the >> Applications menu or something). If that's the case, they'll inherit >> their environment from your GUI. You _may_ be able to have them "notice" >> your change to .bashrc by logging out and in again, or rebooting; it >> depends how your system is configured. > > I tried and find that I must set the variable in .profile file, instead > of .bashrc, in order to let the IDEs started from my GUI to recognize > them after I logged out and in again. Yep, that would do it! Sometimes your GUI will be started from an interactive shell (or one that thinks it's interactive), in which case .bashrc will be processed, but in your case, .profile is the solution. ChrisA From __peter__ at web.de Wed Mar 23 04:51:34 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 Mar 2016 09:51:34 +0100 Subject: 0 equals False, was Re: (unknown) References: Message-ID: Nick Eubank wrote: > Hello All, > > > Found an odd behavior I'd never known about today, not sure if it's a bug > or known. Python 3.4.4 (anaconda). This is a feature. Old versions of Python did not have True and False, so they were added in a compatible way. > True, False, 0, 1 can all be used as dictionary keys. > > But Apparently True and 1 hash to the same item and False and 0 hash to > the same item, so they can easily overwrite (which I spent a while banging > my head over today). > > In other words: > > In[1]: > d = {True: 'a', False: 'b'} > d[0] = 'z' > d[False] > > Out[1]: > 'z' > > I understand that True and False are sub-types of ints, but it's not clear > to me why (i.e. certainly didn't feel intuitive) that they would be > treated the same as keys. > > Relatedly, if this is a desired behavior, any advice one how best to work > with dictionaries when one wants "True" and 1 to be different? I'm working > on a function that accepts arguments that may be "True" or 1 (meaning very > different things) and am seeking a pythonic solution... The pythonic solution is "don't do this". The == operator cannot discriminate between 0, 0.0, and False, or 1, 1.0, and True. True and False are singletons, so you can check identity with x is True or x is False A type check will also work: type(x) == bool isinstance(x, bool) # bool cannot be subclassed If you provide some context we may be able to come up with an alternative approach that fits your use case. From steve+comp.lang.python at pearwood.info Wed Mar 23 05:03:31 2016 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 23 Mar 2016 20:03:31 +1100 Subject: [Not actually OT] Trouble in node.js land Message-ID: <56f25be6$0$2805$c3e8da3$76491128@news.astraweb.com> This is not actually off-topic, as it has relevance to open source projects like Python: the importance of getting package management right, and not basing your development ecosystem on cowboys who might pull the rug out from under your feet at any time. Ironically, this also showcases what happens when you use a language with no batteries included, namely Javascript. One developer just broke most of the Node.js ecosystem by removing an eleven line package from npm (the node.js package manager, somewhat similar to Python's pip only even more critical): http://www.theregister.co.uk/2016/03/23/npm_left_pad_chaos/ This critical package is "left-pad". What does it do? It pads strings with spaces from the left. It's not just spaces though, it can pad with any character you like! Zeroes, commas, even hash signs! We truly live in an age of miracles. The removal of this package (along with about 250 others by the same author, but only left-pad appears to have been noticed) crippled Node.js development as suddenly thousands of deployed apps could no longer download their dependencies. The author removed his package in a fit of pique because he wasn't allowed to continue using a trademarked name. Rather than suck it up like a grown up and change the package name, he removed his entire collection of packages from npm and (temporarily) broke the entire Node.js ecosystem. https://medium.com/@azerbike/i-ve-just-liberated-my-modules-9045c06be67c Of course, moving his allegedly infringing package "kik" to github isn't going to fix the problem. It's still allegedly infringing. More discussion here: https://github.com/azer/left-pad/issues/4 https://news.ycombinator.com/item?id=11340510 https://www.reddit.com/r/programming/comments/4bjss2/an_11_line_npm_package_called_leftpad_with_only/ A colleague passed on this quote from an acquaintance of his: "i asked an npm dev at a talk once if they were going to make a stable version and they said javascript is not like operating systems and doesn't need stable versions" There's a lesson here for Python package management too. As pip becomes ever more popular and functional, there are certain people who believe that the whole "batteries included" philosophy of Python is outdated and unnecessary. Why have a standard library when you can just download the most recent version from PyPI using pip? The node.js experience shows how this can go badly wrong. For those curious, here's left-pad in all its glory: module.exports = leftpad; function leftpad (str, len, ch) { str = String(str); var i = -1; if (!ch && ch !== 0) ch = ' '; len = len - str.length; while (++i < len) { str = ch + str; } return str; } I leave a Python translation for the experts :-) -- Steve From __peter__ at web.de Wed Mar 23 05:10:54 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 Mar 2016 10:10:54 +0100 Subject: Suggestion: make sequence and map interfaces more similar References: Message-ID: Marco S. via Python-list wrote: > I noticed that the sequence types does not have these methods that the map > types has: get(), items(), keys(), values(). > It could seem useless to have them for sequences, but I think it will ease > the creation of functions and methods that allow you to input a generic > iterable as parameter, but needs to use one of these methods in case the > parameter is a map. > > In one word, it will facilitate duck typing. It will also break existing uses of duck typing. The first one I found: >>> class List(list): ... def items(self): ... return list(enumerate(self)) ... >>> from urllib.parse import urlencode >>> urlencode([("a", "b"), ("c", "d")]) 'a=b&c=d' >>> urlencode(List([("a", "b"), ("c", "d")])) '0=%28%27a%27%2C+%27b%27%29&1=%28%27c%27%2C+%27d%27%29' > For the same reason, I would suggest the introduction of a new map type, > vdict, a dict that by default iterates over values instead over keys. So a > vdict object "d" wiil have iter(d) == iter(d.values()), and should also > have a count() method, like sequence types. > > Indeed sequences are, in my humble opinion, a specialized case of maps, > when keys are numeric only, are always contiguous without gaps and start > from 0. This way we will have a simpler way to let people to use sequences > or maps indifferently, and let the code untouched. Can you provide a few examples where this has /practical/ advantages? Isn't allowing some_list.get("key") more likely to hide programming errors than to make code more generic in a useful way? From hongyi.zhao at gmail.com Wed Mar 23 05:33:55 2016 From: hongyi.zhao at gmail.com (Hongyi Zhao) Date: Wed, 23 Mar 2016 09:33:55 +0000 (UTC) Subject: Settig some environment variables from within python. Message-ID: Hi all, I want to submit a qsub job to my hpc cluster from within python. In this case, I must set some environment variables specific for this qsub job and then invoking a bash script from within python. What python code should be used for this job? Regards -- .: Hongyi Zhao [ hongyi.zhao AT gmail.com ] Free as in Freedom :. From hemla21 at gmail.com Wed Mar 23 06:06:56 2016 From: hemla21 at gmail.com (Heli) Date: Wed, 23 Mar 2016 03:06:56 -0700 (PDT) Subject: numpy arrays Message-ID: <3774dc9b-f9d3-462b-bbe4-41b8b2244db7@googlegroups.com> Hi, I have a 2D numpy array like this: [[1,2,3,4], [1,2,3,4], [1,2,3,4] [1,2,3,4]] Is there any fast way to convert this array to [[1,1,1,1], [2,2,2,2] [3,3,3,3] [4,4,4,4]] In general I would need to retrieve every nth element of the interior arrays in to single arrays. I know I can loop over and do this, but I have really big arrays and I need the fastest way to do this. Thanks for your help, From manolo at austrohungaro.com Wed Mar 23 06:26:48 2016 From: manolo at austrohungaro.com (Manolo =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 23 Mar 2016 11:26:48 +0100 Subject: numpy arrays In-Reply-To: <3774dc9b-f9d3-462b-bbe4-41b8b2244db7@googlegroups.com> References: <3774dc9b-f9d3-462b-bbe4-41b8b2244db7@googlegroups.com> Message-ID: <20160323102648.GA1780@beagle> On 03/23/16 at 03:06am, Heli wrote: > I have a 2D numpy array like this: > > [[1,2,3,4], > [1,2,3,4], > [1,2,3,4] > [1,2,3,4]] > > Is there any fast way to convert this array to > > [[1,1,1,1], > [2,2,2,2] > [3,3,3,3] > [4,4,4,4]] You don't mean just transposing your original array, as in original_array.T, right? > In general I would need to retrieve every nth element of the interior > arrays in to single arrays. I know I can loop over and do this, but I > have really big arrays and I need the fastest way to do this. I didn't really get this, so transposing is probably not what you need. Anyway, just in case! Manolo From steve at pearwood.info Wed Mar 23 06:32:24 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 23 Mar 2016 21:32:24 +1100 Subject: numpy arrays References: <3774dc9b-f9d3-462b-bbe4-41b8b2244db7@googlegroups.com> Message-ID: <56f270b9$0$1618$c3e8da3$5496439d@news.astraweb.com> On Wed, 23 Mar 2016 09:06 pm, Heli wrote: > Hi, > > I have a 2D numpy array like this: > > [[1,2,3,4], > [1,2,3,4], > [1,2,3,4] > [1,2,3,4]] > > Is there any fast way to convert this array to > > [[1,1,1,1], > [2,2,2,2] > [3,3,3,3] > [4,4,4,4]] Mathematically, this is called the "transpose" of the array, and you can do that in numpy: py> import numpy as np py> arr = np.array( ... [[1,2,3,4], ... [1,2,3,4], ... [1,2,3,4], ... [1,2,3,4]]) py> arr array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) py> arr.T array([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]) -- Steven From bc at freeuk.com Wed Mar 23 06:34:53 2016 From: bc at freeuk.com (BartC) Date: Wed, 23 Mar 2016 10:34:53 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 23/03/2016 06:09, Ben Finney wrote: > The problem is that Bart simultaneously is a beginner at Python, and > expresses astonishment that everyone shrugs when Bart's > dreadfully-written code performs so badly. My interests differ from most people here writing Python. For example, I'm interested in byte-code (any byte-code) and what can be done with it. Investigating how well it performs in 'extreme' cases means executing algorithms predominantly in byte-code, not measuring how well some library function (in some unspecified language) can cope with the algorithm. And doing it 'Pythonically' can lead to suggestions such as the following the other day: c, psource = psource[0], psource[1:] (where psource is a very long string), which even I could tell, from knowing what goes on behind the scenes, wasn't going to work well (duplicating the rest of the string roughly every other character). A couple of years ago I had a project which tried to use a universal syntax to express algorithms, and translating it into various languages. The following code was generated for Python. (/This/ is also quite a good way of learning a language, by figuring out how to implement a specific feature in one language, in another. Another way is to try and implement it...) 'N-Sieve' benchmark: # Python source output import sys import math import copy def nsieve(m): flags = ([1]*(m+1)) count = 0 for i in range(3,m+1): if flags[i]: count += 1 j = (i+i) while (j<=m): if flags[j]: flags[j] = 0 j = (j+i) sys.stdout.write(str("Primes up to ")) sys.stdout.write(str(m)) sys.stdout.write(str(": ")) sys.stdout.write(str(count)) sys.stdout.write("\n") return count def start(): nsieve(5120000) nsieve(2560000) nsieve(1280000) start() (The sys writes are used as it was easier than figuring out how to reliably control spacing and newlines using 'print'. The m+1's I think are there because the algorithm I used was 1-based). In the case of this project, the source syntax was intended as a wrapper around actual Python; it was not a language in its own right. (Although, these simple benchmarks could generate Python, Lua or Lisp from the exact same source. I know zilch about Lisp, except what I had to figure out to make this work, and which I promptly forgot again. But the resulting code ran perfectly!) But I'd be more interesting now in translating another actual language to Python. Now, the resulting Python is likely to be low-quality, with extra code needed to match the source semantics. Then performance could well be a factor not entirely offset by the novelty of watching Python flawlessly execute a program not written in Python. > Good faith is contradicted by asserting knowledge of Python, complaining > about how some deliberately non-idiomatic Python code is performing > poorly, dismissing suggestions for improvement ? specifically in the > context of someone who admittedly knows so little about Python. Someone could be interested in cars, mechanics and performance without wanting to know the most Pythonic way to get from Kings Cross to Heathrow. -- Bartc From rosuav at gmail.com Wed Mar 23 06:35:38 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 21:35:38 +1100 Subject: numpy arrays In-Reply-To: <3774dc9b-f9d3-462b-bbe4-41b8b2244db7@googlegroups.com> References: <3774dc9b-f9d3-462b-bbe4-41b8b2244db7@googlegroups.com> Message-ID: On Wed, Mar 23, 2016 at 9:06 PM, Heli wrote: > I have a 2D numpy array like this: > > [[1,2,3,4], > [1,2,3,4], > [1,2,3,4] > [1,2,3,4]] > > Is there any fast way to convert this array to > > [[1,1,1,1], > [2,2,2,2] > [3,3,3,3] > [4,4,4,4]] What you want is called *transposing* the array: http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html That should be a sufficiently fast operation. ChrisA From hemla21 at gmail.com Wed Mar 23 06:47:27 2016 From: hemla21 at gmail.com (Heli) Date: Wed, 23 Mar 2016 03:47:27 -0700 (PDT) Subject: numpy arrays In-Reply-To: <3774dc9b-f9d3-462b-bbe4-41b8b2244db7@googlegroups.com> References: <3774dc9b-f9d3-462b-bbe4-41b8b2244db7@googlegroups.com> Message-ID: <436d32cb-f6f8-4b9e-90f2-c7fa488e9222@googlegroups.com> On Wednesday, March 23, 2016 at 11:07:27 AM UTC+1, Heli wrote: > Hi, > > I have a 2D numpy array like this: > > [[1,2,3,4], > [1,2,3,4], > [1,2,3,4] > [1,2,3,4]] > > Is there any fast way to convert this array to > > [[1,1,1,1], > [2,2,2,2] > [3,3,3,3] > [4,4,4,4]] > > In general I would need to retrieve every nth element of the interior arrays in to single arrays. I know I can loop over and do this, but I have really big arrays and I need the fastest way to do this. > > Thanks for your help, Thanks a lot everybody, Transposing is exactly what I want. I just was not sure if that would work on internal arrays of a 2D array. Problem solved thanks everyone. From simon+python at bleah.co.uk Wed Mar 23 06:47:47 2016 From: simon+python at bleah.co.uk (Simon Ward) Date: Wed, 23 Mar 2016 10:47:47 +0000 Subject: numpy arrays In-Reply-To: <3774dc9b-f9d3-462b-bbe4-41b8b2244db7@googlegroups.com> References: <3774dc9b-f9d3-462b-bbe4-41b8b2244db7@googlegroups.com> Message-ID: <65cfffdf-c80d-4faf-b689-ab72ff192ffe@email.android.com> On 23 March 2016 10:06:56 GMT+00:00, Heli wrote: >Hi, > >I have a 2D numpy array like this: > >[[1,2,3,4], > [1,2,3,4], > [1,2,3,4] > [1,2,3,4]] > >Is there any fast way to convert this array to > >[[1,1,1,1], > [2,2,2,2] > [3,3,3,3] > [4,4,4,4]] Use the transpose() method: http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.ndarray.transpose.html Simon -- Sent from Kaiten Mail. Please excuse my brevity. From rosuav at gmail.com Wed Mar 23 06:48:54 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 21:48:54 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Mar 23, 2016 at 9:34 PM, BartC wrote: > ... which even I could tell, from knowing what goes on behind the scenes, > wasn't going to work well ... > ... >> Good faith is contradicted by asserting knowledge of Python, complaining >> about how some deliberately non-idiomatic Python code is performing >> poorly, dismissing suggestions for improvement ? specifically in the >> context of someone who admittedly knows so little about Python. > > > Someone could be interested in cars, mechanics and performance without > wanting to know the most Pythonic way to get from Kings Cross to Heathrow. But if I complain that the trek across four blocks of London cost me ninety minutes and my train ticket (which I then had to get replaced), you would blame it on me getting lost, rather than accepting my assertion that London's slow to get around. And if you said "hey, take a bus or a taxi next time", and I next time walked and got lost again, you would rightly call me a fool. And if I then had the audacity to say that London's streets are badly designed, because I looked at them and even without knowing what sort of traffic goes on them, I can tell that those are slow roads... you'd have very little respect for my statements about London. It wouldn't matter if I'm the world's greatest expert on hiking from Adelaide to Perth; it wouldn't matter how many nuances of Nullarbor sand I'm familiar with, nor how best to find drinking water there. I clearly know nothing about London, and my complaints about the city should be taken with a grain of salt, until such time as I put in the effort to get to know YOUR city YOUR way. (Events depicted in this work are entirely fictional and have no basis in reality. Really. Really truly. Anyway, I only got lost once.) ChrisA From mail at timgolden.me.uk Wed Mar 23 06:57:07 2016 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 23 Mar 2016 10:57:07 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56F27683.5030409@timgolden.me.uk> On 23/03/2016 10:48, Chris Angelico wrote: > On Wed, Mar 23, 2016 at 9:34 PM, BartC wrote: >> Someone could be interested in cars, mechanics and performance without >> wanting to know the most Pythonic way to get from Kings Cross to Heathrow. > > But if I complain that the trek across four blocks of London cost me > ninety minutes and my train ticket (which I then had to get replaced), > you would blame it on me getting lost, rather than accepting my > assertion that London's slow to get around. And if you said "hey, take > a bus or a taxi next time", and I next time walked and got lost again, > you would rightly call me a fool. And if I then had the audacity to > say that London's streets are badly designed, because I looked at them > and even without knowing what sort of traffic goes on them, I can tell > that those are slow roads... you'd have very little respect for my > statements about London. It wouldn't matter if I'm the world's > greatest expert on hiking from Adelaide to Perth; it wouldn't matter > how many nuances of Nullarbor sand I'm familiar with, nor how best to > find drinking water there. I clearly know nothing about London, and my > complaints about the city should be taken with a grain of salt, until > such time as I put in the effort to get to know YOUR city YOUR way. > > (Events depicted in this work are entirely fictional and have no basis > in reality. Really. Really truly. Anyway, I only got lost once.) Well if you tried to walk from King's Cross to Heathrow and only got lost once, I'm very impressed. I'm impressed if you did it at all! TJG From songofacandy at gmail.com Wed Mar 23 07:06:00 2016 From: songofacandy at gmail.com (INADA Naoki) Date: Wed, 23 Mar 2016 11:06:00 +0000 Subject: [Not actually OT] Trouble in node.js land In-Reply-To: <56f25be6$0$2805$c3e8da3$76491128@news.astraweb.com> References: <56f25be6$0$2805$c3e8da3$76491128@news.astraweb.com> Message-ID: > > > For those curious, here's left-pad in all its glory: > > module.exports = leftpad; > function leftpad (str, len, ch) { > str = String(str); > var i = -1; > if (!ch && ch !== 0) ch = ' '; > len = len - str.length; > while (++i < len) { > str = ch + str; > } > return str; > } > > I leave a Python translation for the experts :-) > > >>> s = "foo" >>> s.rjust(5, '@') '@@foo' From songofacandy at gmail.com Wed Mar 23 07:12:40 2016 From: songofacandy at gmail.com (INADA Naoki) Date: Wed, 23 Mar 2016 11:12:40 +0000 Subject: 0 equals False, was Re: (unknown) In-Reply-To: References: Message-ID: Tips: Since True == 1, sum() can count Trues. >>> def count_even(seq): ... return sum(i%2 == 0 for i in seq) >>> count_even(range(100)) 50 From steve at pearwood.info Wed Mar 23 07:26:44 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 23 Mar 2016 22:26:44 +1100 Subject: Suggestion: make sequence and map interfaces more similar References: Message-ID: <56f27d76$0$1600$c3e8da3$5496439d@news.astraweb.com> On Wed, 23 Mar 2016 06:54 am, Marco S. wrote: > I noticed that the sequence types does not have these methods that the map > types has: get(), items(), keys(), values(). > > It could seem useless to have them for sequences, That's putting it mildly. > but I think it will ease > the creation of functions and methods that allow you to input a generic > iterable as parameter, but needs to use one of these methods in case the > parameter is a map. Perhaps it would. But countering that is the disadvantage that you're adding methods to sequences that have no sensible meaning for a sequence. Strings and floats are quite different things, but occasionally it makes sense to write a function that accepts either a string or a float. Perhaps we could introduce methods to strings and floats to blur the difference, to "ease the creation of functions and methods that allow you to input a generic scalar (string, float, int) as parameter..."? Some of these methods would be easy: class float: def upper(self): return self Some a bit more work: def find(self, substring, start, end): s = str(self) return s.find(substring, start, end) but some perplex me. What would (27.25).expand_tabs() do? Of course this is silly. Even Perl and Javascript don't go this far in making floats and strings interchangeable. This is a good thing: if you're calling some_float.upper(), you've almost certainly made a programming error, and you don't want this nonsensical method call to silently succeed. So it is with sequences and mappings. They are *not* the same sort of thing, even though they have a few superficial similarities, and they shouldn't try to behave as the same thing. What should some_dict.append(None) do? The very concept is nonsense: dicts aren't *ordered sequences*, you can't append to a dict. Maybe you could give dicts a method *called* "append", but it wouldn't mean the same thing as list.append, and it probably wouldn't have the same signature: list.append(value) Appends value to the end of the list. dict.append(key, value) Adds a new key to the dict, with the given value. Same as dict[key] = value. Forcing these two completely different methods to have the same name doesn't do anything useful. That's like putting a door handle on your iPhone, in case some day you want to treat your iPhone as a door. > In one word, it will facilitate duck typing. I think you have misunderstood the purpose and meaning of duck-typing. Duck-typing is not about forcing unrelated, dissimilar types to have the same interface just in case you want to write a function that will accept either type. Duck-typing is about accepting anything which "quacks like a duck". If all you need is something which lays an egg, you shouldn't care whether it is a chicken or a goose or a duck. It doesn't mean that dogs and cats should have a "lay_egg" method, just in case somebody wants to accept a duck or a dog. > For the same reason, I would suggest the introduction of a new map type, > vdict, a dict that by default iterates over values instead over keys. So a > vdict object "d" wiil have iter(d) == iter(d.values()), and should also > have a count() method, like sequence types. I don't really see the point in this. What sort of function will expect to iterate over a mapping, but not care whether it is getting keys or values? Sure, there are generic functions that will iterate over *any iterable*, and you can pass dict.keys() or dict.values(), and both will work fine. That's exactly what duck-typing is about. But let's imagine this hypothetical function that will accept any mapping, and some mappings will iterate over keys and some mappings iterate over values. What would you do with it? def walk(the_dict): for obj in the_dict: print("Key =", obj) # That's wrong, it might be a value. value = the_dict[obj] # That's wrong too. the_dict[obj] = "processed" # Still wrong. There's nothing useful or interesting you can do with a mapping and something which might be a key, or might be a value, but you don't know which. You can treat them in isolation, as if they had nothing to do with a dict, and that's about it. But in that case, why insist on a dict? walk(the_dict.keys()) walk(the_dict.values()) walk(the_list) walk(the_iterator) > Indeed sequences are, in my humble opinion, a specialized case of maps, > when keys are numeric only, are always contiguous without gaps and start > from 0. That's a very superficial similarity: a list ['a', 'b', 'x', 'y'] is something like a mapping {0: 'a', 1: 'b', 2: 'x', 3: 'y'}. Seems logical, since in both cases we write collection[2] and get 'x' back. But think about it a bit more, and you will see that the behaviour is in fact *very different*. For example: the_list = ['a', 'b', 'x', 'y'] # the_list is equivalent to {0: 'a', 1: 'b', 2: 'x', 3: 'y'} the_list.insert(0, 'z') # the_list is now equivalent to {0: 'z', 1: 'a', 2: 'b', 3: 'x', 4: 'y'} Every existing "key:value" pair has changed! What sort of mapping operates like that? del the_list[2] # the_list is now equivalent to {0: 'z', 1: 'a', 2: 'x', 3: 'y'} I've said to delete the "key" 2, but there it still is. "Key" 2 still exists, it just has a different value! And it is "key" 4 which has been deleted! But not the *value* attached to "key" 4, that's been moved to 3! What sort of crazy mapping behaves like this? The answer is, of course, *no* sort of mapping. Sequences are not mappings. The only reason we think of them as kinda-sorta like mappings is because of a superficial similarity between key:value and index:item. That similarity is real, but virtually everything else about mappings and sequences is different. > This way we will have a simpler way to let people to use sequences > or maps indifferently, and let the code untouched. Have you ever actually wanted to use sequences or maps indifferently? To do what? The only case I've ever seen of that is the dict constructor, and dict.update, which will accept either a mapping or a sequence of (key, value) pairs. -- Steven From rosuav at gmail.com Wed Mar 23 07:28:03 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 22:28:03 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <56F27683.5030409@timgolden.me.uk> References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56F27683.5030409@timgolden.me.uk> Message-ID: On Wed, Mar 23, 2016 at 9:57 PM, Tim Golden wrote: > On 23/03/2016 10:48, Chris Angelico wrote: >> On Wed, Mar 23, 2016 at 9:34 PM, BartC wrote: >>> Someone could be interested in cars, mechanics and performance without >>> wanting to know the most Pythonic way to get from Kings Cross to Heathrow. >> >> But if I complain that the trek across four blocks of London cost me >> ninety minutes and my train ticket (which I then had to get replaced), >> you would blame it on me getting lost, rather than accepting my >> assertion that London's slow to get around. And if you said "hey, take >> a bus or a taxi next time", and I next time walked and got lost again, >> you would rightly call me a fool. And if I then had the audacity to >> say that London's streets are badly designed, because I looked at them >> and even without knowing what sort of traffic goes on them, I can tell >> that those are slow roads... you'd have very little respect for my >> statements about London. It wouldn't matter if I'm the world's >> greatest expert on hiking from Adelaide to Perth; it wouldn't matter >> how many nuances of Nullarbor sand I'm familiar with, nor how best to >> find drinking water there. I clearly know nothing about London, and my >> complaints about the city should be taken with a grain of salt, until >> such time as I put in the effort to get to know YOUR city YOUR way. >> >> (Events depicted in this work are entirely fictional and have no basis >> in reality. Really. Really truly. Anyway, I only got lost once.) > > Well if you tried to walk from King's Cross to Heathrow and only got > lost once, I'm very impressed. I'm impressed if you did it at all! I was walking something like four blocks, from one station to another (we flew in to one of the airports and needed to take a train to Manchester, and that involved trains on different lines). It was a short trip and would have been an easy one, had I consulted a map beforehand instead of thinking "Oh, it's just straight there and then there and there, no problem!". Obviously London's fault for being unintuitive. And for having railway lines that don't meet at the same stations (well, maybe that's a legit complaint, but the city has to worry about backward compatibility too). ChrisA From python at lucidity.plus.com Wed Mar 23 07:56:27 2016 From: python at lucidity.plus.com (Erik) Date: Wed, 23 Mar 2016 11:56:27 +0000 Subject: No subject In-Reply-To: References: Message-ID: <56F2846B.2010805@lucidity.plus.com> Hi Nick, On 23/03/16 03:17, Nick Eubank wrote: > In other words: > > In[1]: > d = {True: 'a', False: 'b'} > d[0] = 'z' > d[False] > > Out[1]: > 'z' [snip] > Relatedly, if this is a desired behavior, any advice one how best to work > with dictionaries when one wants "True" and 1 to be different? See the accepted answer here: http://stackoverflow.com/questions/3387691/python-how-to-perfectly-override-a-dict If you use the class that the answer suggests and then define a subclass: """ class MyTransformedDict(TransformedDict): __reverse_transform__ = { "__True__": True, "__False__": False, } def __keytransform__(self, key): if key is True: return "__True__" if key is False: return "__False__" return key def __iter__(self): return (self.__reverse_transform__.get(k, k) for k in super(MyTransformedDict, self).__iter__()) def __contains__(self, key): return self.__keytransform__(key) in self.store """ Then as long as you wrap such dictionaries in a "MyTransformedDict()" (choose a better name!), it will do what: """ d = MyTransformedDict({True: 'a', False: 'b'}) d[0] = 'z' d[False] """ Note that in your case, I've added the reverse transformation from the magic tokens so that iter(), .iterkeys() and .iteritems()) return the original True and False keys. I've also added __contains__, but that should be in the "TransformedDict()" superclass (I didn't want to reproduce the whole of that here). There are things missing (such as a dict-like repr()) or not done optimally there, but it might be a good start. This works on Python 2 and 3. E. From steve at pearwood.info Wed Mar 23 08:17:35 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 23 Mar 2016 23:17:35 +1100 Subject: os.rename on Windows Message-ID: <56f28962$0$1612$c3e8da3$5496439d@news.astraweb.com> Any Windows users here? According to the documentation, os.rename(original, new) will fail if new already exists. Would somebody be kind enough to tell me what OSError is raised? In particular: # Untested. import os open('a123.junk', 'w') open('b123.junk', 'w') try: os.rename('a123.junk', 'b123.junk') except OSError as e: print(e.winerror) # Windows only print(e.errno) print(repr(e)) os.unlink('a123.junk') os.unlink('b123.junk') I'd test it myself, except I don't have access to Windows with Python. Thanks in advance. -- Steven From rosuav at gmail.com Wed Mar 23 08:27:41 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 23 Mar 2016 23:27:41 +1100 Subject: os.rename on Windows In-Reply-To: <56f28962$0$1612$c3e8da3$5496439d@news.astraweb.com> References: <56f28962$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Mar 23, 2016 at 11:17 PM, Steven D'Aprano wrote: > import os > open('a123.junk', 'w') > open('b123.junk', 'w') > try: > os.rename('a123.junk', 'b123.junk') > except OSError as e: > print(e.winerror) # Windows only > print(e.errno) > print(repr(e)) > > os.unlink('a123.junk') > os.unlink('b123.junk') > 32-bit Python on 64-bit Windows 7 in a VirtualBox VM under Debian Testing. Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (In tel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> open('a123.junk', 'w') <_io.TextIOWrapper name='a123.junk' mode='w' encoding='cp1252'> >>> open('b123.junk', 'w') <_io.TextIOWrapper name='b123.junk' mode='w' encoding='cp1252'> >>> try: ... os.rename('a123.junk', 'b123.junk') ... except OSError as e: ... print(e.winerror) # Windows only ... print(e.errno) ... print(repr(e)) ... 183 17 FileExistsError(17, 'Cannot create a file when that file already exists') >>> os.unlink('a123.junk') >>> os.unlink('b123.junk') Traceback (most recent call last): File "", line 1, in PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'b123.junk' >>> The last error is because _ is retaining the open file, so it hasn't been closed. Entering any non-None expression allows the unlink. ChrisA From random832 at fastmail.com Wed Mar 23 08:28:21 2016 From: random832 at fastmail.com (Random832) Date: Wed, 23 Mar 2016 08:28:21 -0400 Subject: os.rename on Windows In-Reply-To: <56f28962$0$1612$c3e8da3$5496439d@news.astraweb.com> References: <56f28962$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1458736101.3194317.557444826.1DD94744@webmail.messagingengine.com> On Wed, Mar 23, 2016, at 08:17, Steven D'Aprano wrote: > Any Windows users here? > > print(e.winerror) # Windows only > print(e.errno) > print(repr(e)) 183 17 FileExistsError(17, 'Cannot create a file when that file already exists') Python 3.5.1. From steve at pearwood.info Wed Mar 23 08:30:16 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 23 Mar 2016 23:30:16 +1100 Subject: os.rename on Windows References: <56f28962$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f28c5a$0$1616$c3e8da3$5496439d@news.astraweb.com> On Wed, 23 Mar 2016 11:28 pm, Random832 wrote: > On Wed, Mar 23, 2016, at 08:17, Steven D'Aprano wrote: >> Any Windows users here? >> >> print(e.winerror) # Windows only >> print(e.errno) >> print(repr(e)) > > 183 > 17 > FileExistsError(17, 'Cannot create a file when that file already > exists') > > Python 3.5.1. Great! Thanks, and to Chris too (and anyone else who answers). -- Steven From nicoe at altern.org Wed Mar 23 08:31:26 2016 From: nicoe at altern.org (Nicolas =?utf-8?Q?=C3=89vrard?=) Date: Wed, 23 Mar 2016 13:31:26 +0100 Subject: E-commerce system in Python In-Reply-To: <8c9f662d-7faa-4bb5-9670-13899f6a8762@googlegroups.com> References: <8c9f662d-7faa-4bb5-9670-13899f6a8762@googlegroups.com> Message-ID: <20160323123126.GG4998@localhost.localdomain> * Arshpreet Singh [2016-03-18 05:25 +0100]: >I am looking for an E-commerce system in python to sell things things >online, which can also be responsive for Android and IOS. > >A quick Google search brought me http://getsaleor.com/ it uses >Django, Is there any available one using Flask or newly born asyncio >based framework? You could build your own e-commerce system using Tryton and flask-tryton. http://www.tryton.org/ https://pypi.python.org/pypi/flask_tryton We're in the process of adding basic cart functionalities to the ERP. It will probably be included in the near future. -- Nicolas ?vrard - B2CK SPRL E-mail/Jabber: nicolas.evrard at b2ck.com Tel: +32 472 54 46 59 Website: http://www.b2ck.com/ From random832 at fastmail.com Wed Mar 23 09:33:41 2016 From: random832 at fastmail.com (Random832) Date: Wed, 23 Mar 2016 09:33:41 -0400 Subject: [Not actually OT] Trouble in node.js land In-Reply-To: <56f25be6$0$2805$c3e8da3$76491128@news.astraweb.com> References: <56f25be6$0$2805$c3e8da3$76491128@news.astraweb.com> Message-ID: <1458740021.3208883.557500010.1EBFC599@webmail.messagingengine.com> On Wed, Mar 23, 2016, at 05:03, Steven D'Aprano wrote: > https://medium.com/@azerbike/i-ve-just-liberated-my-modules-9045c06be67c > > Of course, moving his allegedly infringing package "kik" to github isn't > going to fix the problem. It's still allegedly infringing. I think the issue, and it is a reasonable one, is that this was not determined in a court of law. It's not actually clear to me that it's infringing or not (yes, they're both computer programs, but they do very different things, so it's not clear if they are or that they ought to be the "same area"), and it's arguably something that Kik Interactive Inc. should have had to actually sue him for rather than demanding a third party to arbitrarily mess with his stuff. And there's also the fact that corporations apparently have absolutely no concept of how to properly communicate with someone to ask them to change something or stop doing something. From bc at freeuk.com Wed Mar 23 09:41:46 2016 From: bc at freeuk.com (BartC) Date: Wed, 23 Mar 2016 13:41:46 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 23/03/2016 10:48, Chris Angelico wrote: > On Wed, Mar 23, 2016 at 9:34 PM, BartC wrote: >> Someone could be interested in cars, mechanics and performance without >> wanting to know the most Pythonic way to get from Kings Cross to Heathrow. > > But if I complain that the trek across four blocks of London cost me > ninety minutes and my train ticket (which I then had to get replaced), > you would blame it on me getting lost, rather than accepting my > assertion that London's slow to get around. And if you said "hey, take > a bus or a taxi next time", and I next time walked and got lost again, > you would rightly call me a fool. And if I then had the audacity to > say that London's streets are badly designed, because I looked at them > and even without knowing what sort of traffic goes on them, I can tell > that those are slow roads... you'd have very little respect for my > statements about London. It wouldn't matter if I'm the world's > greatest expert on hiking from Adelaide to Perth; it wouldn't matter > how many nuances of Nullarbor sand I'm familiar with, nor how best to > find drinking water there. I clearly know nothing about London, and my > complaints about the city should be taken with a grain of salt, until > such time as I put in the effort to get to know YOUR city YOUR way. To extend this analogy better, executing byte-code to directly perform a task itself might be equivalent to travelling on foot, while everyone is suggesting taking the bus, tube or taxi. But when you are on foot, it might be worth looking at what's slowing you down, or indeed at whether you are actually being slowed down at all. With walking it's easy because 3mph is typical, you'll know when something is obviously wrong (dragging or carrying a huge amount of baggage with you for example). Running byte-code is not so obvious. Interestingly, the typical difference between my byte-code and CPython's, is roughly the same as between (my) cycling and walking. With odd spots where CPython is quicker (which I'm investigating...). While PyPy can sometimes beat both of those, on a straight downhill section, but I suspect it cheats there a little by being motor-assisted. (FWIW, in central London usually I walk or cycle. I wouldn't walk from King's Cross to LHR, nearly 20 miles, unless I had nothing better to do, or there was no alternative.) -- Bartc From nobody at nowhere.invalid Wed Mar 23 09:45:29 2016 From: nobody at nowhere.invalid (Nobody) Date: Wed, 23 Mar 2016 13:45:29 +0000 Subject: numpy arrays References: <3774dc9b-f9d3-462b-bbe4-41b8b2244db7@googlegroups.com> Message-ID: > What you want is called *transposing* the array: > > http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html > > That should be a sufficiently fast operation. Transposing itself is fast, as it just swaps the strides and dimensions without touching the data (i.e. it returns a new view of the original array), but subsequent operations may be slower as the data is no longer contiguous (i.e. iterating over the flattened array in order won't result in sequential memory access). If that's an issue, you can use numpy.ascontiguousarray() to make a contiguous copy of the data. From sjmsoft at gmail.com Wed Mar 23 10:03:56 2016 From: sjmsoft at gmail.com (sjmsoft at gmail.com) Date: Wed, 23 Mar 2016 07:03:56 -0700 (PDT) Subject: os.rename on Windows In-Reply-To: <56f28962$0$1612$c3e8da3$5496439d@news.astraweb.com> References: <56f28962$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: Python 2.7.11 on Windows 7 Enterprise (64-bit machine, 32-bit Python) and two Windows Server 2012 R2 (64-bit machines, both 32-bit and 64-bit Pythons): 183 17 WindowsError(183, 'Cannot create a file when that file already exists') HTH, Steve From eryksun at gmail.com Wed Mar 23 10:16:23 2016 From: eryksun at gmail.com (eryk sun) Date: Wed, 23 Mar 2016 09:16:23 -0500 Subject: os.rename on Windows In-Reply-To: <56f28962$0$1612$c3e8da3$5496439d@news.astraweb.com> References: <56f28962$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Mar 23, 2016 at 7:17 AM, Steven D'Aprano wrote: > > According to the documentation, os.rename(original, new) will fail if new > already exists. In 3.3+ you can use os.replace. For POSIX systems it's functionally the same as os.rename. pyosreplace [1] backports os.replace for 2.6, 2.7 and 3.2. Ignore the comment on the PyPI page that MoveFileEx isn't guaranteed to be atomic. It won't do a CopyFile because os.replace doesn't use the flag MOVEFILE_COPY_ALLOWED. For a cross-volume move, which can't be executed atomically in a single NtSetInformationFile system call, os.replace fails with the Windows error code ERROR_NOT_SAME_DEVICE (0x0011 or 17). [1]: https://pypi.python.org/pypi/pyosreplace > Would somebody be kind enough to tell me what OSError is raised? If the file already exists, os.rename fails with winerror set to ERROR_ALREADY_EXISTS (0x00B7 or 183). If you need to support 2.x, you should handle WindowsError, which is a subclass of OSError that has the "winerror" attribute. In 3.3+ OSError itself has the "winerror" attribute, and in this case WindowsError is just an alias for OSError. For 3.3+ you can also handle the cross-platform FileExistsError subclass of OSError. From steve at pearwood.info Wed Mar 23 10:52:10 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 24 Mar 2016 01:52:10 +1100 Subject: [Not actually OT] Trouble in node.js land References: <56f25be6$0$2805$c3e8da3$76491128@news.astraweb.com> Message-ID: <56f2ad9c$0$1607$c3e8da3$5496439d@news.astraweb.com> On Thu, 24 Mar 2016 12:33 am, Random832 wrote: > On Wed, Mar 23, 2016, at 05:03, Steven D'Aprano wrote: >> https://medium.com/@azerbike/i-ve-just-liberated-my-modules-9045c06be67c >> >> Of course, moving his allegedly infringing package "kik" to github isn't >> going to fix the problem. It's still allegedly infringing. > > I think the issue, and it is a reasonable one, is that this was not > determined in a court of law. It's not actually clear to me that it's > infringing or not (yes, they're both computer programs, but they do very > different things, so it's not clear if they are or that they ought to be > the "same area"), and it's arguably something that Kik Interactive Inc. > should have had to actually sue him for rather than demanding a third > party to arbitrarily mess with his stuff. > > And there's also the fact that corporations apparently have absolutely > no concept of how to properly communicate with someone to ask them to > change something or stop doing something. I don't think this is the case at all. If the author of the package had tried to negotiate, and been rebuffed, he surely would have said so. "Look, I tried to be reasonable, but they wouldn't be reasonable, so I had no choice!". But that's not what his own account of the story shows. His account shows clearly: - He didn't bother to check to see whether the name was in use when he picked it. - The lawyers were polite but firm. - He apparently made no attempt to negotiate, just told them no. Twice. - His own account didn't dispute the possibility of confusion between two software packages with the same name. He could have argued "My software in a command-line tool for creating Javascript projects; yours is a chat client. There is no possibility of confusion between the two." But he gives no indication that he did this. It probably wouldn't do him much good if he made that argument, since the courts tend to use the "Moron in a hurry" test. If a stupid person who is not paying attention could be confused by the reuse of the name, then it shouldn't be allowed. They're both software, right? It's not like one was software and the other was a brand of chocolate biscuit. But, judging from his own story, it doesn't appear he even made that argument. Instead, it seems that his argument was simple: "No. Don't want to." So the lawyers did the right thing: instead of suing him, they approached the people hosting the software, and got them to take it down. There is a prima facie evidence of trademark infringement, and the alleged infringer has made no attempt to deny infringement, defend himself or rename the package, even when asked. So they took down *one* package. At which point, the author spat the dummy and took down 250 or so packages, including the one which brought Node.js to its knees. It's hard to feel sympathy for the guy when *his own account* of what took place makes him out to be a totally self-centred dick with poor impulse control. But now this is off-topic. There are difficult people in all programming language communities, and it could have been *any* package that was removed suddenly with no warning. What's more interesting is the difference between language communities which can easily weather such troubles or those that can't. -- Steven From g.starck at gmail.com Wed Mar 23 11:03:32 2016 From: g.starck at gmail.com (gst) Date: Wed, 23 Mar 2016 08:03:32 -0700 (PDT) Subject: 0 equals False, was Re: (unknown) In-Reply-To: References: Message-ID: Le mercredi 23 mars 2016 04:52:02 UTC-4, Peter Otten a ?crit?: > Nick Eubank wrote: > > > Hello All, > > > > > > Found an odd behavior I'd never known about today, not sure if it's a bug > > or known. Python 3.4.4 (anaconda). > > True, False, 0, 1 can all be used as dictionary keys. > > > > But Apparently True and 1 hash to the same item and False and 0 hash to > > the same item, so they can easily overwrite (which I spent a while banging > > my head over today). > > > > In other words: > > > > In[1]: > > d = {True: 'a', False: 'b'} > > d[0] = 'z' > > d[False] > > > > Out[1]: > > 'z' > > > > I understand that True and False are sub-types of ints, but it's not clear > > to me why (i.e. certainly didn't feel intuitive) that they would be > > treated the same as keys. > > > > Relatedly, if this is a desired behavior, any advice one how best to work > > with dictionaries when one wants "True" and 1 to be different? I'm working > > on a function that accepts arguments that may be "True" or 1 (meaning very > > different things) and am seeking a pythonic solution... I would include the type in the dictionary key: d = {} x = True d[(type(x), x)] = 42 x = 1 d[(type(x), x)] = "foo" From random832 at fastmail.com Wed Mar 23 11:26:02 2016 From: random832 at fastmail.com (Random832) Date: Wed, 23 Mar 2016 11:26:02 -0400 Subject: [Not actually OT] Trouble in node.js land In-Reply-To: <56f2ad9c$0$1607$c3e8da3$5496439d@news.astraweb.com> References: <56f25be6$0$2805$c3e8da3$76491128@news.astraweb.com> <56f2ad9c$0$1607$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1458746762.3237061.557619626.27F4A893@webmail.messagingengine.com> On Wed, Mar 23, 2016, at 10:52, Steven D'Aprano wrote: > - He didn't bother to check to see whether the name was in use when he > picked it. Someone not making a commercial product shouldn't have to worry about a name collision with something they've never heard of. > - The lawyers were polite but firm. > > - He apparently made no attempt to negotiate, just told them no. Twice. I'd missed the part where the lawyers contacted him directly. The next step should have been a lawsuit, not to do an end run around the law by trying to convince someone else to enact extralegal enforcement on their behalf. > - His own account didn't dispute the possibility of confusion between two > software packages with the same name. He could have argued "My software > in > a command-line tool for creating Javascript projects; yours is a chat > client. There is no possibility of confusion between the two." But he > gives > no indication that he did this. > > It probably wouldn't do him much good if he made that argument, since the > courts tend to use the "Moron in a hurry" test. If a stupid person who is > not paying attention could be confused by the reuse of the name, then it > shouldn't be allowed. They're both software, right? It's not like one was > software and the other was a brand of chocolate biscuit. But, judging > from > his own story, it doesn't appear he even made that argument. A) His software is a command line tool, how's someone looking for a phone app going to find it in the first place? B) His software costs no money, so no harm has been done even if someone looking for the phone app finds it and "buys" it by mistake. Even if the interpretation of the law used by the court _is_ that phone apps and command line tools are the same "area", this is, if true, a failure of the system that people should fight against rather than just accept. From ned at nedbatchelder.com Wed Mar 23 11:40:14 2016 From: ned at nedbatchelder.com (Ned Batchelder) Date: Wed, 23 Mar 2016 08:40:14 -0700 (PDT) Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4430157c-1629-4deb-9c36-f34e18f851ff@googlegroups.com> On Wednesday, March 23, 2016 at 6:35:12 AM UTC-4, BartC wrote: > On 23/03/2016 06:09, Ben Finney wrote: > > > The problem is that Bart simultaneously is a beginner at Python, and > > expresses astonishment that everyone shrugs when Bart's > > dreadfully-written code performs so badly. > > My interests differ from most people here writing Python. > > For example, I'm interested in byte-code (any byte-code) and what can be > done with it. Investigating how well it performs in 'extreme' cases > means executing algorithms predominantly in byte-code, not measuring how > well some library function (in some unspecified language) can cope with > the algorithm. Thanks for clarifying your focus. As you explore this topic, keep in mind then that you are only looking at part of Python. When you find yourself wondering why the bytecode is a certain way, the answer might be, "Because wherever this bytecode is run, the standard library is available, and this problem is better solved with a thing in the standard library." This doesn't mean your investigations are invalid, but they are only part of the story. When it seems to you like Python has made a strange choice, you may have to broaden your perspective to understand it. --Ned. From best_lay at yahoo.com Wed Mar 23 11:40:19 2016 From: best_lay at yahoo.com (Wildman) Date: Wed, 23 Mar 2016 10:40:19 -0500 Subject: Key Binding Problem References: Message-ID: On Wed, 23 Mar 2016 02:47:47 -0400, Terry Reedy wrote: > On 3/23/2016 12:28 AM, Wildman via Python-list wrote: >> On Wed, 23 Mar 2016 03:02:51 +0000, MRAB wrote: >> >>> On 2016-03-23 02:46, Wildman via Python-list wrote: >>>> My question is how do I coax bind into executing the >>>> button procedures? Or is there a way to generate the >>>> button click event from the binding? >>>> >>> It won't let you bind to a function called "load_image" because there >>> isn't a function called "load_image"! >>> >>> The "Window" class, however, does have a method with that name. >>> >>> Try binding the keys in Window.__init__ or Window.init_window: >>> >>> def init_window(self): >>> ... >>> root.bind("", self.load_image) >> >> Here is what I tried: >> >> class Window(tk.Frame): >> >> def __init__(self, master = None): >> tk.Frame.__init__(self,master) >> self.master = master >> root.bind("l", self.load_image) >> >> I get this error and it doesn't make any sense to me: >> >> Exception in Tkinter callback >> Traceback (most recent call last): >> File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1535, in __call__ >> return self.func(*args) >> TypeError: load_image() takes exactly 1 argument (2 given) > > Event handlers must have one parameter (other than 'self' for methods), > the event, as that is what they will be passed. You defined load_image > like this. > > def load_image(self): > # load image file > > It should be this > > def load_image(self, event): > # load image file > > You are free to ignore the event object and some people then name the > parameter '_' (or dummy) to signify that it will be ignored. > > def load_image(self, _): > # load image file > > You must pass the bound method, as you did, and not the function itself > (which has two parameters). Thank you very much. I have seen sample code that used 'event' in the definition but without any explanation as to why and without actually using it. Since my code seemed to run OK without it, at least until now, I didn't give it much thought. My mistake. I am new to python so understanding comes a little slower for me. And I am not a professional programmer. I enjoy it as a hobby so my experience is more limited where the advanced topics are concerned. Thanks to the knowledgeable people here I am gaining insight as I go. Thanks again! -- GNU/Linux user #557453 May the Source be with you. From best_lay at yahoo.com Wed Mar 23 11:58:09 2016 From: best_lay at yahoo.com (Wildman) Date: Wed, 23 Mar 2016 10:58:09 -0500 Subject: Key Binding Problem References: Message-ID: On Wed, 23 Mar 2016 02:47:47 -0400, Terry Reedy wrote: > def load_image(self, _): > # load image file > > You must pass the bound method, as you did, and not the function itself > (which has two parameters). I meant to ask a followup question in my previous post but it slipped my mind. What is the best thing to do... Define all procedures this way, (self. event)? Define all event handlers this way? Define only the event handlers that will be called from elsewhere in the code, as in this case? -- GNU/Linux user #557453 More gun laws will reduce gun violence just like Obamacare reduced insurance rates. From breamoreboy at yahoo.co.uk Wed Mar 23 12:08:35 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 23 Mar 2016 16:08:35 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 23/03/2016 10:34, BartC wrote: > On 23/03/2016 06:09, Ben Finney wrote: > >> The problem is that Bart simultaneously is a beginner at Python, and >> expresses astonishment that everyone shrugs when Bart's >> dreadfully-written code performs so badly. > > My interests differ from most people here writing Python. > > For example, I'm interested in byte-code (any byte-code) and what can be > done with it. Investigating how well it performs in 'extreme' cases > means executing algorithms predominantly in byte-code, not measuring how > well some library function (in some unspecified language) can cope with > the algorithm. > > And doing it 'Pythonically' can lead to suggestions such as the > following the other day: > > c, psource = psource[0], psource[1:] > > (where psource is a very long string), which even I could tell, from > knowing what goes on behind the scenes, wasn't going to work well > (duplicating the rest of the string roughly every other character). > It would work perfectly. How would it duplicate the rest of the string roughly every other character? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at yahoo.co.uk Wed Mar 23 12:09:15 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 23 Mar 2016 16:09:15 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <85h9fxene8.fsf@benfinney.id.au> References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <85h9fxene8.fsf@benfinney.id.au> Message-ID: On 23/03/2016 06:09, Ben Finney wrote: > Steven D'Aprano writes: > >> On Mon, 21 Mar 2016 06:47 pm, Ben Finney wrote: >> >>> Bart can show good faith by *learning* idiomatic Python, with the >>> humility of a beginner. And also by refraining from rhetoric about >>> how bad Python's performance is, until he gains experience to make >>> those claims. >> >> "Humility of a beginner"... what a strange phrase to use about >> somebody who has been programming for decades. > > What a strange reading of what I wrote. Clearly I'm referring to the > fact Bart is a beginner in Python. > > To show good faith in learning Python ? if indeed that is what Bart > wants, which I'm not convinced of given how much he prefers to talk > about a different private programming language instead ? then he should > be taking advantage of the teaching resources that have been offered > numerous times. > >> What exactly is the problem here? Is it that Bart hasn't earned the >> right to say what we all know, that Python is slow, because he's an >> outsider? > > The problem is that Bart simultaneously is a beginner at Python, and > expresses astonishment that everyone shrugs when Bart's > dreadfully-written code performs so badly. > > Good faith is contradicted by asserting knowledge of Python, complaining > about how some deliberately non-idiomatic Python code is performing > poorly, dismissing suggestions for improvement ? specifically in the > context of someone who admittedly knows so little about Python. > +1 -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From random832 at fastmail.com Wed Mar 23 12:24:28 2016 From: random832 at fastmail.com (Random832) Date: Wed, 23 Mar 2016 12:24:28 -0400 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1458750268.3251250.557690202.04DB2EB3@webmail.messagingengine.com> On Wed, Mar 23, 2016, at 12:08, Mark Lawrence wrote: > > And doing it 'Pythonically' can lead to suggestions such as the > > following the other day: > > > > c, psource = psource[0], psource[1:] > > > > (where psource is a very long string), which even I could tell, from > > knowing what goes on behind the scenes, wasn't going to work well > > (duplicating the rest of the string roughly every other character). > > > > It would work perfectly. How would it duplicate the rest of the string > roughly every other character? Er, I think he's suggesting that this would be in an inner loop (something like while psource: c, psource = psource[0], psource[1:]). What I'm not sure of is why he thinks this is pythonic. From louisanderson360 at hotmail.com Wed Mar 23 13:31:07 2016 From: louisanderson360 at hotmail.com (louis anderson) Date: Wed, 23 Mar 2016 17:31:07 +0000 Subject: Not downloading Message-ID: Dear Python, After a workshop in my school today regarding python, i have downloaded it on my laptop however when i go to launch it, it either tells me to modify python, repair python or uninstall python. It will not let me go onto python at all. I do not know what is going on and i hope yourselves can help me. Thankyou From tjreedy at udel.edu Wed Mar 23 13:46:38 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 23 Mar 2016 13:46:38 -0400 Subject: Settig some environment variables from within python. In-Reply-To: References: Message-ID: On 3/23/2016 5:33 AM, Hongyi Zhao wrote: > Hi all, > > I want to submit a qsub job to my hpc cluster from within python. In > this case, I must set some environment variables specific for this qsub > job and then invoking a bash script from within python. > > What python code should be used for this job? The os module. -- Terry Jan Reedy From tjreedy at udel.edu Wed Mar 23 14:00:48 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 23 Mar 2016 14:00:48 -0400 Subject: 0 equals False, was Re: (unknown) In-Reply-To: References: Message-ID: On 3/23/2016 4:51 AM, Peter Otten wrote: > The pythonic solution is "don't do this". The == operator cannot > discriminate between 0, 0.0, and False, and 0j and Fraction(0, 1) and Decimal(0) > or 1, 1.0, and True and 1+0j, Fraction(1, 1) and Decimal(1) Sets and dicts are based both based on (transitive) equality. -- Terry Jan Reedy From tjreedy at udel.edu Wed Mar 23 14:08:02 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 23 Mar 2016 14:08:02 -0400 Subject: [Not actually OT] Trouble in node.js land In-Reply-To: <56f25be6$0$2805$c3e8da3$76491128@news.astraweb.com> References: <56f25be6$0$2805$c3e8da3$76491128@news.astraweb.com> Message-ID: On 3/23/2016 5:03 AM, Steven D'Aprano wrote: > One developer just broke most of the Node.js ecosystem by removing an eleven > line package from npm (the node.js package manager, somewhat similar to > Python's pip only even more critical): Does PyPI actually delete packages, as opposed to making them harder to find? -- Terry Jan Reedy From ethan at stoneleaf.us Wed Mar 23 14:23:00 2016 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 23 Mar 2016 11:23:00 -0700 Subject: [Not actually OT] Trouble in node.js land In-Reply-To: References: <56f25be6$0$2805$c3e8da3$76491128@news.astraweb.com> Message-ID: <56F2DF04.7060108@stoneleaf.us> On 03/23/2016 11:08 AM, Terry Reedy wrote: > On 3/23/2016 5:03 AM, Steven D'Aprano wrote: > >> One developer just broke most of the Node.js ecosystem by removing an >> eleven >> line package from npm (the node.js package manager, somewhat similar to >> Python's pip only even more critical): > > Does PyPI actually delete packages, as opposed to making them harder to > find? I don't know the exact answer, but I do know there is a big warning label around the delete button: Do NOT use this button. There is no undo. -- ~Ethan~ From ethan at stoneleaf.us Wed Mar 23 14:26:46 2016 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 23 Mar 2016 11:26:46 -0700 Subject: No subject In-Reply-To: References: Message-ID: <56F2DFE6.7040006@stoneleaf.us> On 03/22/2016 08:17 PM, Nick Eubank wrote: > Relatedly, if this is a desired behavior, any advice one how best to work > with dictionaries when one wants "True" and 1 to be different? I'm working > on a function that accepts arguments that may be "True" or 1 (meaning very > different things) and am seeking a pythonic solution... If your keys are only numeric and True/False, you can check for and mutate True/False into strings "True"/"False" -- ~Ethan~ From ikorot01 at gmail.com Wed Mar 23 14:51:07 2016 From: ikorot01 at gmail.com (Igor Korot) Date: Wed, 23 Mar 2016 14:51:07 -0400 Subject: Not downloading In-Reply-To: References: Message-ID: Hi, On Wed, Mar 23, 2016 at 1:31 PM, louis anderson wrote: > Dear Python, After a workshop in my school today regarding python, i have downloaded it on my laptop however when i go to launch it, it either tells me to modify python, repair python or uninstall python. It will not let me go onto python at all. I do not know what is going on and i hope yourselves can help me. What OS you are running? What version? Which python you downloaded? What version? Where di you downloaded it from? Thank you. > Thankyou > -- > https://mail.python.org/mailman/listinfo/python-list From bruce.kirk24 at gmail.com Wed Mar 23 16:16:30 2016 From: bruce.kirk24 at gmail.com (Bruce Kirk) Date: Wed, 23 Mar 2016 13:16:30 -0700 (PDT) Subject: Python to do CDC on XML files Message-ID: <833ad88a-4840-4a23-8ab3-b736068b49fe@googlegroups.com> Does anyone know of any existing projects on how to generate a change data capture on 2 very large xml files. The xml structures are the same, it is the data within the files that may differ. I need to take a XML file from yesterday and compare it to the XML file produced today and not which XML records have changed. I have done a google search and I am not able to find much on the subject other than software vendors trying to sell me their products. :-) Regards From gordon at panix.com Wed Mar 23 16:20:53 2016 From: gordon at panix.com (John Gordon) Date: Wed, 23 Mar 2016 20:20:53 +0000 (UTC) Subject: Not downloading References: Message-ID: In louis anderson writes: > After a workshop in my school today regarding python i have downloaded > it on my laptop Since you were in fact able to download it, your message title of "Not downloading" is somewhat misleading... > however when i go to launch it it either tells me to modify python > repair python or uninstall python. It will not let me go onto python > at all. What operating system do you have on your laptop, and what version of Python are you trying to install? Python 3.5 is known to have trouble installing on Windows XP. If you have Win XP, try using an older 3.4 version of Python. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From bgailer at gmail.com Wed Mar 23 16:47:07 2016 From: bgailer at gmail.com (Bob Gailer) Date: Wed, 23 Mar 2016 16:47:07 -0400 Subject: Python to do CDC on XML files In-Reply-To: <833ad88a-4840-4a23-8ab3-b736068b49fe@googlegroups.com> References: <833ad88a-4840-4a23-8ab3-b736068b49fe@googlegroups.com> Message-ID: On Mar 23, 2016 4:20 PM, "Bruce Kirk" wrote: > > Does anyone know of any existing projects on how to generate a change data capture on 2 very large xml files. > > The xml structures are the same, it is the data within the files that may differ. > It should not be too difficult to write a program that locates the tags delimiting each record, then compare them. From srkunze at mail.de Wed Mar 23 18:06:01 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Wed, 23 Mar 2016 23:06:01 +0100 Subject: monkey patching __code__ In-Reply-To: <87egb1vbyn.fsf@handshake.de> References: <56EBEB5A.7050207@mail.de> <56EED3DE.7050101@mail.de> <56F13417.8060108@mail.de> <87egb1vbyn.fsf@handshake.de> Message-ID: <56F31349.2090900@mail.de> On 23.03.2016 09:24, dieter wrote: > But you have observed that you cannot do everything with a > code substitution: a function call does not only depend on the code > but also on other properties of the function object: e.g. the > parameter processing. Yep, that's because Python is very flexible and provides means for changing even that. So, it's not part of the __code__ object but part of the actual function. That's okay. > You might be able to change them in a similar way as "__code__" (i.e. > direct modification). Otherwise, you would need to construct a new > "function object" -- and lose the possibility to completely > change the function object in place. Exactly. Except __globals__ we are all set and I think that'll work for us. I will report once we've implemented it that way. Best, Sven From ben+python at benfinney.id.au Wed Mar 23 18:09:43 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 24 Mar 2016 09:09:43 +1100 Subject: [Not actually OT] Trouble in node.js land References: <56f25be6$0$2805$c3e8da3$76491128@news.astraweb.com> <56f2ad9c$0$1607$c3e8da3$5496439d@news.astraweb.com> <1458746762.3237061.557619626.27F4A893@webmail.messagingengine.com> Message-ID: <85shzgdexk.fsf@benfinney.id.au> Random832 writes: > B) His software costs no money, so no harm has been done even if > someone looking for the phone app finds it and "buys" it by mistake. That statement assumes that only the loss of money is harm. Do you recognise damage to public reputation as harm? Do you recognise any other non-monetary damage as harm? Is it legitimate to defend against such damage ? for example, damage to public reputation ? through use of trademark law? -- \ ?This world in arms is not spending money alone. It is spending | `\ the sweat of its laborers, the genius of its scientists, the | _o__) hopes of its children.? ?Dwight Eisenhower, 1953-04-16 | Ben Finney From breamoreboy at yahoo.co.uk Wed Mar 23 19:21:38 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 23 Mar 2016 23:21:38 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <1458750268.3251250.557690202.04DB2EB3@webmail.messagingengine.com> References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <1458750268.3251250.557690202.04DB2EB3@webmail.messagingengine.com> Message-ID: On 23/03/2016 16:24, Random832 wrote: > > > On Wed, Mar 23, 2016, at 12:08, Mark Lawrence wrote: >>> And doing it 'Pythonically' can lead to suggestions such as the >>> following the other day: >>> >>> c, psource = psource[0], psource[1:] >>> >>> (where psource is a very long string), which even I could tell, from >>> knowing what goes on behind the scenes, wasn't going to work well >>> (duplicating the rest of the string roughly every other character). >>> >> >> It would work perfectly. How would it duplicate the rest of the string >> roughly every other character? > > Er, I think he's suggesting that this would be in an inner loop > (something like while psource: c, psource = psource[0], psource[1:]). > What I'm not sure of is why he thinks this is pythonic. > It was in response to Dennis Lee Bieber http://code.activestate.com/lists/python-list/700242/. Quite why he thinks it won't work well I've no idea. I'd have said it was Pythonic, as slicing is a standard idiom. As for every other character, it again shows his complete ignorance of Python. Although thinking about it, it you were to skip every character that needed processing, surely that would be really fast? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From steve at pearwood.info Wed Mar 23 19:55:40 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 24 Mar 2016 10:55:40 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f32cff$0$1602$c3e8da3$5496439d@news.astraweb.com> On Thu, 24 Mar 2016 03:24 am, Random832 wrote: > On Wed, Mar 23, 2016, at 12:08, Mark Lawrence wrote: >> > And doing it 'Pythonically' can lead to suggestions such as the >> > following the other day: >> > >> > c, psource = psource[0], psource[1:] >> > >> > (where psource is a very long string), which even I could tell, from >> > knowing what goes on behind the scenes, wasn't going to work well >> > (duplicating the rest of the string roughly every other character). >> > >> >> It would work perfectly. How would it duplicate the rest of the string >> roughly every other character? > > Er, I think he's suggesting that this would be in an inner loop > (something like while psource: c, psource = psource[0], psource[1:]). > What I'm not sure of is why he thinks this is pythonic. Because somebody here (Dennis) criticised his earlier code for passing "your entire source string along with the character from it to the function", and suggested splitting the string into its head and tail instead. Dennis' code started: while psource: c, psource = psource[0], psource[1:] lxsymbol = disptable[min(ord(c), 256)](c, psource) But one positive: this conclusively proves that "Pythonic" is in the eye of the beholder. Dennis thinks that c, psource = psource[0], psource[1:] is reasonable Python code; you think it's not ("I'm not sure why [Bart] thinks this is pythonic"). Pythonic or not, Bart is correct to be concerned about the performance, since this ends up copying the string over and over again. If we start with the string "aardvark", say, it gets split: "a", "ardvark" "a", "rdvark" "r", "dvark" "d", "vark" "v", "ark" "a", "rk" "r", "k" "k", "" each of which involves creating two string objects. Ignoring the effects of string interning (caching), an 8-character string gets split up into: 8 x 1 character strings; 1 x 7 character string; 1 x 6 character string; 1 x 5 character string; 1 x 4 character string; 1 x 3 character string; 1 x 2 character string; 1 x 1 character string; 1 x 0 character string; thus creating 16 string objects in total, and copying 8+7+6+5+4+3+2+1+0 characters, or 36 characters in total. For an N character string, we have: N x 1 character strings; 1 x N-1 character string; 1 x N-2 character string; 1 x N-3 character string; ... 1 x 2 character string; 1 x 1 character string; 1 x 0 character string; giving a total of sum(range(N+1)) which is N*(N+1)/2. In big-oh notation, this is quadratic behaviour: O(N**2), and Bart is right to be concerned. This same sort of thing is precisely why building up a string by repeated string concatenation can be horribly slow. This is the same, only in reverse: we're demolishing the string, one character at a time. Now, there are practical reasons why this may not be *quite* as bad as Bart fears: - caching of small strings may mean that we're more like O( (N-1)**2 ), which is (barely) better; - the coefficient is in our favour (1/2); - string copying may be quite efficient (although not as efficient as in C, where they can be implemented by just a memcopy, more or less); - the strings are getting smaller all the time, which makes memory management easier, when compared to having to allocate growing strings; - although against that, perhaps this ends up fragmenting memory even more? - it *may* turn out that the cost of the rest of the work done dwarfs the cost of copying the string in the first place - but then again it might not. -- Steven From bruce.kirk24 at gmail.com Wed Mar 23 19:57:12 2016 From: bruce.kirk24 at gmail.com (Bruce Kirk) Date: Wed, 23 Mar 2016 19:57:12 -0400 Subject: Python to do CDC on XML files In-Reply-To: References: <833ad88a-4840-4a23-8ab3-b736068b49fe@googlegroups.com> Message-ID: <683FF696-8223-46FB-9A72-55839A8B4241@gmail.com> I agree, the challenge is the volume of the data to compare is 13. Million records. So it needs to be very fast Sent from my iPad > On Mar 23, 2016, at 4:47 PM, Bob Gailer wrote: > > > On Mar 23, 2016 4:20 PM, "Bruce Kirk" wrote: > > > > Does anyone know of any existing projects on how to generate a change data capture on 2 very large xml files. > > > > The xml structures are the same, it is the data within the files that may differ. > > > It should not be too difficult to write a program that locates the tags delimiting each record, then compare them. From random832 at fastmail.com Wed Mar 23 20:12:12 2016 From: random832 at fastmail.com (Random832) Date: Wed, 23 Mar 2016 20:12:12 -0400 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <56f32cff$0$1602$c3e8da3$5496439d@news.astraweb.com> References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f32cff$0$1602$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1458778332.487148.558100370.607E9944@webmail.messagingengine.com> On Wed, Mar 23, 2016, at 19:55, Steven D'Aprano wrote: > while psource: > c, psource = psource[0], psource[1:] > lxsymbol = disptable[min(ord(c), 256)](c, psource) > > > But one positive: this conclusively proves that "Pythonic" is in the eye > of > the beholder. Dennis thinks that c, psource = psource[0], psource[1:] is > reasonable Python code; you think it's not ("I'm not sure why [Bart] > thinks > this is pythonic"). I guess the question is, what do you _actually_ need the tail string for? If you're using it in a loop, to pop further characters from (the scenario that would cause it to be copying the string over lots of times), wouldn't it make more sense to use a StringIO (or, in the real world where your C source code isn't a string, a file) and let that class take care of handing out characters when you ask for them? Like... fsource = StringIO(psource) while True: c = fsource.read(1) lxsymbol = disptable[min(ord(c), 256)](c, fsource) From rosuav at gmail.com Wed Mar 23 20:15:42 2016 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 24 Mar 2016 11:15:42 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <1458778332.487148.558100370.607E9944@webmail.messagingengine.com> References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f32cff$0$1602$c3e8da3$5496439d@news.astraweb.com> <1458778332.487148.558100370.607E9944@webmail.messagingengine.com> Message-ID: On Thu, Mar 24, 2016 at 11:12 AM, Random832 wrote: > I guess the question is, what do you _actually_ need the tail string > for? If you're using it in a loop, to pop further characters from (the > scenario that would cause it to be copying the string over lots of > times), wouldn't it make more sense to use a StringIO (or, in the real > world where your C source code isn't a string, a file) and let that > class take care of handing out characters when you ask for them? > > Like... > > fsource = StringIO(psource) > > while True: > c = fsource.read(1) > lxsymbol = disptable[min(ord(c), 256)](c, fsource) Or... just grab an iterator off the string and call next() on it? ChrisA From jandbfawcett at gmail.com Wed Mar 23 20:39:18 2016 From: jandbfawcett at gmail.com (Bryon Fawcett) Date: Thu, 24 Mar 2016 13:39:18 +1300 Subject: Connect to Default Printer Message-ID: Good afternoon. Could you please advise me how to connect the python software to my default printer. Regards, Bryon Fawcett. From breamoreboy at yahoo.co.uk Wed Mar 23 21:12:32 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 24 Mar 2016 01:12:32 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <56f32cff$0$1602$c3e8da3$5496439d@news.astraweb.com> References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f32cff$0$1602$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 23/03/2016 23:55, Steven D'Aprano wrote: > On Thu, 24 Mar 2016 03:24 am, Random832 wrote: > >> On Wed, Mar 23, 2016, at 12:08, Mark Lawrence wrote: >>>> And doing it 'Pythonically' can lead to suggestions such as the >>>> following the other day: >>>> >>>> c, psource = psource[0], psource[1:] >>>> >>>> (where psource is a very long string), which even I could tell, from >>>> knowing what goes on behind the scenes, wasn't going to work well >>>> (duplicating the rest of the string roughly every other character). >>>> >>> >>> It would work perfectly. How would it duplicate the rest of the string >>> roughly every other character? >> >> Er, I think he's suggesting that this would be in an inner loop >> (something like while psource: c, psource = psource[0], psource[1:]). >> What I'm not sure of is why he thinks this is pythonic. > > Because somebody here (Dennis) criticised his earlier code for passing "your > entire source string along with the character from it to the function", and > suggested splitting the string into its head and tail instead. Dennis' code > started: > > while psource: > c, psource = psource[0], psource[1:] > lxsymbol = disptable[min(ord(c), 256)](c, psource) > > > But one positive: this conclusively proves that "Pythonic" is in the eye of > the beholder. Dennis thinks that c, psource = psource[0], psource[1:] is > reasonable Python code; you think it's not ("I'm not sure why [Bart] thinks > this is pythonic"). > > Pythonic or not, Bart is correct to be concerned about the performance, Where and when did he ever say anything about performance with respect to the above piece of code? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From eryksun at gmail.com Wed Mar 23 22:07:51 2016 From: eryksun at gmail.com (eryk sun) Date: Wed, 23 Mar 2016 21:07:51 -0500 Subject: Not downloading In-Reply-To: References: Message-ID: On Wed, Mar 23, 2016 at 12:31 PM, louis anderson wrote: > After a workshop in my school today regarding python, i have downloaded it on my laptop > however when i go to launch it, it either tells me to modify python, repair python or uninstall > python. It will not let me go onto python at all. I do not know what is going on and i hope > yourselves can help me. This problem is unlikely to be resolved on this list since attachments don't work here (e.g. for screenshots and zipped log files). Please create an issue on bugs.python.org. From best_lay at yahoo.com Wed Mar 23 22:17:57 2016 From: best_lay at yahoo.com (Wildman) Date: Wed, 23 Mar 2016 21:17:57 -0500 Subject: Key Binding Problem References: Message-ID: <06adnbnMouHI027LnZ2dnUU7-XednZ2d@giganews.com> On Wed, 23 Mar 2016 20:34:08 -0400, Dennis Lee Bieber wrote: > On Wed, 23 Mar 2016 10:58:09 -0500, Wildman via Python-list > declaimed the following: > >>On Wed, 23 Mar 2016 02:47:47 -0400, Terry Reedy wrote: >> >>> def load_image(self, _): >>> # load image file >>> >>> You must pass the bound method, as you did, and not the function itself >>> (which has two parameters). >> >>I meant to ask a followup question in my previous post but >>it slipped my mind. >> >>What is the best thing to do... >>Define all procedures this way, (self. event)? > > Not "." but "," -- separate arguments That was a typo. My fingers have dyslexia. > Anything that is a method in a class object will tend to receive the > object itself as the first argument (commonly called "self" in Python, "me" > in Visual BASIC, "this" in C++). Tk callback functions (I think you were > using Tkinter) likely pass the event data (that is, what triggered the > callback -- a key-in callback passes information about the key that was > pressed). > >>Define all event handlers this way? > > If they are methods of a Tk class, then likely they need this format... > But for classes you create yourself, it depends on how you intend to invoke > them. Thanks for the info. >>Define only the event handlers that will be called from >>elsewhere in the code, as in this case? > > Uhm... If an event handler is never invoked, why write it? I was referring to procedures called by a button click as opposed to a procedure calledd from elsewhere in the code. I guess there is no difference. I assume that is what you meant. -- GNU/Linux user #557453 The cow died so I don't need your bull! From rosuav at gmail.com Wed Mar 23 23:24:25 2016 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 24 Mar 2016 14:24:25 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Mar 24, 2016 at 12:41 AM, BartC wrote: > To extend this analogy better, executing byte-code to directly perform a > task itself might be equivalent to travelling on foot, while everyone is > suggesting taking the bus, tube or taxi. > > But when you are on foot, it might be worth looking at what's slowing you > down, or indeed at whether you are actually being slowed down at all. With > walking it's easy because 3mph is typical, you'll know when something is > obviously wrong (dragging or carrying a huge amount of baggage with you for > example). Running byte-code is not so obvious. > It's easy to see that carrying five boxes of books will slow down you're walking *dramatically*. In fact, it's probably quicker to take just one of them, and then come back for another one, and so on. When you travel by car, it's much harder to measure the cost of the five boxes, but it made so much difference in walking time that you should probably take one box at a time, right? This is how you're currently evaluating Python. Instead of starting with the most simple and obvious code and refining from there, you're starting from a whole lot of preconceived ideas about what's "fast" or "slow", and assuming/expecting that they'll all still be valid. Many of them won't be, yet you still persist in doing things based on what you expect to be the case (because of what's fast/slow in C or some other language). We've explained this a number of times, and one by one, we're coming to the conclusion that you not only don't understand Python, you don't *want* to understand Python; and until you actually understand how the language works, timing stats are dubious. Do you understand why people aren't taking your results very seriously? ChrisA From rustompmody at gmail.com Wed Mar 23 23:38:44 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 23 Mar 2016 20:38:44 -0700 (PDT) Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thursday, March 24, 2016 at 8:54:49 AM UTC+5:30, Chris Angelico wrote: > On Thu, Mar 24, 2016 at 12:41 AM, BartC wrote: > > To extend this analogy better, executing byte-code to directly perform a > > task itself might be equivalent to travelling on foot, while everyone is > > suggesting taking the bus, tube or taxi. > > > > But when you are on foot, it might be worth looking at what's slowing you > > down, or indeed at whether you are actually being slowed down at all. With > > walking it's easy because 3mph is typical, you'll know when something is > > obviously wrong (dragging or carrying a huge amount of baggage with you for > > example). Running byte-code is not so obvious. > > > > It's easy to see that carrying five boxes of books will slow down > you're walking *dramatically*. In fact, it's probably quicker to take > just one of them, and then come back for another one, and so on. When > you travel by car, it's much harder to measure the cost of the five > boxes, but it made so much difference in walking time that you should > probably take one box at a time, right? > > This is how you're currently evaluating Python. Instead of starting > with the most simple and obvious code and refining from there, you're > starting from a whole lot of preconceived ideas about what's "fast" or > "slow", and assuming/expecting that they'll all still be valid. Many > of them won't be, yet you still persist in doing things based on what > you expect to be the case (because of what's fast/slow in C or some > other language). We've explained this a number of times, and one by > one, we're coming to the conclusion that you not only don't understand > Python, you don't *want* to understand Python; and until you actually > understand how the language works, timing stats are dubious. > > Do you understand why people aren't taking your results very seriously? Terry recommended a. re module b. array lookup c. dict lookup Putting aside Bart's objection to re module for the moment, he has already posted a list-lookup version. In effect he has complied with the suggestions of experienced members of this list (in this case a python-dev) Can I request you (Bart) to re-post these data?? - if-else - list-lookup - dict-lookup From adam at no_thanks.com Thu Mar 24 00:18:31 2016 From: adam at no_thanks.com (Adam) Date: Wed, 23 Mar 2016 21:18:31 -0700 Subject: crash while using PyCharm / Python3 References: Message-ID: "Adam" wrote in message news:ncikss$tks$1 at news.albasani.net... > > Host OS: Ubuntu Desktop 14.04 LTS / Unity > > System crashed while using PyCharm / Python3. > Booting takes forever and stuck at the purple screen with > the Ubuntu logo and the five dots cycling. > How to fix? > Searching for this thread in a browser lead to the code.activestate.com website where I see posts from Daniel Wilcox. But, in my newsreader, I do not see his posts, which is why his posts are not getting any response. Daniel, how/where are you responding to this thread? From rosuav at gmail.com Thu Mar 24 03:00:51 2016 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 24 Mar 2016 18:00:51 +1100 Subject: Python to do CDC on XML files In-Reply-To: <683FF696-8223-46FB-9A72-55839A8B4241@gmail.com> References: <833ad88a-4840-4a23-8ab3-b736068b49fe@googlegroups.com> <683FF696-8223-46FB-9A72-55839A8B4241@gmail.com> Message-ID: On Thu, Mar 24, 2016 at 10:57 AM, Bruce Kirk wrote: > I agree, the challenge is the volume of the data to compare is 13. Million records. So it needs to be very fast 13M records is a good lot. To what extent can the data change? You may find it easiest to do some sort of conversion to text, throwing away any information that isn't "interesting", and then use the standard 'diff' utility to compare the text files. It's up to you to figure out what differences are "uninteresting"; it'll depend on your exact data. As long as you can do the conversion-to-text in a simple and straight-forward way, the overall operation will be reasonably fast. If this is a periodic thing (eg you're constantly checking today's file against yesterday's), saving the dumped text file will mean you generally need to just convert one file, halving your workload. This isn't a solution so much as a broad pointer... hope it's at least a start! ChrisA From rlopezsr at gmail.com Thu Mar 24 04:17:58 2016 From: rlopezsr at gmail.com (Rudi Lopez Lopez) Date: Thu, 24 Mar 2016 03:17:58 -0500 Subject: Bug in python34 package struct Message-ID: from struct import pack print(hex(126)) print(pack('>H',126)) Rudi G. Lopez From __peter__ at web.de Thu Mar 24 04:19:32 2016 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 Mar 2016 09:19:32 +0100 Subject: Python to do CDC on XML files References: <833ad88a-4840-4a23-8ab3-b736068b49fe@googlegroups.com> Message-ID: Bruce Kirk wrote: > Does anyone know of any existing projects on how to generate a change data > capture on 2 very large xml files. > > The xml structures are the same, it is the data within the files that may > differ. > > I need to take a XML file from yesterday and compare it to the XML file > produced today and not which XML records have changed. > > I have done a google search and I am not able to find much on the subject > other than software vendors trying to sell me their products. :-) There is http://www.logilab.org/project/xmldiff As an alternative you may try to log the changes as they occur instead of inspecting the result. If the application generating the file is not under your control, does it offer other output formats, e. g. csv? Or if the xml file is basically a sequence of one type of node you may convert it to a database (sqlite will do) to match and compare the "records". From rosuav at gmail.com Thu Mar 24 05:04:51 2016 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 24 Mar 2016 20:04:51 +1100 Subject: Bug in python34 package struct In-Reply-To: References: Message-ID: On Thu, Mar 24, 2016 at 7:17 PM, Rudi Lopez Lopez wrote: > from struct import pack > > print(hex(126)) > print(pack('>H',126)) Explain the bug? ChrisA From marko at pacujo.net Thu Mar 24 05:05:35 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 24 Mar 2016 11:05:35 +0200 Subject: Bug in python34 package struct References: Message-ID: <87bn64nt40.fsf@elektro.pacujo.net> Rudi Lopez Lopez : > from struct import pack > > print(hex(126)) > print(pack('>H',126)) I can't see any bug. The tilde (~) has an ASCII code 126. Marko From lele at metapensiero.it Thu Mar 24 06:14:31 2016 From: lele at metapensiero.it (Lele Gaifax) Date: Thu, 24 Mar 2016 11:14:31 +0100 Subject: netrc and password containing whitespace Message-ID: <87wposnpx4.fsf@metapensiero.it> Hi all, I tried to insert an entry in my ~/.netrc for an account having a password that contains a space, something like: machine my-host-name login myname password "My Password" The standard library netrc module does not seem able to parse it, raising a NetrcParseError. Other programs (Emacs, to mention one) do the right thing with an entry like that. Inspecting the module, I see that it explicitly put the quote chars (both single and double, that is '"' and "'") in the shlex-based lexer's wordchars: def _parse(self, file, fp, default_netrc): lexer = shlex.shlex(fp) lexer.wordchars += r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" lexer.commenters = lexer.commenters.replace('#', '') ... Since the method read_token() state machine gives higher priority to wordchars over quotes, it obviously cannot parse the quoted string correctly: ... elif self.posix and nextchar in self.escape: escapedstate = 'a' self.state = nextchar elif nextchar in self.wordchars: self.token = nextchar self.state = 'a' elif nextchar in self.quotes: if not self.posix: self.token = nextchar self.state = nextchar ... I was not able to lookup an exact definition of netrc's syntax, so I wonder: is the implementation somewhat flawed, or am I missing something? Thanks in advance for any hint, ciao, lele. -- nickname: Lele Gaifax | Quando vivr? di quello che ho pensato ieri real: Emanuele Gaifas | comincer? ad aver paura di chi mi copia. lele at metapensiero.it | -- Fortunato Depero, 1929. From nomail at com.invalid Thu Mar 24 06:39:36 2016 From: nomail at com.invalid (ast) Date: Thu, 24 Mar 2016 11:39:36 +0100 Subject: newbie question Message-ID: <56f3c3eb$0$4546$426a74cc@news.free.fr> Hi I have a string which contains a tupe, eg: s = "(1, 2, 3, 4)" and I want to recover the tuple in a variable t t = (1, 2, 3, 4) how would you do ? From dpalao.python at gmail.com Thu Mar 24 06:49:05 2016 From: dpalao.python at gmail.com (David Palao) Date: Thu, 24 Mar 2016 11:49:05 +0100 Subject: newbie question In-Reply-To: <56f3c3eb$0$4546$426a74cc@news.free.fr> References: <56f3c3eb$0$4546$426a74cc@news.free.fr> Message-ID: Hi, Use "eval": s = "(1, 2, 3, 4)" t = eval(s) Best 2016-03-24 11:39 GMT+01:00 ast : > Hi > > I have a string which contains a tupe, eg: > > s = "(1, 2, 3, 4)" > > and I want to recover the tuple in a variable t > > t = (1, 2, 3, 4) > > how would you do ? > > > -- > https://mail.python.org/mailman/listinfo/python-list From nomail at com.invalid Thu Mar 24 06:54:12 2016 From: nomail at com.invalid (ast) Date: Thu, 24 Mar 2016 11:54:12 +0100 Subject: newbie question In-Reply-To: References: <56f3c3eb$0$4546$426a74cc@news.free.fr> Message-ID: <56f3c759$0$27835$426a74cc@news.free.fr> "David Palao" a ?crit dans le message de news:mailman.86.1458816553.2244.python-list at python.org... > Hi, > Use "eval": > s = "(1, 2, 3, 4)" > t = eval(s) > > Best > Thank you From m at funkyhat.org Thu Mar 24 06:57:40 2016 From: m at funkyhat.org (Matt Wheeler) Date: Thu, 24 Mar 2016 10:57:40 +0000 Subject: newbie question In-Reply-To: <56f3c3eb$0$4546$426a74cc@news.free.fr> References: <56f3c3eb$0$4546$426a74cc@news.free.fr> Message-ID: >>> import ast >>> s = "(1, 2, 3, 4)" >>> t = ast.literal_eval(s) >>> t (1, 2, 3, 4) On 24 March 2016 at 10:39, ast wrote: > Hi > > I have a string which contains a tupe, eg: > > s = "(1, 2, 3, 4)" > > and I want to recover the tuple in a variable t > > t = (1, 2, 3, 4) > > how would you do ? > > > -- > https://mail.python.org/mailman/listinfo/python-list -- Matt Wheeler http://funkyh.at From python.list at tim.thechases.com Thu Mar 24 06:58:36 2016 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 24 Mar 2016 05:58:36 -0500 Subject: newbie question In-Reply-To: References: <56f3c3eb$0$4546$426a74cc@news.free.fr> Message-ID: <20160324055836.78385795@bigbox.christie.dr> On 2016-03-24 11:49, David Palao wrote: >> s = "(1, 2, 3, 4)" >> >> and I want to recover the tuple in a variable t >> >> t = (1, 2, 3, 4) >> >> how would you do ? > > Use "eval": > s = "(1, 2, 3, 4)" > t = eval(s) Using eval() has security implications. Use ast.literal_eval for safety instead: import ast s = "(1, 2, 3, 4)" t = ast.literal_eval(s) -tkc From srkunze at mail.de Thu Mar 24 07:10:22 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Thu, 24 Mar 2016 12:10:22 +0100 Subject: newbie question In-Reply-To: References: <56f3c3eb$0$4546$426a74cc@news.free.fr> Message-ID: <56F3CB1E.2000606@mail.de> On 24.03.2016 11:57, Matt Wheeler wrote: >>>> import ast >>>> s = "(1, 2, 3, 4)" >>>> t = ast.literal_eval(s) >>>> t > (1, 2, 3, 4) I suppose that's the better solution in terms of safety. From steve at pearwood.info Thu Mar 24 07:13:20 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 24 Mar 2016 22:13:20 +1100 Subject: newbie question References: <56f3c3eb$0$4546$426a74cc@news.free.fr> Message-ID: <56f3cbd2$0$1609$c3e8da3$5496439d@news.astraweb.com> On Thu, 24 Mar 2016 09:39 pm, ast wrote: > Hi > > I have a string which contains a tupe, eg: > > s = "(1, 2, 3, 4)" > > and I want to recover the tuple in a variable t > > t = (1, 2, 3, 4) > > how would you do ? py> import ast py> ast.literal_eval("(1, 2, 3, 4)") (1, 2, 3, 4) -- Steven From invalid at invalid.invalid Thu Mar 24 08:55:57 2016 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 24 Mar 2016 12:55:57 +0000 (UTC) Subject: Connect to Default Printer References: Message-ID: On 2016-03-24, Bryon Fawcett wrote: > Could you please advise me how to connect the python software to my default > printer. import os os.popen("lpr","w").write("Hi there, this just got printed!\r\n") -- Grant From bc at freeuk.com Thu Mar 24 09:01:54 2016 From: bc at freeuk.com (BartC) Date: Thu, 24 Mar 2016 13:01:54 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 24/03/2016 03:24, Chris Angelico wrote: > On Thu, Mar 24, 2016 at 12:41 AM, BartC wrote: >> To extend this analogy better, executing byte-code to directly perform a >> task itself might be equivalent to travelling on foot, while everyone is >> suggesting taking the bus, tube or taxi. > It's easy to see that carrying five boxes of books will slow down > you're walking *dramatically*. In fact, it's probably quicker to take > just one of them, and then come back for another one, and so on. When > you travel by car, it's much harder to measure the cost of the five > boxes, but it made so much difference in walking time that you should > probably take one box at a time, right? > > This is how you're currently evaluating Python. Instead of starting > with the most simple and obvious code and refining from there, you're > starting from a whole lot of preconceived ideas about what's "fast" or > "slow", and assuming/expecting that they'll all still be valid. Many > of them won't be, yet you still persist in doing things based on what > you expect to be the case (because of what's fast/slow in C or some > other language). We've explained this a number of times, and one by > one, we're coming to the conclusion that you not only don't understand > Python, you don't *want* to understand Python; and until you actually > understand how the language works, timing stats are dubious. > > Do you understand why people aren't taking your results very seriously? I've been using interpreted languages since the 80s, when they were much cruder and slower (and when hardware was much slower too). Yet I could still use them effectively. (I reckoned that when used sensibly and in the right balance, a solution using a dynamic language would only be between one and two times slower than using compiled, native code. But it was many times more productive.) So I understand perfectly that such languages have a huge range of applications no matter what the speed of the underlying byte-code. However.... once you start looking at tasks where the speed /might/ matter, then you have to start measuring properly. And forgetting Python for a minute and concentrating only on its byte-code as a language in its own right, how would you go about the job of streamlining it? You might start with profiling it to see which codes are more expensive, which are called most then, all the usual stuff. But there are all sorts of micro-micro-benchmarks that can concentrate on a single byte-code. For example, how long does it take to call an empty function with no parameters? Just putting such a call into a simple loop can be effective: Python 3 (on Windows) might take 200ns. Clisp is 1300ns (interpreted, presumably). Ruby 170ns. Lua 80ns. Mine 10-20ns. Unoptimised C is 4ns, but this is not executing code indirectly as most of the rest have to. [Timings include loop overheads that need to be factored out.] So there might be room for improvement, but those faster languages are also simpler. Is Python's richness or dynamism the main factor here? If so there is probably little to be done; if not... This is where the fun starts. But I understand that most people aren't interested in this kind of sport. -- Bartc From m at funkyhat.org Thu Mar 24 09:22:13 2016 From: m at funkyhat.org (Matt Wheeler) Date: Thu, 24 Mar 2016 13:22:13 +0000 Subject: newbie question In-Reply-To: <56F3CB1E.2000606@mail.de> References: <56f3c3eb$0$4546$426a74cc@news.free.fr> <56F3CB1E.2000606@mail.de> Message-ID: On Thu, 24 Mar 2016 11:10 Sven R. Kunze, wrote: > On 24.03.2016 11:57, Matt Wheeler wrote: > >>>> import ast > >>>> s = "(1, 2, 3, 4)" > >>>> t = ast.literal_eval(s) > >>>> t > > (1, 2, 3, 4) > > I suppose that's the better solution in terms of safety. > It has the added advantage that the enquirer gets to import a module that shares their name ;) > From steve at pearwood.info Thu Mar 24 09:50:15 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Mar 2016 00:50:15 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> On Thu, 24 Mar 2016 02:24 pm, Chris Angelico wrote: > This is how you're currently evaluating Python. Instead of starting > with the most simple and obvious code One problem is that what counts as "simple and obvious" depends on what you are used to. Coming from a background of Pascal, iterating over a list like this: for i in range(len(mylist)): print mylist[i] was both simple and obvious. It took me years to break myself of that habit. Likewise clearing a list: for i in range(len(mylist)-1, -1, 0): del mylist[i] Fortunately I didn't need to do that very often. The point is that you, like most of the prominent posters here, have many years of experience in programming in Python. How do you expect Bart to come up with the same "simple and obvious" code as you? > and refining from there, you're > starting from a whole lot of preconceived ideas about what's "fast" or > "slow", and assuming/expecting that they'll all still be valid. Bart has done a much better job than most people at trying different things, despite the hostility he's been receiving. I don't think he's fully in the "dynamic scripting/glue/programming language" headspace, and I still have some disagreements with some of his opinions, but he's actually shown himself to be quite open to concrete suggestions made. Bart, if you're reading, can I suggest that any future benchmarks should be relatively constrained and short, so it is easier to read and understand them, and suggest improvements. > Many > of them won't be, yet you still persist in doing things based on what > you expect to be the case (because of what's fast/slow in C or some > other language). We've explained this a number of times, and one by > one, we're coming to the conclusion that you not only don't understand > Python, you don't *want* to understand Python; and until you actually > understand how the language works, timing stats are dubious. > > Do you understand why people aren't taking your results very seriously? You know what is missing from this conversation? For one of Bart's critics to actually show faster code. There's plenty of people telling him off for writing unpythonic and slow code, but I haven't seen anyone actually demonstrating that Python is faster than his results show. -- Steven From steve at pearwood.info Thu Mar 24 09:53:50 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Mar 2016 00:53:50 +1100 Subject: newbie question References: <56f3c3eb$0$4546$426a74cc@news.free.fr> Message-ID: <56f3f16f$0$1595$c3e8da3$5496439d@news.astraweb.com> On Thu, 24 Mar 2016 09:49 pm, David Palao wrote: > Hi, > Use "eval": > s = "(1, 2, 3, 4)" > t = eval(s) Don't use eval unless you absolutely, categorically, 100% trust the source of the string. Otherwise, you are letting the person who provided the string run any code they like on your computer. You want malware? That's how you get malware. -- Steven From rosuav at gmail.com Thu Mar 24 10:01:43 2016 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 25 Mar 2016 01:01:43 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Mar 25, 2016 at 12:50 AM, Steven D'Aprano wrote: > On Thu, 24 Mar 2016 02:24 pm, Chris Angelico wrote: > > >> This is how you're currently evaluating Python. Instead of starting >> with the most simple and obvious code > > One problem is that what counts as "simple and obvious" depends on what you > are used to. Coming from a background of Pascal, iterating over a list like > this: > > for i in range(len(mylist)): > print mylist[i] > > was both simple and obvious. It took me years to break myself of that habit. > > Likewise clearing a list: > > for i in range(len(mylist)-1, -1, 0): > del mylist[i] > > > Fortunately I didn't need to do that very often. > > The point is that you, like most of the prominent posters here, have many > years of experience in programming in Python. How do you expect Bart to > come up with the same "simple and obvious" code as you? I don't, until it's pointed out. At that point, someone who respects the language will at least pay *some* heed to the changed recommendations; what we're seeing here is that he continues to use C idioms and then complain that Python is slow. I don't expect him to magically know what Python idioms are, but when the thread has gone on this long and he's still showing the same style of code, that's when I start to agree with Ben that he's not paying heed to Pythonic vs non-Pythonic. ChrisA From bc at freeuk.com Thu Mar 24 10:04:53 2016 From: bc at freeuk.com (BartC) Date: Thu, 24 Mar 2016 14:04:53 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 24/03/2016 13:50, Steven D'Aprano wrote: > On Thu, 24 Mar 2016 02:24 pm, Chris Angelico wrote: > > >> This is how you're currently evaluating Python. Instead of starting >> with the most simple and obvious code > > One problem is that what counts as "simple and obvious" depends on what you > are used to. Coming from a background of Pascal, iterating over a list like > this: > > for i in range(len(mylist)): > print mylist[i] > > was both simple and obvious. It took me years to break myself of that habit. > > Likewise clearing a list: > > for i in range(len(mylist)-1, -1, 0): > del mylist[i] That's wouldn't be I'd call clearing a list, more like destroying it completely! How would you actually clear a list by traversing it (ie. not just building a new one)? This doesn't work: for x in L: x=0 as each x only refers to the value in each element of L, not the element itself (like the pass-by-reference problem). I'd presumably have to do: for i in range(len(L)): L[i]=0 -- Bartc From jon+usenet at unequivocal.co.uk Thu Mar 24 10:08:07 2016 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Thu, 24 Mar 2016 14:08:07 -0000 (UTC) Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2016-03-24, BartC wrote: > On 24/03/2016 13:50, Steven D'Aprano wrote: >> Likewise clearing a list: >> >> for i in range(len(mylist)-1, -1, 0): >> del mylist[i] > > That's wouldn't be I'd call clearing a list, more like destroying it > completely! > > How would you actually clear a list by traversing it (ie. not just > building a new one)? > > This doesn't work: > > for x in L: > x=0 > > as each x only refers to the value in each element of L, not the element > itself (like the pass-by-reference problem). > > I'd presumably have to do: > > for i in range(len(L)): > L[i]=0 That's kind've a weird thing to want to do; if you thought you needed to do that then most likely what you should actually be doing is re-writing your code so you no longer need to. However, you could do: L[:] = [0] * len(L) From bc at freeuk.com Thu Mar 24 10:16:06 2016 From: bc at freeuk.com (BartC) Date: Thu, 24 Mar 2016 14:16:06 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 24/03/2016 14:08, Jon Ribbens wrote: > On 2016-03-24, BartC wrote: >> On 24/03/2016 13:50, Steven D'Aprano wrote: >>> Likewise clearing a list: >>> >>> for i in range(len(mylist)-1, -1, 0): >>> del mylist[i] >> >> That's wouldn't be I'd call clearing a list, more like destroying it >> completely! >> >> How would you actually clear a list by traversing it (ie. not just >> building a new one)? >> >> This doesn't work: >> >> for x in L: >> x=0 >> >> as each x only refers to the value in each element of L, not the element >> itself (like the pass-by-reference problem). >> >> I'd presumably have to do: >> >> for i in range(len(L)): >> L[i]=0 > > That's kind've a weird thing to want to do; The thing I'm trying to demonstrate is changing an element of a list that you are traversing in a loop. Not necessarily set all elements to the same value. if you thought you needed > to do that then most likely what you should actually be doing is > re-writing your code so you no longer need to. However, you could do: > > L[:] = [0] * len(L) OK, but that's just building a new list as I've already mentioned. Or is the Pythonic way, when you want to change some elements of a list to just build a new one that incorporates those changes? -- Bartc From marko at pacujo.net Thu Mar 24 10:16:39 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 24 Mar 2016 16:16:39 +0200 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8737rgnepk.fsf@elektro.pacujo.net> BartC : > And forgetting Python for a minute and concentrating only on its > byte-code as a language in its own right, how would you go about the > job of streamlining it? CPython's bytecode is not crucial for CPython's execution speed. The bytecode is mainly a method of improving the performance of loading modules. IOW, it seeks to optimize parsing. CPython's VM does not have to execute the bytecode as-is. It can further compile and reprocess it internally to optimize speed and other attributes. As far as CPython is considered, a .pyc file contains precisely the same information as the .py file. Thus, executing .pyc is no faster than executing a .py file (ignoring the parsing overhead). The only advantage of streamlining bytecode is to speed up load times, which is a complete nonissue in most production environments. Really, your optimization efforts should concentrate not on bytecode but on runtime data structures, algorithms, heuristics, equivalence transformations, reachability analysis, profiling and such. Marko From m at funkyhat.org Thu Mar 24 10:22:28 2016 From: m at funkyhat.org (Matt Wheeler) Date: Thu, 24 Mar 2016 14:22:28 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 24 March 2016 at 14:04, BartC wrote: >On 24/03/2016 13:50, Steven D'Aprano wrote: >> for i in range(len(mylist)-1, -1, 0): >> del mylist[i] > > That's wouldn't be I'd call clearing a list, more like destroying it > completely! Look more closely. The semantics of using the del keyword with an index are to delete that element. The list isn't destroyed, it just has each element removed in turn. The point is that one can just do `mylist.clear()` > How would you actually clear a list by traversing it (ie. not just building > a new one)? > > This doesn't work: > > for x in L: > x=0 > > as each x only refers to the value in each element of L, not the element > itself (like the pass-by-reference problem). > > I'd presumably have to do: > > for i in range(len(L)): > L[i]=0 That doesn't clear the list, that results in a list of the same length where every element is 0. That might sound like the same thing if you're used to a bounded array of ints, for example, but in Python it's very much not. -- Matt Wheeler http://funkyh.at From bc at freeuk.com Thu Mar 24 10:28:32 2016 From: bc at freeuk.com (BartC) Date: Thu, 24 Mar 2016 14:28:32 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 24/03/2016 14:01, Chris Angelico wrote: > I don't, until it's pointed out. At that point, someone who respects > the language will at least pay *some* heed to the changed > recommendations; what we're seeing here is that he continues to use C > idioms and then complain that Python is slow. I don't expect him to > magically know what Python idioms are, but when the thread has gone on > this long and he's still showing the same style of code, that's when I > start to agree with Ben that he's not paying heed to Pythonic vs > non-Pythonic. Have a look at the short thread 'Rotation' in comp.programming starting 4-Jan-2016. (Possible link: https://groups.google.com/forum/#!searchin/comp.programming/rotation/comp.programming/aQh4n2HGtaU/sSbcyjqfEQAJ) Someone posts an algorithm in C++, I post a version in my language, someone else calls that a 'blub' solution and offers a much shorter version in /their/ language. I point out that their solution just uses a built-in to do the work. It by-passes the question of the algorithm, which was the point of the thread. I also point out that I also gave a one-line version in my language. What you're trying to say I guess is that such a one-liner would be Pythonic. And what I'm saying is that that would defeat the object of what I'm trying to do. -- Bartc From random832 at fastmail.com Thu Mar 24 10:33:01 2016 From: random832 at fastmail.com (Random832) Date: Thu, 24 Mar 2016 10:33:01 -0400 Subject: netrc and password containing whitespace In-Reply-To: <87wposnpx4.fsf@metapensiero.it> References: <87wposnpx4.fsf@metapensiero.it> Message-ID: <1458829981.3529604.558622250.1EE36599@webmail.messagingengine.com> On Thu, Mar 24, 2016, at 06:14, Lele Gaifax wrote: > I tried to insert an entry in my ~/.netrc for an account having a > password that contains a space, something like: > > machine my-host-name login myname password "My Password" > > The standard library netrc module does not seem able to parse it, > raising a NetrcParseError. Other programs (Emacs, to mention one) do > the right thing with an entry like that. > > I was not able to lookup an exact definition of netrc's syntax, so I > wonder: is the implementation somewhat flawed, or am I missing > something? The implementation seems very basic... I ran into trouble trying to store entries with no password (with the idea in mind of having my program prompt for the password), though, out of curiosity, does ftp handle your quoted passwords? Also, I'm surprised that you're using .netrc for emacs - in my experience the file emacs uses is called .authinfo. From jussi.piitulainen at helsinki.fi Thu Mar 24 10:34:13 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Thu, 24 Mar 2016 16:34:13 +0200 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: BartC writes: > On 24/03/2016 14:08, Jon Ribbens wrote: >> On 2016-03-24, BartC wrote: >>> I'd presumably have to do: >>> >>> for i in range(len(L)): >>> L[i]=0 >> >> That's kind've a weird thing to want to do; > > The thing I'm trying to demonstrate is changing an element of a list > that you are traversing in a loop. Not necessarily set all elements to > the same value. You understand correctly, but it may be more natural in practice to write it this way: for k, item in enumerate(them): them[k] = f(item) I _think_ I might write it that way even when "f(item)" does not depend on the old value at all, but I don't expect to be in that situation. From rustompmody at gmail.com Thu Mar 24 10:37:15 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 24 Mar 2016 07:37:15 -0700 (PDT) Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <8737rgnepk.fsf@elektro.pacujo.net> References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <8737rgnepk.fsf@elektro.pacujo.net> Message-ID: On Thursday, March 24, 2016 at 7:46:55 PM UTC+5:30, Marko Rauhamaa wrote: > BartC : > > > And forgetting Python for a minute and concentrating only on its > > byte-code as a language in its own right, how would you go about the > > job of streamlining it? > Really, your optimization efforts should concentrate not on bytecode but > on runtime data structures, algorithms, heuristics, equivalence > transformations, reachability analysis, profiling and such. 'A' is a scientific programmer; he optimizes his scientific programs 'C' is a financial programmer; he optimizes his finance programs 'B(art)' is a bytecode-interpreter programmer; How does he optimize his bytecode interpreters? From bc at freeuk.com Thu Mar 24 10:49:17 2016 From: bc at freeuk.com (BartC) Date: Thu, 24 Mar 2016 14:49:17 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 24/03/2016 14:34, Jussi Piitulainen wrote: > BartC writes: >> On 24/03/2016 14:08, Jon Ribbens wrote: >>> On 2016-03-24, BartC wrote: >>>> I'd presumably have to do: >>>> >>>> for i in range(len(L)): >>>> L[i]=0 >>> >>> That's kind've a weird thing to want to do; >> >> The thing I'm trying to demonstrate is changing an element of a list >> that you are traversing in a loop. Not necessarily set all elements to >> the same value. > > You understand correctly, but it may be more natural in practice to > write it this way: > > for k, item in enumerate(them): > them[k] = f(item) > > I _think_ I might write it that way even when "f(item)" does not depend > on the old value at all, but I don't expect to be in that situation. > Yes, you're right. Usually the update is conditional on the existing value. But my too-simple example would have had an unneeded item variable. -- Bartc From breamoreboy at yahoo.co.uk Thu Mar 24 10:51:32 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 24 Mar 2016 14:51:32 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 24/03/2016 14:22, Matt Wheeler wrote: > > The point is that one can just do `mylist.clear()` > Only in 3.3 and up. In Python 2.x you have to do it the old fashioned, long winded way. mylist[:] = [] -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From random832 at fastmail.com Thu Mar 24 10:53:14 2016 From: random832 at fastmail.com (Random832) Date: Thu, 24 Mar 2016 10:53:14 -0400 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1458831194.3535222.558644394.160CC204@webmail.messagingengine.com> On Thu, Mar 24, 2016, at 10:49, BartC wrote: > On 24/03/2016 14:34, Jussi Piitulainen wrote: > > You understand correctly, but it may be more natural in practice to > > write it this way: > > > > for k, item in enumerate(them): > > them[k] = f(item) > > > > I _think_ I might write it that way even when "f(item)" does not depend > > on the old value at all, but I don't expect to be in that situation. > > > > Yes, you're right. Usually the update is conditional on the existing > value. But my too-simple example would have had an unneeded item > variable. How about them[:] = map(f, them)? From lele at metapensiero.it Thu Mar 24 11:03:07 2016 From: lele at metapensiero.it (Lele Gaifax) Date: Thu, 24 Mar 2016 16:03:07 +0100 Subject: netrc and password containing whitespace References: <87wposnpx4.fsf@metapensiero.it> <1458829981.3529604.558622250.1EE36599@webmail.messagingengine.com> Message-ID: <87fuvfor4k.fsf@metapensiero.it> Random832 writes: > The implementation seems very basic... I ran into trouble trying to > store entries with no password (with the idea in mind of having my > program prompt for the password), though, out of curiosity, does ftp > handle your quoted passwords? Uhm, dunno :-) I think it's been more than two decades since my last use of FTP... I use it as a generic auths pocket, mainly for emails and IRC. I found the glitch adding an entry for a new account in my offlineimap configuration. > Also, I'm surprised that you're using .netrc for emacs - in my > experience the file emacs uses is called .authinfo. AFAICT, that's just the default file name stored in netrc-file, the format is really the same. Using .netrc has the advantage that other programs can use it, like the cited offlineimap. Aside that, the functionality is exposed in Emacs as netrc-xxx, and comes from net/netrc.el. Cfr. also https://www.emacswiki.org/emacs/GnusAuthinfo. ciao, lele. -- nickname: Lele Gaifax | Quando vivr? di quello che ho pensato ieri real: Emanuele Gaifas | comincer? ad aver paura di chi mi copia. lele at metapensiero.it | -- Fortunato Depero, 1929. From jon+usenet at unequivocal.co.uk Thu Mar 24 11:03:16 2016 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Thu, 24 Mar 2016 15:03:16 -0000 (UTC) Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2016-03-24, BartC wrote: > On 24/03/2016 14:08, Jon Ribbens wrote: >> if you thought you needed to do that then most likely what you >> should actually be doing is re-writing your code so you no longer >> need to. However, you could do: >> >> L[:] = [0] * len(L) > > OK, but that's just building a new list as I've already mentioned. No it isn't, it's replacing the elements in-place, that's what the "L[:]" bit means. Replacing the list object itself would be: L = [0] * len(L) > Or is the Pythonic way, when you want to change some elements of a list > to just build a new one that incorporates those changes? I think it would depend on how many elements you were changing and why. It doesn't come up all that often because of the ease in which Python functions can return multiple values but sometimes you might make a function which takes as a parameter a list which the function will mutate. From invalid at invalid.invalid Thu Mar 24 11:05:30 2016 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 24 Mar 2016 15:05:30 +0000 (UTC) Subject: newbie question References: <56f3c3eb$0$4546$426a74cc@news.free.fr> <56f3f16f$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2016-03-24, Steven D'Aprano wrote: > On Thu, 24 Mar 2016 09:49 pm, David Palao wrote: > >> Hi, >> Use "eval": >> s = "(1, 2, 3, 4)" >> t = eval(s) > > Don't use eval unless you absolutely, categorically, 100% trust the source > of the string. And then still don't use it. :) eval is only safe if you're passing it a literal string containing nothing but a literal constant expression -- in which case the eval is superflous. OK, I admit I've used it for quick hacks on occasion. But, I shouldn't have. -- Grant From bc at freeuk.com Thu Mar 24 11:18:49 2016 From: bc at freeuk.com (BartC) Date: Thu, 24 Mar 2016 15:18:49 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 24/03/2016 15:03, Jon Ribbens wrote: > On 2016-03-24, BartC wrote: >> On 24/03/2016 14:08, Jon Ribbens wrote: >>> if you thought you needed to do that then most likely what you >>> should actually be doing is re-writing your code so you no longer >>> need to. However, you could do: >>> >>> L[:] = [0] * len(L) >> >> OK, but that's just building a new list as I've already mentioned. > > No it isn't, it's replacing the elements in-place, Replace them with what, if not an entirely new list built from '[0]*len(L)'? (And which would briefly require twice the memory occupied by the old list, if I'm not mistaken.) >> Or is the Pythonic way, when you want to change some elements of a list >> to just build a new one that incorporates those changes? > > I think it would depend on how many elements you were changing and > why. It doesn't come up all that often because of the ease in which > Python functions can return multiple values but sometimes you might > make a function which takes as a parameter a list which the function > will mutate. Answering my own question, obviously changing some elements of a list has to be Pythonic, otherwise there wouldn't be lists, only non-mutable tuples. Although I was talking more within the context of a for-in loop. -- Bartc From jon+usenet at unequivocal.co.uk Thu Mar 24 11:25:56 2016 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Thu, 24 Mar 2016 15:25:56 -0000 (UTC) Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2016-03-24, BartC wrote: > On 24/03/2016 15:03, Jon Ribbens wrote: >> On 2016-03-24, BartC wrote: >>> On 24/03/2016 14:08, Jon Ribbens wrote: >>>> if you thought you needed to do that then most likely what you >>>> should actually be doing is re-writing your code so you no longer >>>> need to. However, you could do: >>>> >>>> L[:] = [0] * len(L) >>> >>> OK, but that's just building a new list as I've already mentioned. >> >> No it isn't, it's replacing the elements in-place, > > Replace them with what, if not an entirely new list built from > '[0]*len(L)'? (And which would briefly require twice the memory occupied > by the old list, if I'm not mistaken.) It's replacing them with elements from an entirely new list, which is then discarded, and only the original list remains. From random832 at fastmail.com Thu Mar 24 11:30:55 2016 From: random832 at fastmail.com (Random832) Date: Thu, 24 Mar 2016 11:30:55 -0400 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1458833455.3543894.558683386.0E36852A@webmail.messagingengine.com> On Thu, Mar 24, 2016, at 11:18, BartC wrote: > On 24/03/2016 15:03, Jon Ribbens wrote: > > No it isn't, it's replacing the elements in-place, > > Replace them with what, if not an entirely new list built from > '[0]*len(L)'? Well, the *contents* of such a list, obviously. But the original list's contents are replaced, meaning that e.g. all other references to the list remain valid etc. > (And which would briefly require twice the memory occupied > by the old list, if I'm not mistaken.) Sure, *briefly*. And if you really care about that, you can do L[:] = (0 for x in L); or itertools.repeat(0, len(L)). From ned at nedbatchelder.com Thu Mar 24 11:30:58 2016 From: ned at nedbatchelder.com (Ned Batchelder) Date: Thu, 24 Mar 2016 08:30:58 -0700 (PDT) Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: <96c17017-a658-4c0b-bbd5-b9d2ed982e1f@googlegroups.com> On Thursday, March 24, 2016 at 9:51:11 AM UTC-4, Steven D'Aprano wrote: > You know what is missing from this conversation? > > For one of Bart's critics to actually show faster code. > > There's plenty of people telling him off for writing unpythonic and slow > code, but I haven't seen anyone actually demonstrating that Python is > faster than his results show. As I mentioned before, I'm happy to explain the fuller Python way to write code, but I don't think Bart wants to learn it, because he is focused on a different goal than, "write real Python code the best possible way." Here, for example, is a real lexer for JavaScript that I wrote: https://bitbucket.org/ned/jslex/src It makes heavy use of regexes to go fast. I don't have benchmarks against other implementations unfortunately. --Ned. From tjreedy at udel.edu Thu Mar 24 12:01:45 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Mar 2016 12:01:45 -0400 Subject: Connect to Default Printer In-Reply-To: References: Message-ID: On 3/23/2016 8:39 PM, Bryon Fawcett wrote: > Could you please advise me how to connect the python software to my default > printer. IDLE prints to default printer with function print_window in idlelib/IOBinding.py. The two GetOption calls return these two strings (from config-main.def). For print-command-posix, 'lpr %s' For print-command-win, 'start /min notepad /p %s' You should be able to adapt to your needs. Perhaps you do not need the messageboxes. -- Terry Jan Reedy From bc at freeuk.com Thu Mar 24 12:12:33 2016 From: bc at freeuk.com (BartC) Date: Thu, 24 Mar 2016 16:12:33 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <96c17017-a658-4c0b-bbd5-b9d2ed982e1f@googlegroups.com> References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> <96c17017-a658-4c0b-bbd5-b9d2ed982e1f@googlegroups.com> Message-ID: On 24/03/2016 15:30, Ned Batchelder wrote: > On Thursday, March 24, 2016 at 9:51:11 AM UTC-4, Steven D'Aprano wrote: >> You know what is missing from this conversation? >> >> For one of Bart's critics to actually show faster code. >> >> There's plenty of people telling him off for writing unpythonic and slow >> code, but I haven't seen anyone actually demonstrating that Python is >> faster than his results show. > > As I mentioned before, I'm happy to explain the fuller Python way to > write code, but I don't think Bart wants to learn it, because he is > focused on a different goal than, "write real Python code the best > possible way." > > Here, for example, is a real lexer for JavaScript that I wrote: > https://bitbucket.org/ned/jslex/src > Thanks for that. I don't have any JS to throw at it, but it seems happy with any bits of source code or even just text. Using your short driver program (with the prints commented out), and tested with 'bible.txt' as input (ie. mostly English words), then your JS lexer was roughly half the speed of the Python version I linked to last week (with the if-elif chains and working with strings). Both tested with 2.7.x. Using PyPy speeded both versions up about 3 times. Your code however is more beautiful than mine... > It makes heavy use of regexes to go fast. I don't have benchmarks > against other implementations unfortunately. (A rough lines-per-second figure would give a general idea.) -- Bartc From best_lay at yahoo.com Thu Mar 24 12:19:52 2016 From: best_lay at yahoo.com (Wildman) Date: Thu, 24 Mar 2016 11:19:52 -0500 Subject: Key Binding Problem References: <06adnbnMouHI027LnZ2dnUU7-XednZ2d@giganews.com> Message-ID: On Thu, 24 Mar 2016 08:06:28 -0400, Dennis Lee Bieber wrote: > On Wed, 23 Mar 2016 21:17:57 -0500, Wildman via Python-list > declaimed the following: > >> >>I was referring to procedures called by a button click as >>opposed to a procedure calledd from elsewhere in the code. >>I guess there is no difference. I assume that is what you >>meant. > > I'd have to see /how/ it is called. The "button click" is an event > handled by the GUI framework, to which you've bound a handler. Such items > (which may be attached to resize, menu, text fields, etc.) would need the > structure the framework uses... So if a method of a class, that means a > first argument placeholder of "self", and most likely a second for some > "event" data structure. You'd have to check the documentation for what it > expects. > > callback by framework: theButton.pressed((clock, x, y)) > defined as: def pressed(self, event): > (granted, having the mouse x/y coordinates may not mean much for a > screen button) > > callback by framework: mouseHandler.move((clock, x, y, lmb, rmb, mmb)) > defined as: def move(self, event): > (xmb is left/right/middle mouse button state) > > > But if it is not being called by the framework, the arrangement/number > of arguments is under your control. If it is a method of a class instance, > it will receive the instance object as the first argument: > object.method(arglist) => method(self, arglist) {where self IS object}. I believe I understand. Thanks. If you can't tell, I'm new to Python so the learning process is on-going. -- GNU/Linux user #557453 The cow died so I don't need your bull! From neattyphoon11957 at gmail.com Thu Mar 24 12:21:29 2016 From: neattyphoon11957 at gmail.com (Niyoo *Unkown*) Date: Thu, 24 Mar 2016 12:21:29 -0400 Subject: Python Message-ID: The reason I uninstalled Python was because it was 32 bit not 64 bit and I couldn't find the 64 bit version. From alister.ware at ntlworld.com Thu Mar 24 12:27:04 2016 From: alister.ware at ntlworld.com (alister) Date: Thu, 24 Mar 2016 16:27:04 GMT Subject: Python References: Message-ID: On Thu, 24 Mar 2016 12:21:29 -0400, Niyoo *Unkown* wrote: > The reason I uninstalled Python was because it was 32 bit not 64 bit and > I couldn't find the 64 bit version. that's nice -- That which is not good for the swarm, neither is it good for the bee. From zachary.ware+pylist at gmail.com Thu Mar 24 12:38:28 2016 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Thu, 24 Mar 2016 11:38:28 -0500 Subject: Python In-Reply-To: References: Message-ID: On Thu, Mar 24, 2016 at 11:21 AM, Niyoo *Unkown* wrote: > The reason I uninstalled Python was because it was 32 bit not 64 bit and I > couldn't find the 64 bit version. Have a look at this page: https://www.python.org/downloads/windows/ The 64 bit versions are the "x86_64" ones. -- Zach From wxjmfauth at gmail.com Thu Mar 24 13:11:21 2016 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Thu, 24 Mar 2016 10:11:21 -0700 (PDT) Subject: newbie question In-Reply-To: References: <56f3c3eb$0$4546$426a74cc@news.free.fr> <56f3f16f$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: >>> s = "(1, 2, 3, 4)" >>> a = tuple([int(e) for e in s.strip('()').split(',')]) >>> a (1, 2, 3, 4) >>> From ned at nedbatchelder.com Thu Mar 24 13:13:51 2016 From: ned at nedbatchelder.com (Ned Batchelder) Date: Thu, 24 Mar 2016 10:13:51 -0700 (PDT) Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> <96c17017-a658-4c0b-bbd5-b9d2ed982e1f@googlegroups.com> Message-ID: <4444d120-f81c-4c22-818c-97be33ffeac4@googlegroups.com> On Thursday, March 24, 2016 at 12:12:55 PM UTC-4, BartC wrote: > On 24/03/2016 15:30, Ned Batchelder wrote: > > On Thursday, March 24, 2016 at 9:51:11 AM UTC-4, Steven D'Aprano wrote: > >> You know what is missing from this conversation? > >> > >> For one of Bart's critics to actually show faster code. > >> > >> There's plenty of people telling him off for writing unpythonic and slow > >> code, but I haven't seen anyone actually demonstrating that Python is > >> faster than his results show. > > > > As I mentioned before, I'm happy to explain the fuller Python way to > > write code, but I don't think Bart wants to learn it, because he is > > focused on a different goal than, "write real Python code the best > > possible way." > > > > Here, for example, is a real lexer for JavaScript that I wrote: > > https://bitbucket.org/ned/jslex/src > > > > Thanks for that. > > I don't have any JS to throw at it, but it seems happy with any bits of > source code or even just text. > > Using your short driver program (with the prints commented out), and > tested with 'bible.txt' as input (ie. mostly English words), then your > JS lexer was roughly half the speed of the Python version I linked to > last week (with the if-elif chains and working with strings). I have tried to find your code, but cannot find in the forest of this thread. Can you provide a link to it online? I would be very interested to understand the difference in performance. Thanks, --Ned. From steve at pearwood.info Thu Mar 24 13:27:05 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Mar 2016 04:27:05 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f4236c$0$1615$c3e8da3$5496439d@news.astraweb.com> On Fri, 25 Mar 2016 01:04 am, BartC wrote: > On 24/03/2016 13:50, Steven D'Aprano wrote: >> On Thu, 24 Mar 2016 02:24 pm, Chris Angelico wrote: >> >> >>> This is how you're currently evaluating Python. Instead of starting >>> with the most simple and obvious code >> >> One problem is that what counts as "simple and obvious" depends on what >> you are used to. Coming from a background of Pascal, iterating over a >> list like this: >> >> for i in range(len(mylist)): >> print mylist[i] >> >> was both simple and obvious. It took me years to break myself of that >> habit. >> >> Likewise clearing a list: >> >> for i in range(len(mylist)-1, -1, 0): >> del mylist[i] > > That's wouldn't be I'd call clearing a list, more like destroying it > completely! No, the list still exists, and mylist (the name) is still bound to it. It is just an empty list (length zero). > How would you actually clear a list by traversing it (ie. not just > building a new one)? The two "right ways" of clearing a list (i.e. setting it to an empty list) is to use slice assignment: mylist[:] = [] or call the mylist.clear() method. > This doesn't work: > > for x in L: > x=0 > > as each x only refers to the value in each element of L, not the element > itself (like the pass-by-reference problem). Correct, except I wouldn't call it a problem. That's just not how Python semantics work. I only know of a handful of languages that support pass-by-reference: Pascal C++ Visual Basic Some other Basics (maybe? I'm not sure) Algol (actually pass-by-name) > I'd presumably have to do: > > for i in range(len(L)): > L[i]=0 I wouldn't describe that as "clearing the list". It is merely setting the existing values to some known quantity which happens to be zero. Why zero? Why not None, or 99, or float("nan")? (Don't answer that, it's a rhetorical question.) In any case, I would expect that the most efficient way to set all the list values to a particular value would be: mylist[:] = [0]*len(mylist) Let's find out. On my computer, using Python 3.3: py> mylist = list(range(100000)) py> with Stopwatch(): ... mylist[:] = [0]*len(mylist) ... time taken: 0.005215 seconds Compared to: py> mylist = list(range(100000)) py> with Stopwatch(): ... for i in range(len(mylist)): ... mylist[i] = 0 ... time taken: 0.037431 seconds That's a difference of about an order of magnitude. The Stopwatch function used for timing is very nearly the same as the recipe posted here: https://code.activestate.com/recipes/577896-benchmark-code-with-the-with-statement/ -- Steven From steve at pearwood.info Thu Mar 24 13:44:00 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Mar 2016 04:44:00 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f42762$0$1603$c3e8da3$5496439d@news.astraweb.com> On Fri, 25 Mar 2016 01:16 am, BartC wrote: > Or is the Pythonic way, when you want to change some elements of a list > to just build a new one that incorporates those changes? If you are only changing a few elements, or one at a time in some random order, then just change the element. Lists have random access, so you can easily change a single item: mylist[975] = "Hello world" But if you intend to change the entire list, *in general* it is faster to create a new list and copy the items into the old list. This is called *slicing*, to be specific, we're assigning to a "slice" corresponding to the entire list: mylist[:] = newlist But we don't have to assign to the entire list. We can assign to a sublist: mylist[2:102] = newlist and mylist will shrink or expand as needed. It is most convenient to use the list replication operator * to build the new list: [0, 1]*100 # like [0, 1, 0, 1, 0, 1, 0, 1, ... , 0, 1] or a list comprehension: [i**2 for i in range(100)] # like [0**2, 1**2, 2**2, 3**3, 4**2, ... 99**2] But most of the time you might not even care about modifying the list in place. Why spend the time to copy the new list over? Just reassign the variable to the new list. mylist = [i**2 for i in range(100)] The difference between mylist = ... and mylist[:] = ... comes down to what happens to other references. Suppose you have some object with a list attribute: instance.data = [1, 2, 3] Now we bind that list to another name (say, you pass it to a function, where the list gets assigned to a local variable): mylist = instance.data mylist and instance.data both "point to" the same underlying list object. Modifications to one will be seen by the other, as they both refer to the same list. If you do mylist[:] = ... that is an in-place modification of the list, and will be seen by all references to that list. But if you do mylist = ... that is a binding operation, and it reassigns the name "mylist" without touching the list object itself, or the instance.data reference. Analogy: if Barack Obama cuts himself shaving, the POTUS will have the same cut, because they are one and the same person (at least for now). But in another year or so, if Obama cuts himself, the POTUS will not notice, because the name POTUS will have been rebound to a different person. -- Steven From srkunze at mail.de Thu Mar 24 13:47:49 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Thu, 24 Mar 2016 18:47:49 +0100 Subject: newbie question In-Reply-To: References: <56f3c3eb$0$4546$426a74cc@news.free.fr> <56F3CB1E.2000606@mail.de> Message-ID: <56F42845.6040800@mail.de> On 24.03.2016 14:22, Matt Wheeler wrote: > On Thu, 24 Mar 2016 11:10 Sven R. Kunze, wrote: > >> On 24.03.2016 11:57, Matt Wheeler wrote: >>>>>> import ast >>>>>> s = "(1, 2, 3, 4)" >>>>>> t = ast.literal_eval(s) >>>>>> t >>> (1, 2, 3, 4) >> I suppose that's the better solution in terms of safety. >> > It has the added advantage that the enquirer gets to import a module that > shares their name ;) One shouldn't underestimate this. ;-) From steve at pearwood.info Thu Mar 24 13:56:37 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Mar 2016 04:56:37 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f42a57$0$1611$c3e8da3$5496439d@news.astraweb.com> On Fri, 25 Mar 2016 02:03 am, Jon Ribbens wrote: > On 2016-03-24, BartC wrote: >> On 24/03/2016 14:08, Jon Ribbens wrote: >>> if you thought you needed to do that then most likely what you >>> should actually be doing is re-writing your code so you no longer >>> need to. However, you could do: >>> >>> L[:] = [0] * len(L) >> >> OK, but that's just building a new list as I've already mentioned. > > No it isn't, it's replacing the elements in-place, that's what the > "L[:]" bit means. Replacing the list object itself would be: > L = [0] * len(L) Yes it is: a new list is built, copied, then discarded. Python builds the [0]*len(L) list first, then copies the elements from it into the existing L (which in CPython is just a fast memcopy of a whole bunch of pointers, plus a resize of L), then garbage collects the new list. A *sufficiently smart* Python interpreter might be able to optimize that even further, but since it's just copying pointers from one array to another, it's already pretty quick. I imagine that, if you had enough memory, a *sufficiently enormous* list would actually be faster to modify in place using the Pascal-ish idiom: for i in range(len(L)): L[i] = 0 rather than building a temporary list and copying it. But I've never been able to demonstrate that: no matter how big a list I created, it was always faster to create a second one and then do slice assignment than to iterate over it in a for loop changing each item in place. This demonstrates that what logically ought to be more efficient (changing values in place) is not necessarily *actually* more efficient. -- Steven From bc at freeuk.com Thu Mar 24 14:03:33 2016 From: bc at freeuk.com (BartC) Date: Thu, 24 Mar 2016 18:03:33 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <4444d120-f81c-4c22-818c-97be33ffeac4@googlegroups.com> References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> <96c17017-a658-4c0b-bbd5-b9d2ed982e1f@googlegroups.com> <4444d120-f81c-4c22-818c-97be33ffeac4@googlegroups.com> Message-ID: On 24/03/2016 17:13, Ned Batchelder wrote: > On Thursday, March 24, 2016 at 12:12:55 PM UTC-4, BartC wrote: >> On 24/03/2016 15:30, Ned Batchelder wrote: >>> On Thursday, March 24, 2016 at 9:51:11 AM UTC-4, Steven D'Aprano wrote: >>>> You know what is missing from this conversation? >>>> >>>> For one of Bart's critics to actually show faster code. >>>> >>>> There's plenty of people telling him off for writing unpythonic and slow >>>> code, but I haven't seen anyone actually demonstrating that Python is >>>> faster than his results show. >>> >>> As I mentioned before, I'm happy to explain the fuller Python way to >>> write code, but I don't think Bart wants to learn it, because he is >>> focused on a different goal than, "write real Python code the best >>> possible way." >>> >>> Here, for example, is a real lexer for JavaScript that I wrote: >>> https://bitbucket.org/ned/jslex/src >>> >> >> Thanks for that. >> >> I don't have any JS to throw at it, but it seems happy with any bits of >> source code or even just text. >> >> Using your short driver program (with the prints commented out), and >> tested with 'bible.txt' as input (ie. mostly English words), then your >> JS lexer was roughly half the speed of the Python version I linked to >> last week (with the if-elif chains and working with strings). > > I have tried to find your code, but cannot find in the forest of this thread. > Can you provide a link to it online? I would be very interested to understand > the difference in performance. This the version I used today: http://pastebin.com/dtM8WnFZ (others I've experimented with aren't much faster or slower.) Testing it with lots of C source, the difference is narrower. (Note that the two will be doing different jobs; one or two things are not complete on mine, such as the final calculation for floating point literals. And the number of tokens read is a bit different. But then they are expecting a different language. Also, I only tested with large monolithic files (to make measuring easier). In terms of getting through the same amount of input however, I think the comparisons aren't too far off.) This is the test code I used for your JS lexer: """A main program for jslex.""" import sys from jslex import JsLexer def show_js_tokens(jstext, ws=False): line = 1 lexer = JsLexer() n=0 for name, tok in lexer.lex(jstext): n+=1 # print_it = True # if name == 'ws' and not ws: # print_it = False # if print_it: # print "%4d %s: %r" % (line, name, tok) line += tok.count("\n") print line,n if __name__ == '__main__': file="bigpy" # file="sqlite" # file="bible.txt" show_js_tokens(open(file).read()) -- Bartc From steve at pearwood.info Thu Mar 24 14:10:35 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Mar 2016 05:10:35 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> On Fri, 25 Mar 2016 12:01 am, BartC wrote: > But there are all sorts of micro-micro-benchmarks that can concentrate > on a single byte-code. For example, how long does it take to call an > empty function with no parameters? Just putting such a call into a > simple loop can be effective: > > Python 3 (on Windows) might take 200ns. Clisp is 1300ns (interpreted, > presumably). Ruby 170ns. Lua 80ns. Mine 10-20ns. Unoptimised C is 4ns, > but this is not executing code indirectly as most of the rest have to. "Might"? Are you making those numbers up? > [Timings include loop overheads that need to be factored out.] Then those numbers are pointless. The Python figure, for example, might be 199ns for the loop overhead and 1ns for the function call, or 1ns for the loop overhead and 199ns for the function call. Or anything in between. How do you know which is which? > So there might be room for improvement, but those faster languages are > also simpler. Right. Let's compare two almost identical looking lines in Python and C: y = x + 1 y = x + 1; Apart from the semi-colon, they do exactly the same thing, right? Well, no. Not even close. In the case of C, the line is limited to working with some specific type (say, an int32). Even there, if the addition might overflow, the behaviour is undefined and the compiler can do anything it wants (including time travel, or erasing your hard disk). In the case of Python, the line will work with a potentially infinite number of types: int, float, complex, Fraction, Decimal, subclasses of all the above, custom numeric types, and anything else that quacks like a number. There's no undefined behaviour: at worst, you will get an exception. There's no integer overflow: you can set x = 10**100 and add one to it, and the result will be mathematically exact. Even though the two lines *look* the same, they are as different as chalk and cheese. If you wrote C code that had the same semantics as the Python code, chances are it wouldn't be much faster than Python. This shouldn't be surprising. Python, or at least the standard CPython interpreter, is written in C. It is, effectively, a DSL ("Domain Specific Language") for C: all the things which are hard in C, like memory management, polymorphic code, not segfaulting, etc., are handled for you. So yes, faster languages are often simpler. They are fast because they do less. As the saying goes, the fastest code is the code that isn't run. > Is Python's richness or dynamism the main factor here? If > so there is probably little to be done; if not... This is where the fun > starts. > > But I understand that most people aren't interested in this kind of sport. Checkout the benchmark game: http://benchmarksgame.alioth.debian.org/ -- Steven From alister.ware at ntlworld.com Thu Mar 24 14:14:56 2016 From: alister.ware at ntlworld.com (alister) Date: Thu, 24 Mar 2016 18:14:56 GMT Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, 24 Mar 2016 14:04:53 +0000, BartC wrote: > On 24/03/2016 13:50, Steven D'Aprano wrote: >> On Thu, 24 Mar 2016 02:24 pm, Chris Angelico wrote: >> >> >>> This is how you're currently evaluating Python. Instead of starting >>> with the most simple and obvious code >> >> One problem is that what counts as "simple and obvious" depends on what >> you are used to. Coming from a background of Pascal, iterating over a >> list like this: >> >> for i in range(len(mylist)): >> print mylist[i] >> >> was both simple and obvious. It took me years to break myself of that >> habit. >> >> Likewise clearing a list: >> >> for i in range(len(mylist)-1, -1, 0): >> del mylist[i] > > That's wouldn't be I'd call clearing a list, more like destroying it > completely! > > How would you actually clear a list by traversing it (ie. not just > building a new one)? > > This doesn't work: > > for x in L: > x=0 > > as each x only refers to the value in each element of L, not the element > itself (like the pass-by-reference problem). > > I'd presumably have to do: > > for i in range(len(L)): > L[i]=0 close I would suggest the following pastern is more "Pythonic" although possibly overkill for this scenario a=[1,2,3,4,5] for i,x in enumerate(a): a[i]=None -- Practice yourself what you preach. -- Titus Maccius Plautus From alister.ware at ntlworld.com Thu Mar 24 14:30:59 2016 From: alister.ware at ntlworld.com (alister) Date: Thu, 24 Mar 2016 18:30:59 GMT Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, 24 Mar 2016 14:28:32 +0000, BartC wrote: > On 24/03/2016 14:01, Chris Angelico wrote: > >> I don't, until it's pointed out. At that point, someone who respects >> the language will at least pay *some* heed to the changed >> recommendations; what we're seeing here is that he continues to use C >> idioms and then complain that Python is slow. I don't expect him to >> magically know what Python idioms are, but when the thread has gone on >> this long and he's still showing the same style of code, that's when I >> start to agree with Ben that he's not paying heed to Pythonic vs >> non-Pythonic. > > Have a look at the short thread 'Rotation' in comp.programming starting > 4-Jan-2016. > > (Possible link: > https://groups.google.com/forum/#!searchin/comp.programming/rotation/ comp.programming/aQh4n2HGtaU/sSbcyjqfEQAJ) > > Someone posts an algorithm in C++, I post a version in my language, > someone else calls that a 'blub' solution and offers a much shorter > version in /their/ language. > > I point out that their solution just uses a built-in to do the work. It > by-passes the question of the algorithm, which was the point of the > thread. I also point out that I also gave a one-line version in my > language. > > What you're trying to say I guess is that such a one-liner would be > Pythonic. And what I'm saying is that that would defeat the object of > what I'm trying to do. if you're trying to demonstrate the deficiency of one algorithm over another then you should be testing them in the same language. If you are trying to compare one language to another then the task should be written in the most efficient means for then language. language "A" has a builtin function "X" where as language "B" does not, that just shows that "A" is better suited to the task than "B", "B" probably has other areas where "A" is not so good. otherwise why not wright in assembler/machine code which has to be the most efficient language (because all the others eventually fall back to executing these processor instructions anyway -- We're constantly being bombarded by insulting and humiliating music, which people are making for you the way they make those Wonder Bread products. Just as food can be bad for your system, music can be bad for your spirtual and emotional feelings. It might taste good or clever, but in the long run, it's not going to do anything for you. -- Bob Dylan, "LA Times", September 5, 1984 From jon+usenet at unequivocal.co.uk Thu Mar 24 15:07:42 2016 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Thu, 24 Mar 2016 19:07:42 -0000 (UTC) Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> <56f42a57$0$1611$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2016-03-24, Steven D'Aprano wrote: > On Fri, 25 Mar 2016 02:03 am, Jon Ribbens wrote: >> On 2016-03-24, BartC wrote: >>> On 24/03/2016 14:08, Jon Ribbens wrote: >>>> if you thought you needed to do that then most likely what you >>>> should actually be doing is re-writing your code so you no longer >>>> need to. However, you could do: >>>> >>>> L[:] = [0] * len(L) >>> >>> OK, but that's just building a new list as I've already mentioned. >> >> No it isn't, it's replacing the elements in-place, that's what the >> "L[:]" bit means. Replacing the list object itself would be: >> L = [0] * len(L) > > Yes it is: a new list is built, copied, then discarded. Obviously (as already mentioned in my earlier reply). But the point is that it is not "just building a new list", as if that were true then L would not be pointing to the same list afterwards. From torriem at gmail.com Thu Mar 24 15:49:44 2016 From: torriem at gmail.com (Michael Torrie) Date: Thu, 24 Mar 2016 13:49:44 -0600 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e44258$0$1598$c3e8da3$5496439d@news.astraweb.com> <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56F444D8.9010200@gmail.com> On 03/21/2016 06:43 AM, BartC wrote: > On 21/03/2016 12:08, Ned Batchelder wrote: >> On Sunday, March 20, 2016 at 9:15:32 PM UTC-4, BartC wrote: >>> >>> A tokeniser along those lines in Python, with most of the bits filled >>> in, is here: >>> >>> http://pastebin.com/dtM8WnFZ >>> >> >> Bart, we get it: you don't like the trade-offs that Python has made. > ... >> You don't like Python. Can we leave it at that? > > On the contrary, I do like it. It's just a shame it's made those > trade-offs as a bit more speed would have made it more useful to me. Have you looked at compiled, python-inspired languages like Num (http://nim-lang.org/). If it's syntax you like and some other Python things like for the for loop works, maybe something like this would be useful to you. From bc at freeuk.com Thu Mar 24 15:54:54 2016 From: bc at freeuk.com (BartC) Date: Thu, 24 Mar 2016 19:54:54 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 24/03/2016 18:10, Steven D'Aprano wrote: > On Fri, 25 Mar 2016 12:01 am, BartC wrote: >> Python 3 (on Windows) might take 200ns. Clisp is 1300ns (interpreted, >> presumably). Ruby 170ns. Lua 80ns. Mine 10-20ns. Unoptimised C is 4ns, >> but this is not executing code indirectly as most of the rest have to. > > "Might"? Are you making those numbers up? No. >> [Timings include loop overheads that need to be factored out.] > > Then those numbers are pointless. Yes, they would need some adjustment to do this stuff properly. FWIW the loop overheads were about 30% in Python, 40% in Ruby, and 20% in mine. > The Python figure, for example, might be > 199ns for the loop overhead and 1ns for the function call, or 1ns for the > loop overhead and 199ns for the function call. Or anything in between. How > do you know which is which? It sounds like they would both need some work! >> So there might be room for improvement, but those faster languages are >> also simpler. > In the case of C, the line is limited to working with some specific type > (say, an int32). Even there, if the addition might overflow, the behaviour > is undefined and the compiler can do anything it wants (including time > travel, I'm pretty sure it can't do time travel... or erasing your hard disk). > > In the case of Python, the line will work with a potentially infinite number > of types: int, float, complex, Fraction, Decimal, subclasses of all the > above, custom numeric types, and anything else that quacks like a number. Yes, it has to do some dynamic type dispatch. All the languages except C were dynamic (C cheats in so many ways). However, my bit of code (a for-loop calling an empty function) doesn't on the surface, do anything that requires type dispatch, or does it? This is where we come to the first differences between how Python works and how, say, my language works (I don't know about Lua, Ruby and Lisp.) Python bytecode for empty function bill(): 4 0 LOAD_CONST 0 (None) 3 RETURN_VALUE Inner loop calling bill(): >> 13 FOR_ITER 13 (to 29) 16 STORE_FAST 0 (n) 8 19 LOAD_GLOBAL 1 (bill) 22 CALL_FUNCTION 0 (0 positional... ) 25 POP_TOP 26 JUMP_ABSOLUTE 13 My bytecode for function bill(): 0: 000 --------- return My inner loop bytecode: 1: 005 %4: 1: 006 --------- call [&t.bill], 0 1: 006 --------- to_f %4, [t.start.av$1:-1] Half the explanation is right here: I use 1 op in the function, and 2 in the loop. Python uses 2 in the function, and 6 in the loop. (I use a dedicated repeat-N-times loop that needs no explicit loop variable, only an internal integer count. I use a special 'proc' form of function with no return value. And I use static functions so the byte-code knows the function being called, and knows it returns no value that needs to be popped.) -- Bartc From kevind0718 at gmail.com Thu Mar 24 16:24:16 2016 From: kevind0718 at gmail.com (kevind0718 at gmail.com) Date: Thu, 24 Mar 2016 13:24:16 -0700 (PDT) Subject: Tkinter --> Why multiple windows Message-ID: Hello: newbie Tkinter question If I run the code below two windows appear. One empty and one with the text box and button. Why? please KD from Tkinter import * class MyDialog: def __init__(self, parent): top = self.top = Toplevel(parent) Label(top, text="Value").pack() self.e = Entry(top) self.e.pack(padx=5) b = Button(top, text="OK", command=self.ok) b.pack(pady=5) def ok(self): print "value is", self.e.get() self.top.destroy() root = Tk() d = MyDialog(root) root.wait_window(d.top) From random832 at fastmail.com Thu Mar 24 16:28:42 2016 From: random832 at fastmail.com (Random832) Date: Thu, 24 Mar 2016 16:28:42 -0400 Subject: Tkinter --> Why multiple windows In-Reply-To: References: Message-ID: <1458851322.3611164.558965098.4D521DBE@webmail.messagingengine.com> On Thu, Mar 24, 2016, at 16:24, kevind0718 at gmail.com wrote: > Hello: > > newbie Tkinter question > > If I run the code below two windows appear. > One empty and one with the text box and button. The empty one is the root window. From kevind0718 at gmail.com Thu Mar 24 16:43:23 2016 From: kevind0718 at gmail.com (kevind0718 at gmail.com) Date: Thu, 24 Mar 2016 13:43:23 -0700 (PDT) Subject: Tkinter --> Why multiple windows In-Reply-To: References: Message-ID: On Thursday, March 24, 2016 at 4:29:03 PM UTC-4, Random832 wrote: > On Thu, Mar 24, 2016, at 16:24, kevind0718 at gmail.com wrote: > > Hello: > > > > newbie Tkinter question > > > > If I run the code below two windows appear. > > One empty and one with the text box and button. > > The empty one is the root window. I kinda guessed that. Is there any downside to hiding it using root.withdraw(). thanks for quick responce. KD From cl at isbd.net Thu Mar 24 16:53:23 2016 From: cl at isbd.net (cl at isbd.net) Date: Thu, 24 Mar 2016 20:53:23 +0000 Subject: [OT'ish] Is there a list as good as this for Javascript Message-ID: <3n0esc-r3p.ln1@esprimo.zbmc.eu> I use Python wherever I can and find this list (as a usenet group via gmane) an invaluable help at times. Occasionally I have to make forays into Javascript, can anyone recommend a place similar to this list where Javascript questions can be asked? The trouble is that there are very many usenet Javascript lists and it's difficult to guess which one[es] might be good. -- Chris Green ? From invalid at invalid.invalid Thu Mar 24 17:47:41 2016 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 24 Mar 2016 21:47:41 +0000 (UTC) Subject: [OT'ish] Is there a list as good as this for Javascript References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> Message-ID: On 2016-03-24, cl at isbd.net wrote: > I use Python wherever I can and find this list (as a usenet group > via gmane) an invaluable help at times. > > Occasionally I have to make forays into Javascript, can anyone > recommend a place similar to this list where Javascript questions > can be asked? Are you asking about 1) Javascript itself (the language)? 2) jQuery or some other client-side framework? 3) The DOM model and API provided by various web browsers? In most forums 99% of the threads are about 2 and 3. > The trouble is that there are very many usenet Javascript lists and > it's difficult to guess which one[es] might be good. That's a tough one. I dabble in Javascript in order to support the Web UI's on some of the embedded products I work on, and I've yet to find a high quality forum for Javascript questions. Javascript programing seems to be dominated by cargo-cult programmers with little understanding of the language. They just sort of cut-n-paste code snippets they find online and then hope. It's not quite as bad as PHP in that regard, but that's not saying mutch. [IMO, the design of the Javascript language itself is _far_ better than the "design" of the PHP language, and that the results of cargo-cult programming in Javascript usually turn out better than they do in PHP.] If you do find anything like c.l.p for Javascript, let us know... -- Grant Edwards grant.b.edwards Yow! I'm sitting on my at SPEED QUEEN ... To me, gmail.com it's ENJOYABLE ... I'm WARM ... I'm VIBRATORY ... From cl at isbd.net Thu Mar 24 18:08:41 2016 From: cl at isbd.net (cl at isbd.net) Date: Thu, 24 Mar 2016 22:08:41 +0000 Subject: [OT'ish] Is there a list as good as this for Javascript References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> Message-ID: <945esc-qkp.ln1@esprimo.zbmc.eu> Grant Edwards wrote: > On 2016-03-24, cl at isbd.net wrote: > > > I use Python wherever I can and find this list (as a usenet group > > via gmane) an invaluable help at times. > > > > Occasionally I have to make forays into Javascript, can anyone > > recommend a place similar to this list where Javascript questions > > can be asked? > > Are you asking about > > 1) Javascript itself (the language)? > Probably mostly this. > 2) jQuery or some other client-side framework? > A little of this, but not much. > 3) The DOM model and API provided by various web browsers? > Not this. > In most forums 99% of the threads are about 2 and 3. > > > The trouble is that there are very many usenet Javascript lists and > > it's difficult to guess which one[es] might be good. > > That's a tough one. I dabble in Javascript in order to support the > Web UI's on some of the embedded products I work on, and I've yet to > find a high quality forum for Javascript questions. Javascript > programing seems to be dominated by cargo-cult programmers with little > understanding of the language. They just sort of cut-n-paste code > snippets they find online and then hope. It's not quite as bad as PHP > in that regard, but that's not saying mutch. [IMO, the design of the > Javascript language itself is _far_ better than the "design" of the > PHP language, and that the results of cargo-cult programming in > Javascript usually turn out better than they do in PHP.] > Yes, it seems that the 'right way' in Javascript is often almost the opposite of the 'right way' in other langueages. Optimise at the expense of readability seems to be the main aim. > If you do find anything like c.l.p for Javascript, let us know... > OK! :-) -- Chris Green ? From breamoreboy at yahoo.co.uk Thu Mar 24 18:18:57 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 24 Mar 2016 22:18:57 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 24/03/2016 19:54, BartC wrote: > On 24/03/2016 18:10, Steven D'Aprano wrote: >> On Fri, 25 Mar 2016 12:01 am, BartC wrote: > >> >> Then those numbers are pointless. > > Yes, they would need some adjustment to do this stuff properly. Please give up before you get sued by the families of the people who have died laughing. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at yahoo.co.uk Thu Mar 24 18:31:24 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 24 Mar 2016 22:31:24 +0000 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: <945esc-qkp.ln1@esprimo.zbmc.eu> References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <945esc-qkp.ln1@esprimo.zbmc.eu> Message-ID: On 24/03/2016 22:08, cl at isbd.net wrote: > >> If you do find anything like c.l.p for Javascript, let us know... >> > OK! :-) > I'd try c.l.bartc as he is the world's leading expert on everything that you need to know about any language, whereby the only thing to know is how fast is it. It's just fantastic, you don't have to bother about the source code that you write, all you have to bother about is the underlying byte code. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at yahoo.co.uk Thu Mar 24 18:43:15 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 24 Mar 2016 22:43:15 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <8737rgnepk.fsf@elektro.pacujo.net> Message-ID: On 24/03/2016 14:37, Rustom Mody wrote: > On Thursday, March 24, 2016 at 7:46:55 PM UTC+5:30, Marko Rauhamaa wrote: >> BartC : >> >>> And forgetting Python for a minute and concentrating only on its >>> byte-code as a language in its own right, how would you go about the >>> job of streamlining it? > >> Really, your optimization efforts should concentrate not on bytecode but >> on runtime data structures, algorithms, heuristics, equivalence >> transformations, reachability analysis, profiling and such. > > 'A' is a scientific programmer; he optimizes his scientific programs > 'C' is a financial programmer; he optimizes his finance programs > 'B(art)' is a bytecode-interpreter programmer; How does he optimize his bytecode > interpreters? > 'A' makes sure as best they can that their program is correct. 'C' makes sure as best they can that their program is correct. 'B' doesn't care provided it is quick. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at yahoo.co.uk Thu Mar 24 18:43:51 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 24 Mar 2016 22:43:51 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: Message-ID: On 12/03/2016 01:16, BartC wrote: Please go and play with this. https://www.ibm.com/developerworks/community/blogs/jfp/entry/A_Comparison_Of_C_Julia_Python_Numba_Cython_Scipy_and_BLAS_on_LU_Factorization?lang=en -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From cl at isbd.net Thu Mar 24 18:45:29 2016 From: cl at isbd.net (cl at isbd.net) Date: Thu, 24 Mar 2016 22:45:29 +0000 Subject: [OT'ish] Is there a list as good as this for Javascript References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <945esc-qkp.ln1@esprimo.zbmc.eu> Message-ID: <997esc-rvp.ln1@esprimo.zbmc.eu> Mark Lawrence wrote: > On 24/03/2016 22:08, cl at isbd.net wrote: > > > >> If you do find anything like c.l.p for Javascript, let us know... > >> > > OK! :-) > > > > I'd try c.l.bartc as he is the world's leading expert on everything that > you need to know about any language, whereby the only thing to know is > how fast is it. It's just fantastic, you don't have to bother about the > source code that you write, all you have to bother about is the > underlying byte code. > Many a true word..... -- Chris Green ? From rosuav at gmail.com Thu Mar 24 18:49:41 2016 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 25 Mar 2016 09:49:41 +1100 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <945esc-qkp.ln1@esprimo.zbmc.eu> Message-ID: On Fri, Mar 25, 2016 at 9:31 AM, Mark Lawrence wrote: > On 24/03/2016 22:08, cl at isbd.net wrote: >> >> >>> If you do find anything like c.l.p for Javascript, let us know... >>> >> OK! :-) >> > > I'd try c.l.bartc as he is the world's leading expert on everything that you > need to know about any language, whereby the only thing to know is how fast > is it. It's just fantastic, you don't have to bother about the source code > that you write, all you have to bother about is the underlying byte code. Enough. You don't need to drag this into arbitrary threads. ChrisA From breamoreboy at yahoo.co.uk Thu Mar 24 18:58:06 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 24 Mar 2016 22:58:06 +0000 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <945esc-qkp.ln1@esprimo.zbmc.eu> Message-ID: On 24/03/2016 22:49, Chris Angelico wrote: > On Fri, Mar 25, 2016 at 9:31 AM, Mark Lawrence wrote: >> On 24/03/2016 22:08, cl at isbd.net wrote: >>> >>> >>>> If you do find anything like c.l.p for Javascript, let us know... >>>> >>> OK! :-) >>> >> >> I'd try c.l.bartc as he is the world's leading expert on everything that you >> need to know about any language, whereby the only thing to know is how fast >> is it. It's just fantastic, you don't have to bother about the source code >> that you write, all you have to bother about is the underlying byte code. > > Enough. You don't need to drag this into arbitrary threads. > > ChrisA > No. While this idiot, BartC, is let loose on this forum, I'll say what I like. It is quite clear that he hasn't got the faintest idea, and the sooner he is kicked into touch, like the RUE, the better for the Python community. "I'll just factor out the loop in this test". Yeah, right. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at yahoo.co.uk Thu Mar 24 19:06:41 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 24 Mar 2016 23:06:41 +0000 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: <997esc-rvp.ln1@esprimo.zbmc.eu> References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <945esc-qkp.ln1@esprimo.zbmc.eu> <997esc-rvp.ln1@esprimo.zbmc.eu> Message-ID: On 24/03/2016 22:45, cl at isbd.net wrote: > Mark Lawrence wrote: >> On 24/03/2016 22:08, cl at isbd.net wrote: >>> >>>> If you do find anything like c.l.p for Javascript, let us know... >>>> >>> OK! :-) >>> >> >> I'd try c.l.bartc as he is the world's leading expert on everything that >> you need to know about any language, whereby the only thing to know is >> how fast is it. It's just fantastic, you don't have to bother about the >> source code that you write, all you have to bother about is the >> underlying byte code. >> > Many a true word..... > I wasn't jesting. BartC is a complete insult to the entire Python community, and I find it quite staggering that he has been allowed to spew his complete cobblers for so long and get away with it. It is so blatantly obvious that he knows precisely nothing about Python, but still the moderators on this list let him get away with it. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From joel.goldstick at gmail.com Thu Mar 24 19:09:12 2016 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 24 Mar 2016 19:09:12 -0400 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <945esc-qkp.ln1@esprimo.zbmc.eu> <997esc-rvp.ln1@esprimo.zbmc.eu> Message-ID: On Thu, Mar 24, 2016 at 7:06 PM, Mark Lawrence wrote: > On 24/03/2016 22:45, cl at isbd.net wrote: > >> Mark Lawrence wrote: >> >>> On 24/03/2016 22:08, cl at isbd.net wrote: >>> >>>> >>>> If you do find anything like c.l.p for Javascript, let us know... >>>>> >>>>> OK! :-) >>>> >>>> >>> I'd try c.l.bartc as he is the world's leading expert on everything that >>> you need to know about any language, whereby the only thing to know is >>> how fast is it. It's just fantastic, you don't have to bother about the >>> source code that you write, all you have to bother about is the >>> underlying byte code. >>> >>> Many a true word..... >> >> > I wasn't jesting. BartC is a complete insult to the entire Python > community, and I find it quite staggering that he has been allowed to spew > his complete cobblers for so long and get away with it. It is so blatantly > obvious that he knows precisely nothing about Python, but still the > moderators on this list let him get away with it. > > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence > > -- > https://mail.python.org/mailman/listinfo/python-list > at least ferous cranis is gone! -- Joel Goldstick http://joelgoldstick.com/ http://cc-baseballstats.info/ From ian.g.kelly at gmail.com Thu Mar 24 19:33:25 2016 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 24 Mar 2016 17:33:25 -0600 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <945esc-qkp.ln1@esprimo.zbmc.eu> Message-ID: On Thu, Mar 24, 2016 at 4:58 PM, Mark Lawrence wrote: > No. While this idiot, BartC, is let loose on this forum, I'll say what I > like. Good to know. I've been on the fence about this for a long time, but lately the frequency of your outbursts seems to have increased, and you're being more of a nuisance to this list than the people whom you're complaining about. *plonk* From breamoreboy at yahoo.co.uk Thu Mar 24 19:46:14 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 24 Mar 2016 23:46:14 +0000 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <945esc-qkp.ln1@esprimo.zbmc.eu> Message-ID: On 24/03/2016 23:33, Ian Kelly wrote: > On Thu, Mar 24, 2016 at 4:58 PM, Mark Lawrence wrote: >> No. While this idiot, BartC, is let loose on this forum, I'll say what I >> like. > > Good to know. I've been on the fence about this for a long time, but > lately the frequency of your outbursts seems to have increased, and > you're being more of a nuisance to this list than the people whom > you're complaining about. > > *plonk* > I just love it. A complete moron like BartC insults the Python community day in, day out, yet I'm the problem? When he can actually write a decent line of Python code and avoid discussing speed I'll think about him as a professional programmer. I cannot see this happening when all he talks about is byte code. He's clearly never read anything like Steve Maguire's "Writing Solid Code". -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From larry.martell at gmail.com Thu Mar 24 20:25:06 2016 From: larry.martell at gmail.com (Larry Martell) Date: Thu, 24 Mar 2016 20:25:06 -0400 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: <3n0esc-r3p.ln1@esprimo.zbmc.eu> References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> Message-ID: On Thu, Mar 24, 2016 at 4:53 PM, wrote: > I use Python wherever I can and find this list (as a usenet group via > gmane) an invaluable help at times. > > Occasionally I have to make forays into Javascript, can anyone > recommend a place similar to this list where Javascript questions can > be asked? The trouble is that there are very many usenet Javascript > lists and it's difficult to guess which one[es] might be good. I don't know of any JS specific mailing lists. When I have a JS question I usually use stackoverflow. But there is also the web design mailing list, which will accept JS questions. See http://www.webdesign-l.com/ For jQuery questions I use the jquery forum - http://forum.jquery.com/ From ned at nedbatchelder.com Thu Mar 24 20:30:45 2016 From: ned at nedbatchelder.com (Ned Batchelder) Date: Thu, 24 Mar 2016 17:30:45 -0700 (PDT) Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f3f09a$0$1595$c3e8da3$5496439d@news.astraweb.com> <96c17017-a658-4c0b-bbd5-b9d2ed982e1f@googlegroups.com> <4444d120-f81c-4c22-818c-97be33ffeac4@googlegroups.com> Message-ID: <9b04020c-aa0f-4d6b-bfd3-4a1009caacac@googlegroups.com> On Thursday, March 24, 2016 at 2:03:58 PM UTC-4, BartC wrote: > On 24/03/2016 17:13, Ned Batchelder wrote: > > On Thursday, March 24, 2016 at 12:12:55 PM UTC-4, BartC wrote: > >> On 24/03/2016 15:30, Ned Batchelder wrote: > >>> On Thursday, March 24, 2016 at 9:51:11 AM UTC-4, Steven D'Aprano wrote: > >>>> You know what is missing from this conversation? > >>>> > >>>> For one of Bart's critics to actually show faster code. > >>>> > >>>> There's plenty of people telling him off for writing unpythonic and slow > >>>> code, but I haven't seen anyone actually demonstrating that Python is > >>>> faster than his results show. > >>> > >>> As I mentioned before, I'm happy to explain the fuller Python way to > >>> write code, but I don't think Bart wants to learn it, because he is > >>> focused on a different goal than, "write real Python code the best > >>> possible way." > >>> > >>> Here, for example, is a real lexer for JavaScript that I wrote: > >>> https://bitbucket.org/ned/jslex/src > >>> > >> > >> Thanks for that. > >> > >> I don't have any JS to throw at it, but it seems happy with any bits of > >> source code or even just text. > >> > >> Using your short driver program (with the prints commented out), and > >> tested with 'bible.txt' as input (ie. mostly English words), then your > >> JS lexer was roughly half the speed of the Python version I linked to > >> last week (with the if-elif chains and working with strings). > > > > I have tried to find your code, but cannot find in the forest of this thread. > > Can you provide a link to it online? I would be very interested to understand > > the difference in performance. > > This the version I used today: > > http://pastebin.com/dtM8WnFZ > Thanks. It is faster than mine. The lesson I learned is, if you (I) make regexes too fancy, they are slower than the low-tech way. :) I suspect there is a way to use the re module more efficiently, but I don't have the time at the moment to figure out how. --Ned. From ned at nedbatchelder.com Thu Mar 24 20:38:27 2016 From: ned at nedbatchelder.com (Ned Batchelder) Date: Thu, 24 Mar 2016 17:38:27 -0700 (PDT) Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <945esc-qkp.ln1@esprimo.zbmc.eu> Message-ID: <4ed51a02-381e-4e1b-b3c1-64a5ffeaac4e@googlegroups.com> On Thursday, March 24, 2016 at 7:47:34 PM UTC-4, Mark Lawrence wrote: > On 24/03/2016 23:33, Ian Kelly wrote: > > On Thu, Mar 24, 2016 at 4:58 PM, Mark Lawrence wrote: > >> No. While this idiot, BartC, is let loose on this forum, I'll say what I > >> like. > > > > Good to know. I've been on the fence about this for a long time, but > > lately the frequency of your outbursts seems to have increased, and > > you're being more of a nuisance to this list than the people whom > > you're complaining about. > > > > *plonk* > > > > I just love it. A complete moron like BartC insults the Python > community day in, day out, yet I'm the problem? When he can actually > write a decent line of Python code and avoid discussing speed I'll think > about him as a professional programmer. I cannot see this happening > when all he talks about is byte code. He's clearly never read anything > like Steve Maguire's "Writing Solid Code". Yes Mark, you are a problem. You insult people personally. There is no need for that. BartC is a challenge, I agree, but he has not said anything personal against you or anyone else. Stop making personal attacks. Find another way to deal with your frustration. The Python Code of Conduct says to treat people with respect. You aren't doing that. I know you feel like Bart has been disrespectful by dragging out threads and ignoring important parts of the Python language. I agree, that is frustrating, but it different than making personal insults. Stop it. You are hurting this list and you are hurting Python. --Ned. From sukh222 at yahoo.com Thu Mar 24 21:17:43 2016 From: sukh222 at yahoo.com (121sukha) Date: Thu, 24 Mar 2016 18:17:43 -0700 (PDT) Subject: Web Scraping Message-ID: I am new to python and I want to use web scraping to download songs from website. how do I write code to check if the website has uploaded a new song and have that song automatically be downloaded onto my computer. I know how to use the requests.get() module but i am more interested in knowing how to download and save every new song that the website uploads on the site. I would extremely appreciate the help from anyone. Thanks! From best_lay at yahoo.com Thu Mar 24 21:24:33 2016 From: best_lay at yahoo.com (Wildman) Date: Thu, 24 Mar 2016 20:24:33 -0500 Subject: Tkinter --> Why multiple windows References: Message-ID: On Thu, 24 Mar 2016 13:24:16 -0700, kevind0718 wrote: > Hello: > > newbie Tkinter question > > If I run the code below two windows appear. > One empty and one with the text box and button. > > Why? please > > KD > > > > from Tkinter import * > > class MyDialog: > def __init__(self, parent): > > top = self.top = Toplevel(parent) > > Label(top, text="Value").pack() > > self.e = Entry(top) > self.e.pack(padx=5) > > b = Button(top, text="OK", command=self.ok) > b.pack(pady=5) > > def ok(self): > > print "value is", self.e.get() > > self.top.destroy() > > > root = Tk() > > d = MyDialog(root) > > root.wait_window(d.top) Try this: from Tkinter import * class MyDialog(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.pack(fill=BOTH, expand=1) self.parent.title("MyDialog") Label(self, text="Value").pack() self.e = Entry(self) self.e.pack(padx=5) self.b = Button(self, text="OK", command=self.ok) self.b.pack(pady=5) def ok(self): print "value is", self.e.get() root = Tk() d = MyDialog(root) root.mainloop() -- GNU/Linux user #557453 May the Source be with you. From tjreedy at udel.edu Thu Mar 24 21:27:48 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Mar 2016 21:27:48 -0400 Subject: Tkinter --> Why multiple windows In-Reply-To: References: Message-ID: On 3/24/2016 4:43 PM, kevind0718 at gmail.com wrote: > On Thursday, March 24, 2016 at 4:29:03 PM UTC-4, Random832 wrote: >> On Thu, Mar 24, 2016, at 16:24, kevind0718 at gmail.com wrote: >>> If I run the code below two windows appear. >>> One empty and one with the text box and button. >>> Why? The answer to that sort of question is nearly always "Because that is what you asked for" >> The empty one is the root window. > I kinda guessed that. > Is there any downside to hiding it using root.withdraw(). In your example, there is no apparent reason to hid root and use a Toplevel. IDLE, however, is currently a multiwindow application with no main window and it uses 'root.withdraw'. (In fact, it appears to do so twice in the IDLE process -- possibly a mistake.) -- Terry Jan Reedy From ben+python at benfinney.id.au Thu Mar 24 21:41:37 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 25 Mar 2016 12:41:37 +1100 Subject: [OT'ish] Is there a list as good as this for Javascript References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <945esc-qkp.ln1@esprimo.zbmc.eu> Message-ID: <85oaa3cp0u.fsf@benfinney.id.au> Mark Lawrence writes: > No. While this idiot, BartC, is let loose on this forum, I'll say > what I like. That is the attitude of a petulant schoolyard bully. Stop, please. You are to behave well in this community, and this is not conditional on the behaviour of others. You are better that that. Please continue to show it. -- \ ?Some forms of reality are so horrible we refuse to face them, | `\ unless we are trapped into it by comedy. To label any subject | _o__) unsuitable for comedy is to admit defeat.? ?Peter Sellers | Ben Finney From torriem at gmail.com Thu Mar 24 22:49:18 2016 From: torriem at gmail.com (Michael Torrie) Date: Thu, 24 Mar 2016 20:49:18 -0600 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56F4A72E.5000402@gmail.com> On 03/24/2016 04:18 PM, Mark Lawrence wrote: > On 24/03/2016 19:54, BartC wrote: >> On 24/03/2016 18:10, Steven D'Aprano wrote: >>> On Fri, 25 Mar 2016 12:01 am, BartC wrote: >> >>> >>> Then those numbers are pointless. >> >> Yes, they would need some adjustment to do this stuff properly. > > Please give up before you get sued by the families of the people who > have died laughing. Mark, please stop with the disparaging remarks. Just ignore this thread since it bother's you so much. Whether or not you or anyone else disagrees with Bart's programming techniques, his use of Python, or anything else, this is no excuse for name disparaging remarks. If Bart doesn't wish to learn whatever it is you wish to teach, that's his problem. I know you're a long-time poster to this list, but your comments of late have been getting a bit inflammatory. I am a bit amazed that Bart is still willing to communicate on this list after the flack he's got from you and a couple of others. I applaud Steve's voice of reason from time to time on this thread. I've been trying to follow things on this thread, and I understand a bit about Pythonic ideomatic style and I know what Python is really good at and some of what it's not so good at, but it seems like one of Bart's original contentions was that given a certain problem, coded in a non-pythonic way, got slower under Python 3 than it was under Python 2 (if I recall correctly). In other words a performance regression. Somehow this seems to have gotten lost in the squabble over how one should use Python. From rustompmody at gmail.com Fri Mar 25 00:10:05 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 24 Mar 2016 21:10:05 -0700 (PDT) Subject: Negative responses (Re: [OT'ish] Is there a list) In-Reply-To: <4ed51a02-381e-4e1b-b3c1-64a5ffeaac4e@googlegroups.com> References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <945esc-qkp.ln1@esprimo.zbmc.eu> <4ed51a02-381e-4e1b-b3c1-64a5ffeaac4e@googlegroups.com> Message-ID: <8959ddf2-f426-4d29-bd4e-dd6e1ea3b1cf@googlegroups.com> On Friday, March 25, 2016 at 6:08:43 AM UTC+5:30, Ned Batchelder wrote: > Yes Mark, you are a problem. You insult people personally. There is no need > for that. BartC is a challenge, I agree, but he has not said anything > personal against you or anyone else. > > Stop making personal attacks. Find another way to deal with your frustration. > > The Python Code of Conduct says to treat people with respect. You aren't > doing that. I know you feel like Bart has been disrespectful by dragging out > threads and ignoring important parts of the Python language. I agree, that > is frustrating, but it different than making personal insults. > > Stop it. You are hurting this list and you are hurting Python. I'd also like to point out the damage done by Mark to complete noobs. - Somebody asks about inability to install python Response: Everybody keeps asking this... Look up the list - Some typical noob question. Response: Dont top post (or some other format/meta/OT ie irrelevant response If getting new people asking new questions is a priority, something needs to be done about these kinds of rude responses. From best_lay at yahoo.com Fri Mar 25 00:37:54 2016 From: best_lay at yahoo.com (Wildman) Date: Thu, 24 Mar 2016 23:37:54 -0500 Subject: Key Binding Problem References: <06adnbnMouHI027LnZ2dnUU7-XednZ2d@giganews.com> Message-ID: On Thu, 24 Mar 2016 21:43:26 -0400, Dennis Lee Bieber wrote: > On Thu, 24 Mar 2016 11:19:52 -0500, Wildman via Python-list > declaimed the following: > >> >>I believe I understand. Thanks. If you can't tell, I'm new to >>Python so the learning process is on-going. > > And you decided to throw in a GUI framework at the same time... Coming from VB6, it seemed the natural thing to do. > I've only written one program using Tkinter (and I stuck the old PMW > library on top of that) -- it was quite horrid of a program. I have used > the file-requester in a few others though, but that is a stand-alone > widget/dialog. I am a hobby programmer so I do this just for the pleasure of creating something. I started with 16bit assembly back in the day and from there went to various flavors of BASIC including PowerBASIC and Visual Basic. Never made the transition to .net. Didn't see a need. I have yet to find anything that I can't do with Classic VB6 that I want to do. > My only other GUI experience is a rudimentary "Jeopardy" framework > (called Jeparody -- did not include timers and player buttons) done on a > whim for an investment mailing list, using VB6... And a significant > application in which I emulated the display features of a Ramtek 9300 > graphics engine using DECWindows with Graphical Kernel System on top (and > no "GUI Builder" -- just a hand-written GUI description file). > > I'd recommend going through the Python Tutorial, study the standard > types in the Library manual, and maybe skim through the Python Reference... > THEN maybe consider a GUI... Good advice. I have found some good tuts on Youtube for Python and Tk. That gave me a good start. And I have several websites bookmarked for other tutorials and references. Plus that several knowledgeable people right here who are willing to help. -- GNU/Linux user #557453 "Be at war with your vices, at peace with your neighbors, and let every new year find you a better man." -Benjamin Franklin From best_lay at yahoo.com Fri Mar 25 01:10:57 2016 From: best_lay at yahoo.com (Wildman) Date: Fri, 25 Mar 2016 00:10:57 -0500 Subject: Problem With Embedded Icon and Python 3.4 Message-ID: I have a program that I have been trying to rewrite so it will run on Python 2.7 and 3.4. It has been a pain to say the least. Thank $DIETY for aliases. Anyway, I got it all working except for one thing. The program has an embedded icon. It is displayed in the window's titlebar. The icon is a 16x16 png that has been base64 encoded using a Linux utility called memencoder. The code below works perfectly with Python 2.7. The icon data is complete for anyone that wants to try to run this code: encoded_icon = """\ iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAACBj SFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAACAVBMVEUAAAAmAAAJ AAD/AAAOAAACAAAAAAABAAAVAAArAAANAAAPAACMAADqV1dYAAAVAAArAACmKiw2AABcAACM CguXBgcYAACrAgKdGRuZKCuPCAk9AAAAAACDAAAFAAABAADQAAAhAAARAAACAAABAAD/AADO AABaAAAfAABFAAD/AAANAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAHAAD/AAAYAAAL AAADAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAtAAAAAAABAABXAACnAAC7AABoAABsAACdAABy AAATAAAIAAB8AACeCwvDW1vboaHZmJi+Tk6mJSXFcHDNg4O8VlaeEhGEAACVAgLCZmbSkpTM fX3LiImXERJUAAATAAChGhvLZmmlREdnAAATAACgHyCzQUW7WlybRkpXAACLBgepZWqZZWt+ ExSoFRataW+vq7WqucSdc3t3EhMjAABLAACNAgKMICJ3GRtTAAAAAACiAACiEhScHR9vAAAk AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAABAAAAAAAAAAAAAAAAAAAAAAAAAAD36+v+ /v785+j539/+8/P27+/gwcPz///1urz+WFnTjI3/cXH5dXfn+f3Z6fDQyM7W/v/bs7vfYGbi c3jfkJbI9v++5vO2w82vusT///+h6spZAAAAkXRSTlMAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAEAAQAADEdRFwAdVEQKAAEABFtjUDAENFJ9WAIABDUoGwEIFRIf AgJRyunZVjSw2MZsCzrm3NH5egMAjv/YGwGcxL/eIVHu40crvPn+9IoHBUaPjUAEFk5dTREC AQAAAAEBAAABAAEAAAIAmCbO4wAAAAFiS0dEqr4GV74AAAAJcEhZcwAACxMAAAsTAQCanBgA AAAHdElNRQfgAxUUFToQYVhVAAAA5klEQVQY02NQZUAGjEwMagzMDCysbGAuO4O6BoMmgxaH to6unr6BoZExp4kpAxeDmbmFpZW1ja2dvYOjEzdQIY+zi6ubO6+Hp5e3D1inr59/QGBQcEho WHgEH5DPHxk1cdLk6JgpU6fFxsUDBRISp8+YOStp9py58+YnpwAFUtMWLFy0OD1jydJlyzOz gAIC2TkrVubm5RcUFhWXlIIMLSuvqKyqFqypratvEAIJCIs0NomKMYtLSEpJg62VkZWTZ2Bo bnFSUFRSVmFobWuHeqzDiYGhs4uhu6cXKuAEFOjrZ0AFThMAxbo5a0L7F4cAAAAldEVYdGRh dGU6Y3JlYXRlADIwMTYtMDMtMjFUMTU6MjA6MzMtMDU6MDBXJmdFAAAAJXRFWHRkYXRlOm1v ZGlmeQAyMDE2LTAzLTIxVDE1OjE5OjI3LTA1OjAwe2m2vwAAAABJRU5ErkJggg==""" root = Tk() decoded_icon=base64.decodestring(encoded_icon) image_icon = Image.open(io.BytesIO(decoded_icon)) icon = ImageTk.PhotoImage(image_icon) root.call('wm', 'iconphoto', root._w, icon) app = Window(root) root.mainloop() When I run the program with Python 3.4, I get this error: Traceback (most recent call last): File "/usr/lib/python3.4/base64.py", line 519, in _input_type_check m = memoryview(s) TypeError: memoryview: str object does not have the buffer interface The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./myprogram.py", line 276, in decoded_icon=base64.decodestring(encoded_icon) File "/usr/lib/python3.4/base64.py", line 561, in decodestring return decodebytes(s) File "/usr/lib/python3.4/base64.py", line 553, in decodebytes _input_type_check(s) File "/usr/lib/python3.4/base64.py", line 522, in _input_type_check raise TypeError(msg) from err TypeError: expected bytes-like object, not str I tried converting the icon string to a byte variable like this: encoded_icon = bytes("""\ iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAACBj (...) ZGlmeQAyMDE2LTAzLTIxVDE1OjE5OjI3LTA1OjAwe2m2vwAAAABJRU5ErkJggg==""") That give me a different error: Traceback (most recent call last): File "./myprogram.py", line 269, in ZGlmeQAyMDE2LTAzLTIxVDE1OjE5OjI3LTA1OjAwe2m2vwAAAABJRU5ErkJggg==""") TypeError: string argument without an encoding I'm not sure what that means. I looks like it wants the string to be encoded but it already is. And why the reference to only the last line of the string? I am at a loss here. Any help would be greatly appreciated. -- GNU/Linux user #557453 Old enough to know better... too young to resist. From tjreedy at udel.edu Fri Mar 25 01:30:17 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Mar 2016 01:30:17 -0400 Subject: Problem With Embedded Icon and Python 3.4 In-Reply-To: References: Message-ID: On 3/25/2016 1:10 AM, Wildman via Python-list wrote: > I have a program that I have been trying to rewrite so it will > run on Python 2.7 and 3.4. It has been a pain to say the least. > Thank $DIETY for aliases. Anyway, I got it all working except > for one thing. The program has an embedded icon. It is displayed > in the window's titlebar. The icon is a 16x16 png that has been > base64 encoded using a Linux utility called memencoder. The code > below works perfectly with Python 2.7. The icon data is complete > for anyone that wants to try to run this code: > > encoded_icon = """\ To make this literal a bytes literal, prepend 'b'. encoded_icon = b'''\ > iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAACBj > SFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAACAVBMVEUAAAAmAAAJ > AAD/AAAOAAACAAAAAAABAAAVAAArAAANAAAPAACMAADqV1dYAAAVAAArAACmKiw2AABcAACM > CguXBgcYAACrAgKdGRuZKCuPCAk9AAAAAACDAAAFAAABAADQAAAhAAARAAACAAABAAD/AADO > AABaAAAfAABFAAD/AAANAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAHAAD/AAAYAAAL > AAADAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAtAAAAAAABAABXAACnAAC7AABoAABsAACdAABy > AAATAAAIAAB8AACeCwvDW1vboaHZmJi+Tk6mJSXFcHDNg4O8VlaeEhGEAACVAgLCZmbSkpTM > fX3LiImXERJUAAATAAChGhvLZmmlREdnAAATAACgHyCzQUW7WlybRkpXAACLBgepZWqZZWt+ > ExSoFRataW+vq7WqucSdc3t3EhMjAABLAACNAgKMICJ3GRtTAAAAAACiAACiEhScHR9vAAAk > AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAABAAAAAAAAAAAAAAAAAAAAAAAAAAD36+v+ > /v785+j539/+8/P27+/gwcPz///1urz+WFnTjI3/cXH5dXfn+f3Z6fDQyM7W/v/bs7vfYGbi > c3jfkJbI9v++5vO2w82vusT///+h6spZAAAAkXRSTlMAAAAAAAAAAAAAAAAAAAAAAAAAAAAA > AAAAAAAAAAAAAAAAAAAAAAEAAQAADEdRFwAdVEQKAAEABFtjUDAENFJ9WAIABDUoGwEIFRIf > AgJRyunZVjSw2MZsCzrm3NH5egMAjv/YGwGcxL/eIVHu40crvPn+9IoHBUaPjUAEFk5dTREC > AQAAAAEBAAABAAEAAAIAmCbO4wAAAAFiS0dEqr4GV74AAAAJcEhZcwAACxMAAAsTAQCanBgA > AAAHdElNRQfgAxUUFToQYVhVAAAA5klEQVQY02NQZUAGjEwMagzMDCysbGAuO4O6BoMmgxaH > to6unr6BoZExp4kpAxeDmbmFpZW1ja2dvYOjEzdQIY+zi6ubO6+Hp5e3D1inr59/QGBQcEho > WHgEH5DPHxk1cdLk6JgpU6fFxsUDBRISp8+YOStp9py58+YnpwAFUtMWLFy0OD1jydJlyzOz > gAIC2TkrVubm5RcUFhWXlIIMLSuvqKyqFqypratvEAIJCIs0NomKMYtLSEpJg62VkZWTZ2Bo > bnFSUFRSVmFobWuHeqzDiYGhs4uhu6cXKuAEFOjrZ0AFThMAxbo5a0L7F4cAAAAldEVYdGRh > dGU6Y3JlYXRlADIwMTYtMDMtMjFUMTU6MjA6MzMtMDU6MDBXJmdFAAAAJXRFWHRkYXRlOm1v > ZGlmeQAyMDE2LTAzLTIxVDE1OjE5OjI3LTA1OjAwe2m2vwAAAABJRU5ErkJggg==""" > > root = Tk() > decoded_icon=base64.decodestring(encoded_icon) > image_icon = Image.open(io.BytesIO(decoded_icon)) > icon = ImageTk.PhotoImage(image_icon) > root.call('wm', 'iconphoto', root._w, icon) > app = Window(root) > root.mainloop() > > > When I run the program with Python 3.4, I get this error: > > Traceback (most recent call last): > File "/usr/lib/python3.4/base64.py", line 519, in _input_type_check > m = memoryview(s) > TypeError: memoryview: str object does not have the buffer interface bytes do have the buffer interface, so I expect that using bytes instead of str will work. -- Terry Jan Reedy From zachary.ware+pylist at gmail.com Fri Mar 25 01:34:13 2016 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Fri, 25 Mar 2016 00:34:13 -0500 Subject: Problem With Embedded Icon and Python 3.4 In-Reply-To: References: Message-ID: On Fri, Mar 25, 2016 at 12:10 AM, Wildman via Python-list wrote: > I have a program that I have been trying to rewrite so it will > run on Python 2.7 and 3.4. It has been a pain to say the least. > Thank $DIETY for aliases. Anyway, I got it all working except > for one thing. The program has an embedded icon. It is displayed > in the window's titlebar. The icon is a 16x16 png that has been > base64 encoded using a Linux utility called memencoder. The code > below works perfectly with Python 2.7. The icon data is complete > for anyone that wants to try to run this code: > > encoded_icon = """\ [...] > I tried converting the icon string to a byte variable like this: > > encoded_icon = bytes("""\ > iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAACBj > (...) > ZGlmeQAyMDE2LTAzLTIxVDE1OjE5OjI3LTA1OjAwe2m2vwAAAABJRU5ErkJggg==""") > > > That give me a different error: > > Traceback (most recent call last): > File "./myprogram.py", line 269, in > ZGlmeQAyMDE2LTAzLTIxVDE1OjE5OjI3LTA1OjAwe2m2vwAAAABJRU5ErkJggg==""") > TypeError: string argument without an encoding > > I'm not sure what that means. I looks like it wants the string > to be encoded but it already is. The bytes constructor in Python 3 requires you to provide an encoding (utf-8, ascii, latin-1, koi8, etc) when passing in a string, otherwise it doesn't know what bytes you want and refuses to guess. You could fix this by adding `encoding='ascii'` to the bytes() call?but I'm not certain that that would work in 2.7, and there's a much easier method, noted later. > And why the reference to only > the last line of the string? Because the traceback would be huge if it included the entire function call, and there's no need to. You can find the error from just that line. It would be arguably more useful to show the first line, but that's more difficult to do. > I am at a loss here. Any help would be greatly appreciated. What you need here is a bytes literal, which is accomplished by prepending a 'b' to the string literal. Your `encoded_icon = """\` just needs to become `encoded_icon = b"""\`. See here [1] for more information. -- Zach [1] https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals From cl at isbd.net Fri Mar 25 05:05:31 2016 From: cl at isbd.net (cl at isbd.net) Date: Fri, 25 Mar 2016 09:05:31 +0000 Subject: [OT'ish] Is there a list as good as this for Javascript References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> Message-ID: Larry Martell wrote: > On Thu, Mar 24, 2016 at 4:53 PM, wrote: > > I use Python wherever I can and find this list (as a usenet group via > > gmane) an invaluable help at times. > > > > Occasionally I have to make forays into Javascript, can anyone > > recommend a place similar to this list where Javascript questions can > > be asked? The trouble is that there are very many usenet Javascript > > lists and it's difficult to guess which one[es] might be good. > > I don't know of any JS specific mailing lists. When I have a JS > question I usually use stackoverflow. But there is also the web design > mailing list, which will accept JS questions. See > http://www.webdesign-l.com/ > OK, thanks, I do know about both of those though I hadn't realised there was a mailing list at Web Design. > For jQuery questions I use the jquery forum - http://forum.jquery.com/ I find forums very difficult to use in general for a number of reasons:- I have to visit them individually, it's not practical for the number of subjects I'm interested in. I belong to 77 lists just now, a similar number of forums would be totally unmanageable. I can't use a decent editor (or my choice) to write and reply to messages. The threading is often rather poor (though some are better than others). -- Chris Green ? From alister.ware at ntlworld.com Fri Mar 25 06:58:53 2016 From: alister.ware at ntlworld.com (alister) Date: Fri, 25 Mar 2016 10:58:53 GMT Subject: Web Scraping References: Message-ID: On Thu, 24 Mar 2016 18:17:43 -0700, 121sukha wrote: > I am new to python and I want to use web scraping to download songs from > website. > how do I write code to check if the website has uploaded a new song and > have that song automatically be downloaded onto my computer. I know how > to use the requests.get() module but i am more interested in knowing how > to download and save every new song that the website uploads on the > site. I would extremely appreciate the help from anyone. Thanks! I belive if you contact the RIAA they have full details available -- You or I must yield up his life to Ahrimanes. I would rather it were you. I should have no hesitation in sacrificing my own life to spare yours, but we take stock next week, and it would not be fair on the company. -- J. Wellington Wells From alister.ware at ntlworld.com Fri Mar 25 07:05:22 2016 From: alister.ware at ntlworld.com (alister) Date: Fri, 25 Mar 2016 11:05:22 GMT Subject: [OT'ish] Is there a list as good as this for Javascript References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <945esc-qkp.ln1@esprimo.zbmc.eu> Message-ID: On Thu, 24 Mar 2016 23:46:14 +0000, Mark Lawrence wrote: > On 24/03/2016 23:33, Ian Kelly wrote: >> On Thu, Mar 24, 2016 at 4:58 PM, Mark Lawrence >> wrote: >>> No. While this idiot, BartC, is let loose on this forum, I'll say >>> what I like. >> >> Good to know. I've been on the fence about this for a long time, but >> lately the frequency of your outbursts seems to have increased, and >> you're being more of a nuisance to this list than the people whom >> you're complaining about. >> >> *plonk* >> >> > I just love it. A complete moron like BartC insults the Python > community day in, day out, yet I'm the problem? When he can actually > write a decent line of Python code and avoid discussing speed I'll think > about him as a professional programmer. I cannot see this happening > when all he talks about is byte code. He's clearly never read anything > like Steve Maguire's "Writing Solid Code". I am afraid I have to disagree with you Responding in BartC's threads is one thing but you are now deliberately trolling him in others, this is a bad as a poster (who shall remain namless) continually telling people the cause of there issues is due to pythons Unicode handling. it does nothing for the OP of this thread & quickly renders it useless. -- I'm into SOFTWARE! From bc at freeuk.com Fri Mar 25 07:06:25 2016 From: bc at freeuk.com (BartC) Date: Fri, 25 Mar 2016 11:06:25 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: References: <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 25/03/2016 01:02, Dennis Lee Bieber wrote: > On Thu, 24 Mar 2016 19:54:54 +0000, BartC declaimed the > following: > > >> >> (I use a dedicated repeat-N-times loop that needs no explicit loop >> variable, > Well, that sure wouldn't support a Python for-loop... If I may, I'll reply to this point outside the group, at this link: http://pastebin.com/hfAKN2jg -- bartc From afiskon at devzen.ru Fri Mar 25 08:06:08 2016 From: afiskon at devzen.ru (Aleksander Alekseev) Date: Fri, 25 Mar 2016 15:06:08 +0300 Subject: How to make Python interpreter a little more strict? Message-ID: <20160325150608.21c3827a@fujitsu> Hello Recently I spend half an hour looking for a bug in code like this: eax at fujitsu:~/temp$ cat ./t.py #!/usr/bin/env python3 for x in range(0,5): if x % 2 == 0: next print(str(x)) eax at fujitsu:~/temp$ ./t.py 0 1 2 3 4 Is it possible to make python complain in this case? Or maybe solve such an issue somehow else? -- Best regards, Aleksander Alekseev http://eax.me/ From sjeik_appie at hotmail.com Fri Mar 25 09:03:05 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Fri, 25 Mar 2016 13:03:05 +0000 Subject: Effects of caching frequently used objects, was Re: Explaining names vs variables in Python In-Reply-To: References: , Message-ID: > To: python-list at python.org > From: __peter__ at web.de > Subject: Effects of caching frequently used objects, was Re: Explaining names vs variables in Python > Date: Wed, 2 Mar 2016 10:12:48 +0100 > > Salvatore DI DIO wrote: > > > Hello, > > > > I know Python does not have variables, but names. > > Multiple names cant then be bound to the same objects. > > > > So this behavior > > > >>>> b = 234 > >>>> v = 234 > >>>> b is v > > True > > > > according to the above that is ok > > > > > > > > But where is the consistency ? if I try : > > > >>>> v = 890 > >>>> w = 890 > >>>> v is w > > False > > > > It is a little difficult to explain this behavior to a newcommer in Python > > > > Can someone give me the right argument to expose ? > > You should not bother with object identity for objects other than None. A little late to the party, but: how about Ellipsis? Shouldn't "is" also be used for that one? (It's rare, I know :)) Albert-Jan From rosuav at gmail.com Fri Mar 25 09:22:33 2016 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 26 Mar 2016 00:22:33 +1100 Subject: Effects of caching frequently used objects, was Re: Explaining names vs variables in Python In-Reply-To: References: Message-ID: On Sat, Mar 26, 2016 at 12:03 AM, Albert-Jan Roskam wrote: >> You should not bother with object identity for objects other than None. > > > A little late to the party, but: how about Ellipsis? Shouldn't "is" also be used for that one? (It's rare, I know :)) Yes, and also True and False, if you're checking for the specific values. (Though it's more common in Python to merely care about truthiness/falsiness.) Other common identity checks include: if str is bytes: # Python 2 handling, where "native strings" are byte strings else: # Python 3 handling, where "native strings" are text strings if iter(x) is x: # x is an iterator, not some other iterable _SENTINEL = object() def func(arg=_SENTINEL): if arg is _SENTINEL: # arg was not passed Anyone who says that identity checks are only for None is significantly over-simplifying things. This isn't necessarily a bad thing, but it should never be taken to be the whole story. ChrisA From kevind0718 at gmail.com Fri Mar 25 09:41:48 2016 From: kevind0718 at gmail.com (kevind0718 at gmail.com) Date: Fri, 25 Mar 2016 06:41:48 -0700 (PDT) Subject: Tkinter --> Why multiple windows In-Reply-To: References: Message-ID: <7d191efb-fe80-488f-87db-268b4b893d42@googlegroups.com> On Thursday, March 24, 2016 at 9:24:44 PM UTC-4, Wildman wrote: > On Thu, 24 Mar 2016 13:24:16 -0700, kevind0718 wrote: > > > Hello: > > > > newbie Tkinter question > > > > If I run the code below two windows appear. > > One empty and one with the text box and button. > > > > Why? please > > > > KD > > > > > > > > from Tkinter import * > > > > class MyDialog: > > def __init__(self, parent): > > > > top = self.top = Toplevel(parent) > > > > Label(top, text="Value").pack() > > > > self.e = Entry(top) > > self.e.pack(padx=5) > > > > b = Button(top, text="OK", command=self.ok) > > b.pack(pady=5) > > > > def ok(self): > > > > print "value is", self.e.get() > > > > self.top.destroy() > > > > > > root = Tk() > > > > d = MyDialog(root) > > > > root.wait_window(d.top) > > Try this: > > from Tkinter import * > > class MyDialog(Frame): > > def __init__(self, parent): > Frame.__init__(self, parent) > self.parent = parent > self.pack(fill=BOTH, expand=1) > self.parent.title("MyDialog") > Label(self, text="Value").pack() > self.e = Entry(self) > self.e.pack(padx=5) > self.b = Button(self, text="OK", command=self.ok) > self.b.pack(pady=5) > > def ok(self): > print "value is", self.e.get() > > root = Tk() > d = MyDialog(root) > root.mainloop() > > -- > GNU/Linux user #557453 > May the Source be with you. Looking at the lines below As related to the code I posted above. I believe this code will allow me to instantiate the class MyDialog, wait until the window is destroyed and then continue on my merry way. root = Tk() d = MyDialog(root) root.wait_window(d.top) Now if I pass an instance of Unamepword into the constructor of MyDialog(unamepword) , I can modify uStr and pWord in MyDialog and the local copy will get updated. Correct? class Unamepword: ## ## class to hold user name and pWord for Database uName = None pWord = None def __init__(self, uStr, pStr): self.uName = uStr self.pWord = pStr Many thanks for your attention to this matter. KD From best_lay at yahoo.com Fri Mar 25 10:41:35 2016 From: best_lay at yahoo.com (Wildman) Date: Fri, 25 Mar 2016 09:41:35 -0500 Subject: Problem With Embedded Icon and Python 3.4 References: Message-ID: On Fri, 25 Mar 2016 01:30:17 -0400, Terry Reedy wrote: > On 3/25/2016 1:10 AM, Wildman via Python-list wrote: >> I have a program that I have been trying to rewrite so it will >> run on Python 2.7 and 3.4. It has been a pain to say the least. >> Thank $DIETY for aliases. Anyway, I got it all working except >> for one thing. The program has an embedded icon. It is displayed >> in the window's titlebar. The icon is a 16x16 png that has been >> base64 encoded using a Linux utility called memencoder. The code >> below works perfectly with Python 2.7. The icon data is complete >> for anyone that wants to try to run this code: >> >> encoded_icon = """\ > > To make this literal a bytes literal, prepend 'b'. > > encoded_icon = b'''\ Whoopee, that worked! Thank you. -- GNU/Linux user #557453 The cow died so I don't need your bull! From best_lay at yahoo.com Fri Mar 25 10:42:22 2016 From: best_lay at yahoo.com (Wildman) Date: Fri, 25 Mar 2016 09:42:22 -0500 Subject: Problem With Embedded Icon and Python 3.4 References: Message-ID: On Fri, 25 Mar 2016 00:34:13 -0500, Zachary Ware wrote: > On Fri, Mar 25, 2016 at 12:10 AM, Wildman via Python-list > wrote: >> I have a program that I have been trying to rewrite so it will >> run on Python 2.7 and 3.4. It has been a pain to say the least. >> Thank $DIETY for aliases. Anyway, I got it all working except >> for one thing. The program has an embedded icon. It is displayed >> in the window's titlebar. The icon is a 16x16 png that has been >> base64 encoded using a Linux utility called memencoder. The code >> below works perfectly with Python 2.7. The icon data is complete >> for anyone that wants to try to run this code: >> >> encoded_icon = """\ > [...] >> I tried converting the icon string to a byte variable like this: >> >> encoded_icon = bytes("""\ >> iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAACBj >> (...) >> ZGlmeQAyMDE2LTAzLTIxVDE1OjE5OjI3LTA1OjAwe2m2vwAAAABJRU5ErkJggg==""") >> >> >> That give me a different error: >> >> Traceback (most recent call last): >> File "./myprogram.py", line 269, in >> ZGlmeQAyMDE2LTAzLTIxVDE1OjE5OjI3LTA1OjAwe2m2vwAAAABJRU5ErkJggg==""") >> TypeError: string argument without an encoding >> >> I'm not sure what that means. I looks like it wants the string >> to be encoded but it already is. > > The bytes constructor in Python 3 requires you to provide an encoding > (utf-8, ascii, latin-1, koi8, etc) when passing in a string, otherwise > it doesn't know what bytes you want and refuses to guess. You could > fix this by adding `encoding='ascii'` to the bytes() call?but I'm not > certain that that would work in 2.7, and there's a much easier method, > noted later. > >> And why the reference to only >> the last line of the string? > > Because the traceback would be huge if it included the entire function > call, and there's no need to. You can find the error from just that > line. It would be arguably more useful to show the first line, but > that's more difficult to do. > >> I am at a loss here. Any help would be greatly appreciated. > > What you need here is a bytes literal, which is accomplished by > prepending a 'b' to the string literal. Your `encoded_icon = """\` > just needs to become `encoded_icon = b"""\`. See here [1] for more > information. Thanks for the info and the link. That fixed the problem. -- GNU/Linux user #557453 The cow died so I don't need your bull! From steve at pearwood.info Fri Mar 25 11:50:02 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Mar 2016 02:50:02 +1100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> On Fri, 25 Mar 2016 06:54 am, BartC wrote: >> In the case of C, the line is limited to working with some specific type >> (say, an int32). Even there, if the addition might overflow, the >> behaviour is undefined and the compiler can do anything it wants >> (including time travel, > > I'm pretty sure it can't do time travel... > > or erasing your hard disk). You are absolutely, and potentially catastrophically, mistaken on that. Undefined behaviour does not mean "implementation specific behaviour". Nor does it mean "something sensible will happen but we don't promise what it will be". It means "the compiler can do anything", including ignoring the code you actually wrote and substituting its own faster code, which may or may not do what your original code did. We can presume that no non-malicious C compiler will *intentionally* erase your hard drive because you added 1 to an integer without checking for overflow, but it is certainly true that undefined behaviour can lead to any behaviour at all. Undefined behaviour in C is a major cause of bugs and security vulnerabilities. Raymond Chen, one of Microsoft's luminaries, describes how undefined behaviour can travel backwards in time to affect code that executes *before* the undefined behaviour occurs: https://blogs.msdn.microsoft.com/oldnewthing/20140627-00/?p=633/ Many people assume that if your code has undefined behaviour, you might have no idea what happens from that point on, but at least you can reason correctly about the state of the program prior to that. THIS IS INCORRECT. The C standard makes no such promise, and in fact explicitly states that the effect of undefined behaviour can affect code that runs before the undefined behaviour occurs. Here is an excellent three part article about undefined behaviour: http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_21.html And three-parter: http://blog.regehr.org/archives/213 http://blog.regehr.org/archives/226 http://blog.regehr.org/archives/232 Bruce Dawson: https://randomascii.wordpress.com/2014/05/19/undefined-behavior-can-format-your-drive/ And I love the title of this talk from Robert C Seacord at CERT: "Dangerous Optimizations and the Loss of Causality" http://bsidespgh.com/2014/media/speakercontent/DangerousOptimizationsBSides.pdf Undefined behaviour in C is a minefield waiting to blow your program's legs off, because the designers of the language made the explicit choice that they wanted the language to be as fast and efficient as possible, even at the cost of safe, reproducible behaviour. -- Steven From steve at pearwood.info Fri Mar 25 12:22:58 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Mar 2016 03:22:58 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f565e4$0$1614$c3e8da3$5496439d@news.astraweb.com> On Fri, 25 Mar 2016 10:06 pm, BartC wrote: > On 25/03/2016 01:02, Dennis Lee Bieber wrote: >> On Thu, 24 Mar 2016 19:54:54 +0000, BartC declaimed the >> following: >> >> >>> >>> (I use a dedicated repeat-N-times loop that needs no explicit loop >>> variable, > >> Well, that sure wouldn't support a Python for-loop... > > If I may, I'll reply to this point outside the group, at this link: > > http://pastebin.com/hfAKN2jg Why split the discussion to *Pastebin*, of all places? Anyway, this is (in my opinion) the only relevant part of your comments there: [quote] But it is an optimisation that /could/ be done by the byte-code compiler when it sees a construct such as: for i in range(100): ..... and 'i' isn't used within the loop. (I don't know what Python says about the value of i after the loop terminates.) [end quote] i is guaranteed to have the same value outside the loop as it last had inside the loop, unless you explicitly unbind the name using "del" (or something equivalent). So after: for i in range(100): pass print(i) "99" will be printed. Likewise: for i in range(100): if i == 50: break print(i) "50" will be printed. [quote] This change would require a new byte-code (one that goes at the end of a loop, not the start), which probably wouldn't be popular either. And, by itself, would have very little impact on the majority of programs. (Also, if loops are that much of a problem, this is where PyPy excels.) [end quote] I am pretty sure that PyPy takes lots of efforts to optimize loops, but I can't tell you precisely what. I would also expect that Victor Stinner's FAT Python project will (eventually) look at optimizing such for-loops too. If you see something like: for i in range(N): do_stuff() and three conditions hold: (1) i is unused in the loop body; (2) range is still bound to the expected built-in function, and no other "range" in a nearer scope (say, a local variable called "range", or a global) exists to shadow it; and (3) and the body of the for-loop has no side-effects that might affect the truth of (1) then it should be safe to replace this loop with a fast, C loop that just calls the body of the loop N times. And that in turn might be fully or partly unrolled, e.g. for i in range(4): spam() could become: spam() spam() spam() spam() (This is a pretty standard compiler optimization technique, and if I recall correctly, PyPy already does this.) #1 (is i used in the loop?) can be detected at compile-time. There might be some tricky corner cases involving calls to nested functions, and of course any call to eval or exec make the analysis intractable, but I think it is otherwise easy to tell whether or not i is used in the for-loop. #2 (is range the expected range) can be handled by assuming it is, and keeping a guard for the case that it isn't. That's what FAT Python will do. I think PyPy does something similar. I don't have an intuition on how hard #3 (does the loop body have any side-effects that might affect this optimization?) might be, except to say that the presence of an eval or exec inside the body will probably make the optimization unsafe. It wouldn't surprise me if the unmaintained but still working Psycho project handled this, as well as such newer projects as pyjion, pyston, numba and theano. Bart, possibly something you have missed in this discussion: many of the optimizations you are surprised not to see are not, and may never be, in the vanilla Python language. But they are being included in language add-ons. There is a thriving, experimental but still usable, culture of JIT compilers for Python. Here is one of the oldest: http://www.ibm.com/developerworks/library/l-psyco/index.html Pyscho is unmaintained and doesn't work on anything better than 2.6, but the author has gone on to be one of the lead devs in PyPy, and it has inspired newer projects like numba and theano. The attitude of the core developers, especially Guido, is that the reference interpreter CPython should stick to only the easiest, least controversial optimizations (if any!) and leave the hard ones to third-party add-ons. -- Steven From dennisngeno7 at gmail.com Fri Mar 25 12:33:53 2016 From: dennisngeno7 at gmail.com (Dennis Ngeno) Date: Fri, 25 Mar 2016 09:33:53 -0700 Subject: Interpretation Message-ID: My programs have never combile, they keep telling me , systax error even after copy pasting From ethan at stoneleaf.us Fri Mar 25 12:45:10 2016 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 25 Mar 2016 09:45:10 -0700 Subject: Effects of caching frequently used objects, was Re: Explaining names vs variables in Python In-Reply-To: References: , Message-ID: <56F56B16.40701@stoneleaf.us> On 03/25/2016 06:03 AM, Albert-Jan Roskam wrote: > Somebody wrote: >> Somebody else wrote: >>> I know Python does not have variables, but names. >>> Multiple names cant then be bound to the same objects. >>> >>> So this behavior >>> >>>--> b = 234 >>>--> v = 234 >>>--> b is v >>> True >>> >>> according to the above that is ok >>> >>> >>> >>> But where is the consistency ? if I try : >>> >>>--> v = 890 >>>--> w = 890 >>>--> v is w >>> False >>> >>> It is a little difficult to explain this behavior to a newcommer in Python >>> >>> Can someone give me the right argument to expose ? >> >> You should not bother with object identity for objects other than None. No. The correct answer is: if identity is important either ensure the object you are getting back is a singleton (such as None, True, an Enum member, etc.) or you assign one name from another name: --> b = 234 --> v = b --> b is v True --> v = 890 --> w = v --> v is w True If identity is not important, don't use `is`. > A little late to the party, but: how about Ellipsis? Shouldn't "is" also be used for that one? (It's rare, I know :)) Ellipsis is a singleton, so `is` is fine. -- ~Ethan~ From marko at pacujo.net Fri Mar 25 12:57:53 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 25 Mar 2016 18:57:53 +0200 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87wpoq1omm.fsf@elektro.pacujo.net> Steven D'Aprano : > Undefined behaviour in C is a minefield waiting to blow your program's > legs off, because the designers of the language made the explicit > choice that they wanted the language to be as fast and efficient as > possible, even at the cost of safe, reproducible behaviour. Yes, although the same could be true for Python as well. For example, you could have this program: ===begin poof.py======================================================== assert 1 < 0 ===end poof.py========================================================== When it is run, you might see this: ======================================================================== $ python3 poof.py python3: the VM vanished in a puff of logic while executing 'poof.py' ======================================================================== Java's Hotspot produces very aggressive optimizations, essentially identifying bugs in the code and deducing the coder knows the bugs will never be realized at runtime and so the code paths that lead to the bug can be removed. Marko From cousinstanley at gmail.com Fri Mar 25 13:58:03 2016 From: cousinstanley at gmail.com (Cousin Stanley) Date: Fri, 25 Mar 2016 10:58:03 -0700 Subject: [OT'ish] Is there a list as good as this for Javascript References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> Message-ID: .... > Occasionally I have to make forays into Javascript, > can anyone recommend a place similar to this list > where Javascript questions can be asked ? .... Several years back I found the newsgroup comp.lang.javascript to be helpful .... However, I haven't used that group for some time now so don't know the current nature of the group .... -- Stanley C. Kitching Human Being Phoenix, Arizona From mattthiel at hotmail.com Fri Mar 25 14:52:34 2016 From: mattthiel at hotmail.com (matthew thiel) Date: Fri, 25 Mar 2016 18:52:34 +0000 Subject: I need help Message-ID: So I downloaded python and made an account but when I run it all it does is give me 3 options repair modify and uninstall I have clicked repair and modify and let them run but at the end it just exit out so how do I get it to work??? Sent from Mail for Windows 10 From ben.usenet at bsb.me.uk Fri Mar 25 15:26:14 2016 From: ben.usenet at bsb.me.uk (Ben Bacarisse) Date: Fri, 25 Mar 2016 19:26:14 +0000 Subject: [OT'ish] Is there a list as good as this for Javascript References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> Message-ID: <87k2kq7415.fsf@bsb.me.uk> Cousin Stanley writes: > .... >> Occasionally I have to make forays into Javascript, >> can anyone recommend a place similar to this list >> where Javascript questions can be asked ? > .... > > Several years back I found > the newsgroup comp.lang.javascript > to be helpful .... Still going. It can't hurt to try. > However, I haven't used that group > for some time now so don't know > the current nature of the group .... I suspect some people are put off answering because there's a poster whose main pleasure seems to be to nit-pick other people's answers (and the OP will be told there's no "Javascript" for starters!). The usual Usenet thick skin advised. -- Ben. From rgacote at appropriatesolutions.com Fri Mar 25 16:24:13 2016 From: rgacote at appropriatesolutions.com (Ray Cote) Date: Fri, 25 Mar 2016 16:24:13 -0400 Subject: Adding run_in_executor task to already existing loop. Message-ID: Hello: I?m trying to perform an synchronous task while using asyncio. I understand the solution is to use run_in_executor. I?m not clear on how to add this into an already running event loop. I?ve found lots of examples showing how to set up a loop and run this, but I?m blocked in regards to doing this when the loop is already established. Example code: def blocking_func(param1): # call the blocking call here. return results async def process_request(): loop = asyncio.get_event_loop() block = loop.run_in_executor(None, blocking_func, ?hello?) results = await loop.run_until_complete(asyncio.gather(*[block, ]) The above code says ?loop already running.? because we?re already in an async ask that has been awaited. What is the proper method of adding in this new synchronous task? Regards ?Ray -- Raymond Cote, President voice: +1.603.924.6079 email: rgacote at AppropriateSolutions.com skype: ray.cote From marko at pacujo.net Fri Mar 25 16:56:03 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 25 Mar 2016 22:56:03 +0200 Subject: Adding run_in_executor task to already existing loop. References: Message-ID: <87mvpm1dlo.fsf@elektro.pacujo.net> Ray Cote : > I?m trying to perform an synchronous task while using asyncio. You seem to want to do something you shouldn't be doing. Asyncio does not tolerate synchronous/blocking calls. You will need to move those in separate threads or processes if you can't turn them into asynchronous tasks. Marko From zachary.ware+pylist at gmail.com Fri Mar 25 17:00:16 2016 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Fri, 25 Mar 2016 16:00:16 -0500 Subject: Adding run_in_executor task to already existing loop. In-Reply-To: References: Message-ID: On Fri, Mar 25, 2016 at 3:24 PM, Ray Cote wrote: > Hello: > > I?m trying to perform an synchronous task while using asyncio. > I understand the solution is to use run_in_executor. > I?m not clear on how to add this into an already running event loop. > > I?ve found lots of examples showing how to set up a loop and run this, but > I?m blocked in regards to doing this when the loop is already established. > > > Example code: > > def blocking_func(param1): > # call the blocking call here. > return results > > async def process_request(): > loop = asyncio.get_event_loop() > block = loop.run_in_executor(None, blocking_func, ?hello?) > results = await loop.run_until_complete(asyncio.gather(*[block, ]) > > The above code says ?loop already running.? because we?re already in an > async ask that has been awaited. What is the proper method of adding in > this new synchronous task? I'm assuming you're doing `await process_request()` elsewhere, which is what's producing your error: you're trying to start the loop within a coroutine running on that loop. loop.run_in_executor() returns a Future just like any other coroutine, so process_request just needs this: async def process_request(): loop = asyncio.get_event_loop() results = await loop.run_in_executor(None, blocking_func, 'hello') -- Zach From zachary.ware+pylist at gmail.com Fri Mar 25 17:00:48 2016 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Fri, 25 Mar 2016 16:00:48 -0500 Subject: Adding run_in_executor task to already existing loop. In-Reply-To: <87mvpm1dlo.fsf@elektro.pacujo.net> References: <87mvpm1dlo.fsf@elektro.pacujo.net> Message-ID: On Fri, Mar 25, 2016 at 3:56 PM, Marko Rauhamaa wrote: > Ray Cote : > >> I?m trying to perform an synchronous task while using asyncio. > > You seem to want to do something you shouldn't be doing. Asyncio does > not tolerate synchronous/blocking calls. You will need to move those in > separate threads or processes if you can't turn them into asynchronous > tasks. That's exactly what run_in_executor does. -- Zach From rgacote at appropriatesolutions.com Fri Mar 25 17:06:06 2016 From: rgacote at appropriatesolutions.com (Ray Cote) Date: Fri, 25 Mar 2016 17:06:06 -0400 Subject: Adding run_in_executor task to already existing loop. In-Reply-To: References: Message-ID: On Fri, Mar 25, 2016 at 5:00 PM, Zachary Ware wrote: > I'm assuming you're doing `await process_request()` elsewhere, which > is what's producing your error: you're trying to start the loop within > a coroutine running on that loop. loop.run_in_executor() returns a > Future just like any other coroutine, so process_request just needs > this: > > async def process_request(): > loop = asyncio.get_event_loop() > results = await loop.run_in_executor(None, blocking_func, 'hello') > Yes, that was precisely the directive I needed. This is now working perfectly. Thanks ?Ray -- Raymond Cote, President voice: +1.603.924.6079 email: rgacote at AppropriateSolutions.com skype: ray.cote From breamoreboy at yahoo.co.uk Fri Mar 25 17:07:31 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 25 Mar 2016 21:07:31 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <56F4A72E.5000402@gmail.com> References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56F4A72E.5000402@gmail.com> Message-ID: On 25/03/2016 02:49, Michael Torrie wrote: > > I've been trying to follow things on this thread, and I understand a bit > about Pythonic ideomatic style and I know what Python is really good at > and some of what it's not so good at, but it seems like one of Bart's > original contentions was that given a certain problem, coded in a > non-pythonic way, got slower under Python 3 than it was under Python 2 > (if I recall correctly). In other words a performance regression. > Somehow this seems to have gotten lost in the squabble over how one > should use Python. > Python 3 is slower, period. The devs are trying to grab some of that back. I'd still say that the additions in Python 3, many of which were backported to 2.6/7, were worth this regression. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From PointedEars at web.de Fri Mar 25 17:17:05 2016 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Fri, 25 Mar 2016 22:17:05 +0100 Subject: [OT'ish] Is there a list as good as this for Javascript References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> Message-ID: <5038313.yTPFmuZgmt@PointedEars.de> cl at isbd.net wrote: > Occasionally I have to make forays into Javascript, can anyone > recommend a place similar to this list where Javascript questions can > be asked? The trouble is that there are very many usenet Javascript > lists and it's difficult to guess which one[es] might be good. There is no Javascript. There are no Usenet lists. This is not only a Python *mailing* list, it is also mirrored as an international Usenet _newsgroup_, (which I am reading). If you can accept all of that, then the international Usenet _newsgroup_ (where I am posting primarily) is for you. So are other national/language-specific newsgroups on the JavaScripts and other ECMAScript implementations. In your newsreader, search for newsgroups whose name contains ?javascript?. Next time, read and STFW first, and get a real name. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From PointedEars at web.de Fri Mar 25 17:19:27 2016 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Fri, 25 Mar 2016 22:19:27 +0100 Subject: [OT'ish] Is there a list as good as this for Javascript References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <945esc-qkp.ln1@esprimo.zbmc.eu> <997esc-rvp.ln1@esprimo.zbmc.eu> Message-ID: <2276224.iCQUJS1o0f@PointedEars.de> Mark Lawrence wrote: > [?] It is so blatantly obvious that he knows precisely nothing about > Python, but still the moderators on this list let him get away with it. This is a mailing list? It is moderated? *Seriously*? -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From rosuav at gmail.com Fri Mar 25 17:23:41 2016 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 26 Mar 2016 08:23:41 +1100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Mar 26, 2016 at 2:50 AM, Steven D'Aprano wrote: > On Fri, 25 Mar 2016 06:54 am, BartC wrote: > >>> In the case of C, the line is limited to working with some specific type >>> (say, an int32). Even there, if the addition might overflow, the >>> behaviour is undefined and the compiler can do anything it wants >>> (including time travel, >> >> I'm pretty sure it can't do time travel... >> >> or erasing your hard disk). > > > You are absolutely, and potentially catastrophically, mistaken on that. > > Undefined behaviour does not mean "implementation specific behaviour". Nor > does it mean "something sensible will happen but we don't promise what it > will be". It means "the compiler can do anything", including ignoring the > code you actually wrote and substituting its own faster code, which may or > may not do what your original code did. C's undefined behaviour is basically "you're not allowed to do this". The compiler is free to assume that you will never do this, ergo it is free to write out machine code that is correct only so long as you do not do this. Let me draw a Python analogy: 1) A well-behaved iterator will return values until it raises StopIteration, and then raise StopIteration thereafter. 2) An iterator which raises and then returns is thus badly written and should not exist. 3) A consumer of an iterator is allowed to misbehave in the event that the iterator returns after raising. 4) Therefore an optimizer is free to *cause* the consumer to misbehave when given an ill-behaved iterator. Consider this code: def zip_forever(*iters, fillvalue=None): """Like zip_longest, but without the silly rule that it should terminate once they all finish""" while True: yield tuple(next(it, fillvalue) for it in iters) If all its iterators are well-behaved, this is identical (modulo monkey-patching of names like "tuple" and "next") to: def zip_forever(*iters, fillvalue=None): yield from zip_longest(*iters, fillvalue=fillvalue) tup = (None,) * len(iters) while True: yield tup Is PyPy/FAT Python/some other optimizer permitted to make this change? The only difference between C's "undefined behaviour" and Python's way of doing the spec is the answer to that one question. C says yes, you're totally allowed to assume that; the end result in all cases should be indistinguishable; any time you can detect that it optimized this away, it's because of a bug somewhere else. Is your code allowed to misbehave when other code has bugs? That, ultimately, is the question. Imagine a tightened up subset of the Python language that restricts certain unusual behaviours. (This has the same purpose as PyPy's RPython, and for all I know, RPython might do exactly this.) It's a narrowly-used single purpose language, and its sole guarantee is that well-written SubPython code will behave the same way in SubPython as it does in CPython. It might then, for instance, not permit rebinding of builtins, nor of function default argument replacements, without an explicit "drop_caches()" call. Code could then be far more aggressively optimized - but behaviour would become undefined in the event that you break one of its rules. That's really all that C's done, and you honestly don't have to get so panicky at the word "undefined". It's simply "don't do this". And let's face it... there's a *lot* of undefined behaviour in CPython once you play with ctypes. Do we have any language guarantees as to what will happen if you change the value of the integer 7 to now be 8? Or will you just say "don't do that"? ChrisA From PointedEars at web.de Fri Mar 25 17:28:38 2016 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Fri, 25 Mar 2016 22:28:38 +0100 Subject: WP-A: A New URL Shortener References: <1537bd9e261.12a0e5b4a204345.4468160629979098801@vmesel.com> <500E8DF1-DCAC-4923-BD94-06DA1716484A@vmesel.com> <1964524.jFVgOtWIx9@PointedEars.de> <2334208.C0ktZ5B2k1@PointedEars.de> Message-ID: <4500052.tJGngFWhWt@PointedEars.de> Chris Angelico wrote: > [?] Thomas 'PointedEars' Lahn [?] wrote: >> Chris Angelico wrote: >>> [?] Thomas 'PointedEars' Lahn [?] wrote: >>>> Daniel Wilcox wrote: >>>>> Cool thanks, highly recommended to use an ORM to deter easy SQL >>>>> injections. >>>> That is to crack a nut with a sledgehammer. SQL injection can be >>>> easily and more efficiently prevented with prepared statements. [?] >>> You don't even need prepared statements. All you need is parameterized >>> queries. >> A prepared statement in this context uses a parameterized query. >> >> > > I know what a prepared statement is. And I know that they are > effective. However they are overkill - as I said, you merely need > parameterization. Then enlighten me, please: How is ?parameterization? or a ?parameterized query?, as *you* understand it, different from a prepared statement? -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From rosuav at gmail.com Fri Mar 25 17:48:24 2016 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 26 Mar 2016 08:48:24 +1100 Subject: WP-A: A New URL Shortener In-Reply-To: <4500052.tJGngFWhWt@PointedEars.de> References: <1537bd9e261.12a0e5b4a204345.4468160629979098801@vmesel.com> <500E8DF1-DCAC-4923-BD94-06DA1716484A@vmesel.com> <1964524.jFVgOtWIx9@PointedEars.de> <2334208.C0ktZ5B2k1@PointedEars.de> <4500052.tJGngFWhWt@PointedEars.de> Message-ID: On Sat, Mar 26, 2016 at 8:28 AM, Thomas 'PointedEars' Lahn wrote: > Chris Angelico wrote: > >> [?] Thomas 'PointedEars' Lahn [?] wrote: >>> Chris Angelico wrote: >>>> [?] Thomas 'PointedEars' Lahn [?] wrote: >>>>> Daniel Wilcox wrote: >>>>>> Cool thanks, highly recommended to use an ORM to deter easy SQL >>>>>> injections. >>>>> That is to crack a nut with a sledgehammer. SQL injection can be >>>>> easily and more efficiently prevented with prepared statements. [?] >>>> You don't even need prepared statements. All you need is parameterized >>>> queries. >>> A prepared statement in this context uses a parameterized query. >>> >>> > >> >> I know what a prepared statement is. And I know that they are >> effective. However they are overkill - as I said, you merely need >> parameterization. > > Then enlighten me, please: How is ?parameterization? or a ?parameterized > query?, as *you* understand it, different from a prepared statement? This is a prepared statement: http://www.postgresql.org/docs/current/static/sql-prepare.html You use a special "PREPARE" query to create *and store* a half-run query, and then you execute it afterwards. Back in the 1990s, I had the option of actually *compiling* my SQL queries as part of my C code, which would prepare all the queries for future execution. It is completely different from the dynamic parameterized queries that most people use. Parameterization is a more general concept which prepared statements invariably use, but which general code need not use. A Python database connector could choose to PREPARE/EXECUTE for every query it's given, or it could choose to escape all the parameters and embed them, or it could (if it's using a decent database back-end like PostgreSQL) simply send the query and its associated parameters as-is. Only one of these options is a "prepared statement". All three are "parameterized queries", at least from the POV of Python code. ChrisA From bc at freeuk.com Fri Mar 25 18:08:19 2016 From: bc at freeuk.com (BartC) Date: Fri, 25 Mar 2016 22:08:19 +0000 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) In-Reply-To: <56f565e4$0$1614$c3e8da3$5496439d@news.astraweb.com> References: <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f565e4$0$1614$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 25/03/2016 16:22, Steven D'Aprano wrote: > On Fri, 25 Mar 2016 10:06 pm, BartC wrote: (OK, I'll risk the wrath of Mark Lawrence et al by daring to post my opinions.) >> But it is an optimisation that /could/ be done by the byte-code compiler > I would also expect that Victor Stinner's FAT Python project will > (eventually) look at optimizing such for-loops too. If you see something > like: > > for i in range(N): > do_stuff() > > > and three conditions hold: > > (1) i is unused in the loop body; > > (2) range is still bound to the expected built-in function, and no > other "range" in a nearer scope (say, a local variable called "range", or a > global) exists to shadow it; and The volatility of 'range' I'd completely forgotten about. Python really doesn't make this stuff easy, does it? Checking this at runtime, per loop (I don't think it's necessary per iteration) is a possibility, but now an extra overhead is introduced. It might worth it if the body of the loop is also optimised, but this is getting into the territory covered by tracing JITs. My kind of approach would try to keep it simple, and that would be helped tremendously by special language constructs (something like Ruby's 100.times) where you can use a streamlined loop, and possible unrolling, straight off. (Personally, if I was creating a byte-code intepreter for Python as-is, I would have a -dynamic:on or -dynamic:off switch.) > Here is one of the oldest: > > http://www.ibm.com/developerworks/library/l-psyco/index.html Yes, I tried that long ago. It's very fast on certain benchmarks. (Both psyco and pypy can run my lexer at around 170Klps. And this is code using string compares and long if-elif chains, that would be crazy in any other language. From that point of view, it's very impressive (I can only get half that speed using the same methods). -- Bartc From PointedEars at web.de Fri Mar 25 18:25:42 2016 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Fri, 25 Mar 2016 23:25:42 +0100 Subject: WP-A: A New URL Shortener References: <1537bd9e261.12a0e5b4a204345.4468160629979098801@vmesel.com> <500E8DF1-DCAC-4923-BD94-06DA1716484A@vmesel.com> <1964524.jFVgOtWIx9@PointedEars.de> <2334208.C0ktZ5B2k1@PointedEars.de> <4500052.tJGngFWhWt@PointedEars.de> Message-ID: <7663219.M9yg8PEDtW@PointedEars.de> Chris Angelico wrote: > On Sat, Mar 26, 2016 at 8:28 AM, Thomas 'PointedEars' Lahn > wrote: >> Chris Angelico wrote: >>> [?] Thomas 'PointedEars' Lahn [?] wrote: >>>> Chris Angelico wrote: >>>>> [?] Thomas 'PointedEars' Lahn [?] wrote: >>>>>> Daniel Wilcox wrote: >>>>>>> Cool thanks, highly recommended to use an ORM to deter easy SQL >>>>>>> injections. >>>>>> That is to crack a nut with a sledgehammer. SQL injection can be >>>>>> easily and more efficiently prevented with prepared statements. [?] >>>>> You don't even need prepared statements. All you need is parameterized >>>>> queries. >>>> A prepared statement in this context uses a parameterized query. >>>> >>>> >> >>> >>> I know what a prepared statement is. And I know that they are >>> effective. However they are overkill - as I said, you merely need >>> parameterization. >> >> Then enlighten me, please: How is ?parameterization? or a ?parameterized >> query?, as *you* understand it, different from a prepared statement? > > This is a prepared statement: > > http://www.postgresql.org/docs/current/static/sql-prepare.html > > You use a special "PREPARE" query to create *and store* a half-run > query, [Having written a database layer (in PHP) myself, I know what a prepared statement is, thank you very much.] Your statement is incorrect both for MySQL (which I know) and PostgreSQL (AIUI your reference): The query is processed and stored of course, but it is definitely _not_ *run* before the EXECUTE command is issued for it. > and then you execute it afterwards. In both DMBSs, the query/statement is filled with parameter values and then executed not before, and then only if and when, one issues the EXECUTE statement for it. > Back in the 1990s, I had the option of actually *compiling* my SQL queries > as part of my C code, which would prepare all the queries for future > execution. It is completely different from the dynamic parameterized > queries that most people use. Interesting, but irrelevant. > Parameterization is a more general concept which prepared statements > invariably use, but which general code need not use. If it is to be safe from SQL injection, it better uses a parameterized query as it is *commonly* understood. > A Python database connector could choose to PREPARE/EXECUTE for every > query it's given, That would not be wise, given that not every query contains variable parameters. > or it could choose to escape all the parameters and embed them, Recommended against, and not a parameterized query at all. > or it could (if it's using a decent database back-end like PostgreSQL) > simply send the query and its associated parameters as-is. Only one of > these options is a "prepared statement". Maybe. I do not know enough about PostgreSQL and its ?[sending] the query and its associated parameters as-is? yet to confirm or deny this. > All three are "parameterized queries", at least from the POV of Python > code. You are mistaken, then: Of the three kinds of ?parameterized queries? as *you* understand them (OWASP and I beg to differ), at least one of them that is not used in a prepared statement is *insufficient to prevent SQL injection*. The second kind also moves tasks to the programming language that are better done by the DBMS; the program code should database-agnostic (in the best case, for mockup testing, even oblivious of the database). Which is why programming languages have come to support prepared statements, and why OWASP recommends to use either them or stored procedures. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail.y From rosuav at gmail.com Fri Mar 25 19:04:06 2016 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 26 Mar 2016 10:04:06 +1100 Subject: WP-A: A New URL Shortener In-Reply-To: <7663219.M9yg8PEDtW@PointedEars.de> References: <1537bd9e261.12a0e5b4a204345.4468160629979098801@vmesel.com> <500E8DF1-DCAC-4923-BD94-06DA1716484A@vmesel.com> <1964524.jFVgOtWIx9@PointedEars.de> <2334208.C0ktZ5B2k1@PointedEars.de> <4500052.tJGngFWhWt@PointedEars.de> <7663219.M9yg8PEDtW@PointedEars.de> Message-ID: On Sat, Mar 26, 2016 at 9:25 AM, Thomas 'PointedEars' Lahn wrote: > Chris Angelico wrote: > >> On Sat, Mar 26, 2016 at 8:28 AM, Thomas 'PointedEars' Lahn >> wrote: >>> Chris Angelico wrote: >>>> [?] Thomas 'PointedEars' Lahn [?] wrote: >>>>> Chris Angelico wrote: >>>>>> [?] Thomas 'PointedEars' Lahn [?] wrote: >>>>>>> Daniel Wilcox wrote: >>>>>>>> Cool thanks, highly recommended to use an ORM to deter easy SQL >>>>>>>> injections. >>>>>>> That is to crack a nut with a sledgehammer. SQL injection can be >>>>>>> easily and more efficiently prevented with prepared statements. [?] >>>>>> You don't even need prepared statements. All you need is parameterized >>>>>> queries. >>>>> A prepared statement in this context uses a parameterized query. >>>>> >>>>> >>> > >>>> >>>> I know what a prepared statement is. And I know that they are >>>> effective. However they are overkill - as I said, you merely need >>>> parameterization. >>> >>> Then enlighten me, please: How is ?parameterization? or a ?parameterized >>> query?, as *you* understand it, different from a prepared statement? >> >> This is a prepared statement: >> >> http://www.postgresql.org/docs/current/static/sql-prepare.html >> >> You use a special "PREPARE" query to create *and store* a half-run >> query, > > [Having written a database layer (in PHP) myself, I know what a prepared > statement is, thank you very much.] > > Your statement is incorrect both for MySQL (which I know) and PostgreSQL > (AIUI your reference): The query is processed and stored of course, but it > is definitely _not_ *run* before the EXECUTE command is issued for it. It legal to partly perform the query. DB2 can retain a "query plan" which consists of the exact paths it will follow. So I stand by my statement. >> Back in the 1990s, I had the option of actually *compiling* my SQL queries >> as part of my C code, which would prepare all the queries for future >> execution. It is completely different from the dynamic parameterized >> queries that most people use. > > Interesting, but irrelevant. Not really, no. It was a form of PREPARE/EXECUTE that hid the PREPARE behind a convenient syntax, and then replaced it with EXECUTE for the run-time. >> Parameterization is a more general concept which prepared statements >> invariably use, but which general code need not use. > > If it is to be safe from SQL injection, it better uses a parameterized query > as it is *commonly* understood. Why? All it needs to do is guarantee that no user data can affect the query. There are myriad ways to do that, and prepared statements are only one of them. Even parameterization is not strictly necessary, as long as the escaping is perfect. (Though that does have its own consequences, and is not recommended.) >> A Python database connector could choose to PREPARE/EXECUTE for every >> query it's given, > > That would not be wise, given that not every query contains variable > parameters. Irrelevant. It would still be legal. Do you understand the difference between what is legal according to a specification and what is actually worth doing? In an explanation of what a parameterized query is, I would expect to be discussing what is semantically and functionally valid, not which optimizations are worth doing. >> or it could choose to escape all the parameters and embed them, > > Recommended against, and not a parameterized query at all. Not once it reaches the underlying database, but it is parameterized in the source code. It's not possible for an external attacker to get past the escaping, if it is done correctly. It is still legal, however, it is indeed not recommended. >> or it could (if it's using a decent database back-end like PostgreSQL) >> simply send the query and its associated parameters as-is. Only one of >> these options is a "prepared statement". > > Maybe. I do not know enough about PostgreSQL and its ?[sending] the query > and its associated parameters as-is? yet to confirm or deny this. The wire protocol supports this. >> All three are "parameterized queries", at least from the POV of Python >> code. > > You are mistaken, then: Of the three kinds of ?parameterized queries? as > *you* understand them (OWASP and I beg to differ), at least one of them > that is not used in a prepared statement is *insufficient to prevent SQL > injection*. Okay, then. Please explain how this code is vulnerable to SQL injection: conn = some_db_module.connect("") cur = conn.cursor() data = input("Enter a value: ") cur.execute("insert into some_table (some_column) values (%s)", (input,)) conn.commit() Do you need to know the implementation of cur.execute to be able to say whether this is safe, or can you be confident that, short of really blatantly obvious bugs in the database connector, this is genuinely a parameterized query? I posit that the latter is the case. MY CODE has a query with a parameter. After that, it's not my problem; attacks on lower-level services are always possible, but aren't called "SQL injection". > The second kind also moves tasks to the programming language that are better > done by the DBMS; the program code should database-agnostic (in the best > case, for mockup testing, even oblivious of the database). > > Which is why programming languages have come to support prepared statements, > and why OWASP recommends to use either them or stored procedures. What would you change in the above code? Does it really need prepared statements or stored procedures? Surely the recommendation of Python is to keep things simple and expressive? ChrisA From ned at nedbatchelder.com Fri Mar 25 19:36:03 2016 From: ned at nedbatchelder.com (Ned Batchelder) Date: Fri, 25 Mar 2016 16:36:03 -0700 (PDT) Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: <5038313.yTPFmuZgmt@PointedEars.de> References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <5038313.yTPFmuZgmt@PointedEars.de> Message-ID: <09151817-fc79-4077-89a0-66e0c6551f9f@googlegroups.com> On Friday, March 25, 2016 at 5:17:21 PM UTC-4, Thomas 'PointedEars' Lahn wrote: > cl at isbd.net wrote: > > > Occasionally I have to make forays into Javascript, can anyone > > recommend a place similar to this list where Javascript questions can > > be asked? The trouble is that there are very many usenet Javascript > > lists and it's difficult to guess which one[es] might be good. > > There is no Javascript. > > There are no Usenet lists. > > This is not only a Python *mailing* list, it is also mirrored as an > international Usenet _newsgroup_, (which I am > reading). > > If you can accept all of that, then the international Usenet _newsgroup_ > (where I am posting primarily) is for you. > So are other national/language-specific newsgroups on the JavaScripts and > other ECMAScript implementations. In your newsreader, search for newsgroups > whose name contains "javascript". > > Next time, read and STFW first, and get a real name. Chris, I apologize for Thomas. His main goal on this list seems to be pointing out when people are wrong, over the smallest details. His secondary goal is enforcing some imaginary rule about real names, though he couldn't be bothered to read your post thoroughly enough to discover yours. Thomas is not typical of the Python community. We are mostly nice people. :) --Ned. From marcosullaroma at gmail.com Fri Mar 25 20:18:47 2016 From: marcosullaroma at gmail.com (Marco Sulla) Date: Sat, 26 Mar 2016 01:18:47 +0100 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56f27d76$0$1600$c3e8da3$5496439d@news.astraweb.com> References: <56f27d76$0$1600$c3e8da3$5496439d@news.astraweb.com> Message-ID: > That's a very superficial similarity: a list ['a', 'b', 'x', 'y'] is > something like a mapping {0: 'a', 1: 'b', 2: 'x', 3: 'y'}. Seems logical, > since in both cases we write collection[2] and get 'x' back. > > But think about it a bit more, and you will see that the behaviour is in > fact *very different*. For example: > > the_list = ['a', 'b', 'x', 'y'] > # the_list is equivalent to {0: 'a', 1: 'b', 2: 'x', 3: 'y'} > the_list.insert(0, 'z') > # the_list is now equivalent to {0: 'z', 1: 'a', 2: 'b', 3: 'x', 4: 'y'} > > Every existing "key:value" pair has changed! What sort of mapping operates > like that? It's like you said: "Animals with four legs can usually run, eat etc. But birds can fly! What sort of animal flies?" Well. birds. You can easily extend dict and create a new class that imitate list, tuple or str without any problem. Sequences are an extension of maps. > Have you ever actually wanted to use sequences or maps indifferently? To do > what? Not my code, but this is an example: https://github.com/thieman/dagobah/blob/master/dagobah/daemon/daemon.py def replace_nones(dict_or_list), line 27 On 23 March 2016 at 12:26, Steven D'Aprano wrote: > On Wed, 23 Mar 2016 06:54 am, Marco S. wrote: > > > I noticed that the sequence types does not have these methods that the > map > > types has: get(), items(), keys(), values(). > > > > It could seem useless to have them for sequences, > > That's putting it mildly. > > > but I think it will ease > > the creation of functions and methods that allow you to input a generic > > iterable as parameter, but needs to use one of these methods in case the > > parameter is a map. > > Perhaps it would. But countering that is the disadvantage that you're > adding > methods to sequences that have no sensible meaning for a sequence. > > Strings and floats are quite different things, but occasionally it makes > sense to write a function that accepts either a string or a float. Perhaps > we could introduce methods to strings and floats to blur the difference, > to "ease the creation of functions and methods that allow you to input a > generic scalar (string, float, int) as parameter..."? > > Some of these methods would be easy: > > class float: > def upper(self): > return self > > > Some a bit more work: > > def find(self, substring, start, end): > s = str(self) > return s.find(substring, start, end) > > but some perplex me. What would (27.25).expand_tabs() do? > > > Of course this is silly. Even Perl and Javascript don't go this far in > making floats and strings interchangeable. This is a good thing: if you're > calling some_float.upper(), you've almost certainly made a programming > error, and you don't want this nonsensical method call to silently succeed. > > So it is with sequences and mappings. They are *not* the same sort of > thing, > even though they have a few superficial similarities, and they shouldn't > try to behave as the same thing. > > What should some_dict.append(None) do? The very concept is nonsense: dicts > aren't *ordered sequences*, you can't append to a dict. Maybe you could > give dicts a method *called* "append", but it wouldn't mean the same thing > as list.append, and it probably wouldn't have the same signature: > > > list.append(value) > Appends value to the end of the list. > > dict.append(key, value) > Adds a new key to the dict, with the given value. > Same as dict[key] = value. > > > Forcing these two completely different methods to have the same name > doesn't > do anything useful. That's like putting a door handle on your iPhone, in > case some day you want to treat your iPhone as a door. > > > > In one word, it will facilitate duck typing. > > I think you have misunderstood the purpose and meaning of duck-typing. > > Duck-typing is not about forcing unrelated, dissimilar types to have the > same interface just in case you want to write a function that will accept > either type. > > Duck-typing is about accepting anything which "quacks like a duck". If all > you need is something which lays an egg, you shouldn't care whether it is a > chicken or a goose or a duck. It doesn't mean that dogs and cats should > have a "lay_egg" method, just in case somebody wants to accept a duck or a > dog. > > > > For the same reason, I would suggest the introduction of a new map type, > > vdict, a dict that by default iterates over values instead over keys. So > a > > vdict object "d" wiil have iter(d) == iter(d.values()), and should also > > have a count() method, like sequence types. > > I don't really see the point in this. What sort of function will expect to > iterate over a mapping, but not care whether it is getting keys or values? > > Sure, there are generic functions that will iterate over *any iterable*, > and > you can pass dict.keys() or dict.values(), and both will work fine. That's > exactly what duck-typing is about. > > But let's imagine this hypothetical function that will accept any mapping, > and some mappings will iterate over keys and some mappings iterate over > values. What would you do with it? > > def walk(the_dict): > for obj in the_dict: > print("Key =", obj) # That's wrong, it might be a value. > value = the_dict[obj] # That's wrong too. > the_dict[obj] = "processed" # Still wrong. > > > There's nothing useful or interesting you can do with a mapping and > something which might be a key, or might be a value, but you don't know > which. You can treat them in isolation, as if they had nothing to do with a > dict, and that's about it. But in that case, why insist on a dict? > > walk(the_dict.keys()) > walk(the_dict.values()) > walk(the_list) > walk(the_iterator) > > > > Indeed sequences are, in my humble opinion, a specialized case of maps, > > when keys are numeric only, are always contiguous without gaps and start > > from 0. > > That's a very superficial similarity: a list ['a', 'b', 'x', 'y'] is > something like a mapping {0: 'a', 1: 'b', 2: 'x', 3: 'y'}. Seems logical, > since in both cases we write collection[2] and get 'x' back. > > But think about it a bit more, and you will see that the behaviour is in > fact *very different*. For example: > > the_list = ['a', 'b', 'x', 'y'] > # the_list is equivalent to {0: 'a', 1: 'b', 2: 'x', 3: 'y'} > the_list.insert(0, 'z') > # the_list is now equivalent to {0: 'z', 1: 'a', 2: 'b', 3: 'x', 4: 'y'} > > Every existing "key:value" pair has changed! What sort of mapping operates > like that? > > del the_list[2] > # the_list is now equivalent to {0: 'z', 1: 'a', 2: 'x', 3: 'y'} > > I've said to delete the "key" 2, but there it still is. "Key" 2 still > exists, it just has a different value! And it is "key" 4 which has been > deleted! But not the *value* attached to "key" 4, that's been moved to 3! > > What sort of crazy mapping behaves like this? > > The answer is, of course, *no* sort of mapping. Sequences are not mappings. > The only reason we think of them as kinda-sorta like mappings is because of > a superficial similarity between key:value and index:item. That similarity > is real, but virtually everything else about mappings and sequences is > different. > > > > > This way we will have a simpler way to let people to use sequences > > or maps indifferently, and let the code untouched. > > Have you ever actually wanted to use sequences or maps indifferently? To do > what? > > The only case I've ever seen of that is the dict constructor, and > dict.update, which will accept either a mapping or a sequence of (key, > value) pairs. > > > > > -- > Steven > > -- > https://mail.python.org/mailman/listinfo/python-list > From marcosullaroma at gmail.com Fri Mar 25 20:35:33 2016 From: marcosullaroma at gmail.com (Marco Sulla) Date: Sat, 26 Mar 2016 01:35:33 +0100 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56f27d76$0$1600$c3e8da3$5496439d@news.astraweb.com> References: <56f27d76$0$1600$c3e8da3$5496439d@news.astraweb.com> Message-ID: Peter Otten wrote: >> I noticed that the sequence types does not have these methods that the map >> types has: get(), items(), keys(), values(). >> It could seem useless to have them for sequences, but I think it will ease >> the creation of functions and methods that allow you to input a generic >> iterable as parameter, but needs to use one of these methods in case the >> parameter is a map. > It will also break existing uses of duck typing. Yes, I suppose it's too late to introduce these methods to sequences. I'd like to see vdict implemented anyway. It can't break old code and add a map type that has a common interface with sequences. From PointedEars at web.de Fri Mar 25 21:36:53 2016 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Sat, 26 Mar 2016 02:36:53 +0100 Subject: [OT'ish] Is there a list as good as this for Javascript References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <5038313.yTPFmuZgmt@PointedEars.de> <09151817-fc79-4077-89a0-66e0c6551f9f@googlegroups.com> Message-ID: <1686453.n4820qZuCL@PointedEars.de> Ned Batchelder wrote: > Chris, I apologize for Thomas. How dare you to speak for me, and *again* the rest of the subscribers? There is nothing to apologize for when I am *helping* someone by giving them useful information. You can apologize for your own presumptous behavior instead. > is main goal on this list seems to be pointing out when people are wrong, > over the smallest details. Certainly I point out when people are wrong. That is how we develop *knowledge*. For that it does not matter of you in your blissful ignorance think that those are ?smallest details?, which they are not. The underlying process is called *learning*. You should try it sometime. > His secondary goal is enforcing some imaginary rule about real names, It is not an imaginary rule, it is a social convention that follows from another social convention, simple politeness. When you are seeking the help of people that you do not know, there is a principle of basic politeness saying that you should tell them who you are. Especially if those people have already extended you the politeness to tell them who *they* are; like here, when you have read their names already. Politeness is another thing you should try sometime, as I see that, your having no valid argument at all, you like to throw dirt instead. > Thomas is not typical of the Python community. We are mostly nice people. > :) You do not even know me. I *am* a nice person, if only for the fact that I do not let people suffer from their own ignorance, and I encourage them to educate and enlighten themselves in order not be dependent on people like you who tell them what they should think. So *evidentially*, *you* are not a nice person. According to your own "logic", *you* do not belong in the Python community. Go away. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From breamoreboy at yahoo.co.uk Fri Mar 25 21:42:37 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 26 Mar 2016 01:42:37 +0000 Subject: Problem With Embedded Icon and Python 3.4 In-Reply-To: References: Message-ID: On 25/03/2016 05:10, Wildman via Python-list wrote: > I have a program that I have been trying to rewrite so it will > run on Python 2.7 and 3.4. This http://pythonhosted.org/six/ might come in handy in future. As I'm also climbing the tkinter cliff at the moment I've found anything on stackoverflow from Bryan Oakley to be very helpful. In particular, his answer here http://stackoverflow.com/questions/17466561/best-way-to-structure-a-tkinter-application really helped me get a grip on things. A lot of the examples here http://pyinmyeye.blogspot.co.uk/ were also useful. HTH. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From steve at pearwood.info Fri Mar 25 22:14:12 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Mar 2016 13:14:12 +1100 Subject: [OT'ish] Is there a list as good as this for Javascript References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <5038313.yTPFmuZgmt@PointedEars.de> Message-ID: <56f5f074$0$1595$c3e8da3$5496439d@news.astraweb.com> On Sat, 26 Mar 2016 08:17 am, PointedEars wrote: ..............................^^^^^^^^^^^ > get a real name. You sign your posts "PointedEars". Do you not realise how hypocritical these repeated carping complaints about "real names" are? Not to mention pointless. Aside from the fact that "real name" is subjective, you have no idea what is someone's real name and what isn't. Nobody appointed you as Real Name Sheriff. Just give it up. -- Steven From steve at pearwood.info Fri Mar 25 22:19:37 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Mar 2016 13:19:37 +1100 Subject: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?) References: <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f565e4$0$1614$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f5f1ba$0$1621$c3e8da3$5496439d@news.astraweb.com> On Sat, 26 Mar 2016 09:08 am, BartC wrote: > On 25/03/2016 16:22, Steven D'Aprano wrote: >> On Fri, 25 Mar 2016 10:06 pm, BartC wrote: > > (OK, I'll risk the wrath of Mark Lawrence et al by daring to post my > opinions.) Please ignore Mark Lawrence when he is acting as an obnoxious troll, as he is now. He occasionally has something useful or helpful to say, but most of the time he thinks he is the self-appointed Guardian of Python's Honour, a job he is singularly ill-equipped for even if Python's honour needed defending, which it doesn't. >>> But it is an optimisation that /could/ be done by the byte-code compiler > >> I would also expect that Victor Stinner's FAT Python project will >> (eventually) look at optimizing such for-loops too. If you see something >> like: >> >> for i in range(N): >> do_stuff() >> >> >> and three conditions hold: >> >> (1) i is unused in the loop body; >> >> (2) range is still bound to the expected built-in function, and no >> other "range" in a nearer scope (say, a local variable called "range", or >> a global) exists to shadow it; and > > The volatility of 'range' I'd completely forgotten about. Python really > doesn't make this stuff easy, does it? True. But it makes *other things* much more easy. Things which are impossible or very difficult in other, stricter languages are trivially easy in Python. > Checking this at runtime, per loop (I don't think it's necessary per > iteration) is a possibility, but now an extra overhead is introduced. It > might worth it if the body of the loop is also optimised, but this is > getting into the territory covered by tracing JITs. Detecting whether or not range has been shadowed or replaced doesn't need a full tracing JIT. Victor's work isn't complete, but preliminary results suggest strongly that the overhead of checking guards will be insignificant. > My kind of approach would try to keep it simple, and that would be > helped tremendously by special language constructs (something like > Ruby's 100.times) where you can use a streamlined loop, and possible > unrolling, straight off. Ruby is an interesting case, because Ruby is even more dynamic than Python. Python doesn't allow you to replace or add methods to built-ins, but Ruby does, so in principle, you have no idea what 100.times is going to do until runtime. That's no different from Python and range. Up until a few years ago, Ruby was considered even slower than Python, by a factor of two or five or so. I'm lead to believe that the latest version of Ruby reverses that, and I've seen claims that it is now faster than Python, but I haven't seen it for myself so I'm not sure if I believe it entirely. > (Personally, if I was creating a byte-code intepreter for Python as-is, > I would have a -dynamic:on or -dynamic:off switch.) > >> Here is one of the oldest: >> >> http://www.ibm.com/developerworks/library/l-psyco/index.html > > Yes, I tried that long ago. It's very fast on certain benchmarks. (Both > psyco and pypy can run my lexer at around 170Klps. And this is code > using string compares and long if-elif chains, that would be crazy in > any other language. From that point of view, it's very impressive (I can > only get half that speed using the same methods). The Python philosophy seems to prefer the use of specialist JIT compilers to speed up bottlenecks rather than language features. I've seen Guido comment that he doesn't believe static AOT optimization is worthwhile in Python and that people should concentrate on JIT optimizations. I suspect he's right. -- Steven From best_lay at yahoo.com Fri Mar 25 22:37:41 2016 From: best_lay at yahoo.com (Wildman) Date: Fri, 25 Mar 2016 21:37:41 -0500 Subject: Problem With Embedded Icon and Python 3.4 References: Message-ID: On Sat, 26 Mar 2016 01:42:37 +0000, Mark Lawrence wrote: > On 25/03/2016 05:10, Wildman via Python-list wrote: >> I have a program that I have been trying to rewrite so it will >> run on Python 2.7 and 3.4. > > This http://pythonhosted.org/six/ might come in handy in future. > > As I'm also climbing the tkinter cliff at the moment I've found anything > on stackoverflow from Bryan Oakley to be very helpful. In particular, > his answer here > http://stackoverflow.com/questions/17466561/best-way-to-structure-a-tkinter-application > really helped me get a grip on things. > > A lot of the examples here http://pyinmyeye.blogspot.co.uk/ were also > useful. > > HTH. Thanks for the links. Good stuff. Bookmarked. -- GNU/Linux user #557453 The cow died so I don't need your bull! From steve at pearwood.info Fri Mar 25 22:46:52 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Mar 2016 13:46:52 +1100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> Message-ID: <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> On Sat, 26 Mar 2016 03:57 am, Marko Rauhamaa wrote: > Steven D'Aprano : > >> Undefined behaviour in C is a minefield waiting to blow your program's >> legs off, because the designers of the language made the explicit >> choice that they wanted the language to be as fast and efficient as >> possible, even at the cost of safe, reproducible behaviour. > > Yes, although the same could be true for Python as well. Is this a philosophical question? Yes, it *could* be true, in some alternate universe, but it isn't actually true. Python does not have undefined behaviour in the C sense. Like any language which doesn't have a formal IEEE standard behind it (and even some that do), it has implementation-specific behaviour, or under- or unspecified behaviour. But that is not the same as C Undefined Behaviour. Please read the links I gave. Culturally, C compiler writers have a preference for using undefined behaviour to allow optimizations, even if it means changing the semantics of your code. The C compiler is allowed to ignore your code, move it around so that things happen in a different order, or add its own code, even if that changes the semantics of the code. Python has nothing even remotely like that. If you shoot yourself in the foot with Python, you can say it is because you didn't understand what your code would do, but you can't say it is because Python moved code around to execute it in an unexpected order, or ignored it. > For example, you could have this program: > > ===begin poof.py======================================================== > assert 1 < 0 > ===end poof.py========================================================== The semantics of "assert condition" are equivalent to: if __debug__: if not condition: raise AssertionError so assert is intentionally a no-op when Python runs with debug mode disabled (the -O command-line switch). > When it is run, you might see this: > > ======================================================================== > $ python3 poof.py > python3: the VM vanished in a puff of logic while executing 'poof.py' > ======================================================================== I assume that the "vanished" quip is your editorial. Otherwise, the only way to get that result would be if you linked the python3 executable to something other than Python 3. There are only two behaviours a conforming Python interpreter can do with "poof.py": - by default, it must raise AssertionError; - if run with optimizations switched on (debugging mode turned off), it must do nothing. Anything else would be a bug in the interpreter or compiler. -- Steven From random832 at fastmail.com Fri Mar 25 22:56:51 2016 From: random832 at fastmail.com (Random832) Date: Fri, 25 Mar 2016 22:56:51 -0400 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1458961011.4138644.560041034.26640549@webmail.messagingengine.com> On Fri, Mar 25, 2016, at 22:46, Steven D'Aprano wrote: > Culturally, C compiler writers have a preference for using undefined > behaviour to allow optimizations, even if it means changing the semantics > of your code. The C compiler is allowed to ignore your code, move it > around > so that things happen in a different order, or add its own code, even if > that changes the semantics of the code. Er, the point of undefined behavior is that your code doesn't *have* semantics. From no.email at nospam.invalid Fri Mar 25 22:59:23 2016 From: no.email at nospam.invalid (Paul Rubin) Date: Fri, 25 Mar 2016 19:59:23 -0700 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87io0a6j1w.fsf@nightsong.com> Steven D'Aprano writes: > Culturally, C compiler writers have a preference for using undefined > behaviour to allow optimizations, even if it means changing the semantics > of your code. If your code has UB then by definition it has no semantics to change. Code with UB has no meaning. From rosuav at gmail.com Fri Mar 25 23:16:45 2016 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 26 Mar 2016 14:16:45 +1100 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: <1686453.n4820qZuCL@PointedEars.de> References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <5038313.yTPFmuZgmt@PointedEars.de> <09151817-fc79-4077-89a0-66e0c6551f9f@googlegroups.com> <1686453.n4820qZuCL@PointedEars.de> Message-ID: On Sat, Mar 26, 2016 at 12:36 PM, Thomas 'PointedEars' Lahn wrote: >> Thomas is not typical of the Python community. We are mostly nice people. >> :) > > You do not even know me. I *am* a nice person, if only for the fact that I > do not let people suffer from their own ignorance, and I encourage them to > educate and enlighten themselves in order not be dependent on people like > you who tell them what they should think. > > So *evidentially*, *you* are not a nice person. According to your own > "logic", *you* do not belong in the Python community. Go away. King Gama is a nicer person than you are, and in very similar ways. ChrisA From PointedEars at web.de Fri Mar 25 23:30:11 2016 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Sat, 26 Mar 2016 04:30:11 +0100 Subject: WP-A: A New URL Shortener References: <1537bd9e261.12a0e5b4a204345.4468160629979098801@vmesel.com> <500E8DF1-DCAC-4923-BD94-06DA1716484A@vmesel.com> <1964524.jFVgOtWIx9@PointedEars.de> <2334208.C0ktZ5B2k1@PointedEars.de> <4500052.tJGngFWhWt@PointedEars.de> <7663219.M9yg8PEDtW@PointedEars.de> Message-ID: <2279730.a2M0GptDFN@PointedEars.de> Chris Angelico wrote: > On Sat, Mar 26, 2016 at 9:25 AM, Thomas 'PointedEars' Lahn > wrote: Attribution line, not attribution novel. >> Chris Angelico wrote: >>> On Sat, Mar 26, 2016 at 8:28 AM, Thomas 'PointedEars' Lahn >>> wrote: >>>> Then enlighten me, please: How is ?parameterization? or a >>>> ?parameterized query?, as *you* understand it, different from a >>>> prepared statement? >>> >>> This is a prepared statement: >>> >>> http://www.postgresql.org/docs/current/static/sql-prepare.html >>> >>> You use a special "PREPARE" query to create *and store* a half-run >>> query, >> >> [Having written a database layer (in PHP) myself, I know what a prepared >> statement is, thank you very much.] >> >> Your statement is incorrect both for MySQL (which I know) and PostgreSQL >> (AIUI your reference): The query is processed and stored of course, but >> it is definitely _not_ *run* before the EXECUTE command is issued for it. > > It legal to partly perform the query. What are you getting at? A query cannot be performed if the values of its parameters have no defined value yet. > DB2 can retain a "query plan" which consists of the exact paths it will > follow. So I stand by my statement. A query plan is _not_ the *execution* (?run?) of a query, but the result of *processing* a query (AISB). So you are still wrong. >>> Back in the 1990s, I had the option of actually *compiling* my SQL >>> queries as part of my C code, which would prepare all the queries for >>> future execution. It is completely different from the dynamic >>> parameterized queries that most people use. >> Interesting, but irrelevant. > > Not really, no. It was a form of PREPARE/EXECUTE that hid the PREPARE > behind a convenient syntax, and then replaced it with EXECUTE for the > run-time. IOW, a prepared statement. Thanks for the confirmation. >>> Parameterization is a more general concept which prepared statements >>> invariably use, but which general code need not use. >> >> If it is to be safe from SQL injection, it better uses a parameterized >> query as it is *commonly* understood. > > Why? [?] Far beyond the scope of this newsgroup/mailing list. RTFM I referred to. >>> A Python database connector could choose to PREPARE/EXECUTE for every >>> query it's given, >> That would not be wise, given that not every query contains variable >> parameters. > > Irrelevant. It would still be legal. Do you understand the difference > between what is legal according to a specification and what is > actually worth doing? Red herring. Legality (better: validity) was not the issue. Whether legal/valid code or or not, it would still not be wise because application performance would be reduced at little advantage, if any. >>> or it could choose to escape all the parameters and embed them, >> Recommended against, and not a parameterized query at all. > > Not once it reaches the underlying database, And that is not how ?parameterized query? is commonly defined. >>> All three are "parameterized queries", at least from the POV of Python >>> code. >> You are mistaken, then: Of the three kinds of ?parameterized queries? as >> *you* understand them (OWASP and I beg to differ), at least one of them >> that is not used in a prepared statement is *insufficient to prevent SQL >> injection*. > > Okay, then. Please explain how this code is vulnerable to SQL injection: > > conn = some_db_module.connect("") > cur = conn.cursor() > data = input("Enter a value: ") ^^^^^ > cur.execute("insert into some_table (some_column) values (%s)", (input,)) ^^^^^ > conn.commit() This code is not vulnerable to SQL injection, unless ?input? referred to an object that had both a suitable __call__() or __init__(), and __str__() method ;-> Probably you meant #--------------------------------------------------------------------------- conn = some_db_module.connect("") cur = conn.cursor() data = input("Enter a value: ") cur.execute("insert into some_table (some_column) values (%s)", (data,)) conn.commit() #--------------------------------------------------------------------------- Since nothing indicates the used module and accessed DBMS (only that, if it is Python code, the module cannot be sqlite3 as that does not support ?%s?), then this code can, if the module uses an escaping mechanism, still be vulnerable to SQL injection. For example, I could input something to the effect of #--------------------------------------------------------------------------- data = r'\"); DROP TABLE some_table; --' #--------------------------------------------------------------------------- if, for example, the string escaping mechanism in the module would simply duplicate any double-quote it finds to escape it in the string literal that it created (as is possible in MySQL and PostgreSQL), and still inject my code because the resulting query would be insert into some_table (some_column) values ("\""); DROP TABLE some_table; --") which is at least syntactically valid MySQL code, but from the perspective of the so-attacked it is still not fine as the table would be gone afterwards. See also: - - ;-) -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From PointedEars at web.de Fri Mar 25 23:37:20 2016 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Sat, 26 Mar 2016 04:37:20 +0100 Subject: [OT'ish] Is there a list as good as this for Javascript References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <5038313.yTPFmuZgmt@PointedEars.de> <09151817-fc79-4077-89a0-66e0c6551f9f@googlegroups.com> <1686453.n4820qZuCL@PointedEars.de> Message-ID: <3039159.EZm1bvJSo6@PointedEars.de> Chris Angelico wrote: > On Sat, Mar 26, 2016 at 12:36 PM, Thomas 'PointedEars' Lahn > wrote: >>> Thomas is not typical of the Python community. We are mostly nice >>> people. >>> :) >> >> You do not even know me. I *am* a nice person, if only for the fact that >> I do not let people suffer from their own ignorance, and I encourage them >> to educate and enlighten themselves in order not be dependent on people >> like you who tell them what they should think. >> >> So *evidentially*, *you* are not a nice person. According to your own >> "logic", *you* do not belong in the Python community. Go away. > > King Gama is a nicer person than you are, and in very similar ways. I do not know a person called ?King Gama?, I do not think I need to know them, I do not think that he is on-topic here either, and I think that you should keep in mind that this is not a niceness contest, but a technical newsgroup/mailing list. I for one prefer a direct, if blunt, correct answer over a nice, evading or incorrect one any time. See also: F'up2 poster -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From rosuav at gmail.com Fri Mar 25 23:46:38 2016 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 26 Mar 2016 14:46:38 +1100 Subject: WP-A: A New URL Shortener In-Reply-To: <2279730.a2M0GptDFN@PointedEars.de> References: <1537bd9e261.12a0e5b4a204345.4468160629979098801@vmesel.com> <500E8DF1-DCAC-4923-BD94-06DA1716484A@vmesel.com> <1964524.jFVgOtWIx9@PointedEars.de> <2334208.C0ktZ5B2k1@PointedEars.de> <4500052.tJGngFWhWt@PointedEars.de> <7663219.M9yg8PEDtW@PointedEars.de> <2279730.a2M0GptDFN@PointedEars.de> Message-ID: On Sat, Mar 26, 2016 at 2:30 PM, Thomas 'PointedEars' Lahn wrote: > Since nothing indicates the used module and accessed DBMS (only that, if it > is Python code, the module cannot be sqlite3 as that does not support ?%s?), > then this code can, if the module uses an escaping mechanism, still be > vulnerable to SQL injection. For example, I could input something to the > effect of > > #--------------------------------------------------------------------------- > data = r'\"); DROP TABLE some_table; --' > #--------------------------------------------------------------------------- > > if, for example, the string escaping mechanism in the module would simply > duplicate any double-quote it finds to escape it in the string literal that > it created (as is possible in MySQL and PostgreSQL), and still inject my > code because the resulting query would be > > insert into some_table (some_column) values ("\""); > DROP TABLE some_table; > --") > > which is at least syntactically valid MySQL code, but from the perspective > of the so-attacked it is still not fine as the table would be gone > afterwards. In other words, you are assuming that the string escaping *in the module* is buggy. Well, duh. This is exactly what I said about not having stupid bugs. The developer of a MySQL binding library should know the *entire* rules for escaping, and, duh, that's going to include escaping the backslash. So the escaped query would be something like: insert into some_table (some_column) values ("\\""); DROP TABLE some_table; --") which would be interpreted correctly by MySQL. ChrisA From rosuav at gmail.com Sat Mar 26 00:24:45 2016 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 26 Mar 2016 15:24:45 +1100 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: <3039159.EZm1bvJSo6@PointedEars.de> References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <5038313.yTPFmuZgmt@PointedEars.de> <09151817-fc79-4077-89a0-66e0c6551f9f@googlegroups.com> <1686453.n4820qZuCL@PointedEars.de> <3039159.EZm1bvJSo6@PointedEars.de> Message-ID: On Sat, Mar 26, 2016 at 2:37 PM, Thomas 'PointedEars' Lahn wrote: > Chris Angelico wrote: > >> On Sat, Mar 26, 2016 at 12:36 PM, Thomas 'PointedEars' Lahn >> wrote: >>>> Thomas is not typical of the Python community. We are mostly nice >>>> people. >>>> :) >>> >>> You do not even know me. I *am* a nice person, if only for the fact that >>> I do not let people suffer from their own ignorance, and I encourage them >>> to educate and enlighten themselves in order not be dependent on people >>> like you who tell them what they should think. >>> >>> So *evidentially*, *you* are not a nice person. According to your own >>> "logic", *you* do not belong in the Python community. Go away. >> >> King Gama is a nicer person than you are, and in very similar ways. > > I do not know a person called ?King Gama?, I do not think I need to know > them, I do not think that he is on-topic here either, and I think that you > should keep in mind that this is not a niceness contest, but a technical > newsgroup/mailing list. I for one prefer a direct, if blunt, correct answer > over a nice, evading or incorrect one any time. > > See also: > > > F'up2 poster Fine. You want a blunt answer? You, Thomas, are not a nice person. You think you are, but you are not. Be nicer or go away. Please. Also, go look up King Gama, as he's from a source that the Pythons follow. ChrisA From rustompmody at gmail.com Sat Mar 26 01:10:03 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 25 Mar 2016 22:10:03 -0700 (PDT) Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <5038313.yTPFmuZgmt@PointedEars.de> <09151817-fc79-4077-89a0-66e0c6551f9f@googlegroups.com> <1686453.n4820qZuCL@PointedEars.de> <3039159.EZm1bvJSo6@PointedEars.de> Message-ID: <9a1e684a-2877-4520-8bb5-00853ef04996@googlegroups.com> On Saturday, March 26, 2016 at 9:55:15 AM UTC+5:30, Chris Angelico wrote: > On Sat, Mar 26, 2016 at 2:37 PM, Thomas 'PointedEars' Lahn wrote: > > Chris Angelico wrote: > > > >> On Sat, Mar 26, 2016 at 12:36 PM, Thomas 'PointedEars' Lahn wrote: > >>>> Thomas is not typical of the Python community. We are mostly nice > >>>> people. > >>>> :) > >>> > >>> You do not even know me. I *am* a nice person, if only for the fact that > >>> I do not let people suffer from their own ignorance, and I encourage them > >>> to educate and enlighten themselves in order not be dependent on people > >>> like you who tell them what they should think. > >>> > >>> So *evidentially*, *you* are not a nice person. According to your own > >>> "logic", *you* do not belong in the Python community. Go away. > >> > >> King Gama is a nicer person than you are, and in very similar ways. > > > > I do not know a person called "King Gama", I do not think I need to know > > them, I do not think that he is on-topic here either, and I think that you > > should keep in mind that this is not a niceness contest, but a technical > > newsgroup/mailing list. I for one prefer a direct, if blunt, correct answer > > over a nice, evading or incorrect one any time. > > > > See also: > > > > > > F'up2 poster > > Fine. You want a blunt answer? > > You, Thomas, are not a nice person. You think you are, but you are > not. Be nicer or go away. Please. "You think??" I think you just failed the Turing test Chris Do admit it though... Thomas 'juvenile' Lahn does a better job than Dihedral From rustompmody at gmail.com Sat Mar 26 01:30:06 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 25 Mar 2016 22:30:06 -0700 (PDT) Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> References: <8737rvxs89.fsf@elektro.pacujo.net> <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Friday, March 25, 2016 at 9:20:23 PM UTC+5:30, Steven D'Aprano wrote: > > Undefined behaviour in C is a minefield waiting to blow your program's legs > off, because the designers of the language made the explicit choice that > they wanted the language to be as fast and efficient as possible, even at > the cost of safe, reproducible behaviour. Thats a nice polemic Steven Ive been guilty of similar... which Ive subsequently tried to correct: http://blog.languager.org/2013/02/c-in-education-and-software-engineering.html For one thing its good to remember that we wouldn't be here without python Python wouldn't be what it is without CPython And the C there is the C you are talking of. More pertinently this polemic misses the real culprit -- intel hardware. 40 years ago Dijkstra pointed out that software costs are variable; hardware costs are fixed. this results in this that programmers will increasingly skip a test that is very skew. If that same super-skew test were taken care of by hardware we (programmers) wouldn't mind. [1] To see this consider overflow error for integers and for floats. Intel hardware catches float errors in hardware but not int errors So language designers have the hobson choice of catching errors at huge cost Or ignoring and (inviting programmers to ) creating flaky systems. [1] Economics/financial considerations drive more than we imagine https://www.facebook.com/EvolvePolitics/videos/1666350230283584/ From juandent at mac.com Sat Mar 26 01:31:57 2016 From: juandent at mac.com (Juan Dent) Date: Fri, 25 Mar 2016 23:31:57 -0600 Subject: PLEASE HELP -- TOTALLY NEW TO PYTHON Message-ID: <30049892-D089-451B-A839-03D825448588@mac.com> I am trying to run ?python cppdep.py? but get the following: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ analyzing dependencies among all components ... Traceback (most recent call last): File "cppdep.py", line 675, in main() File "cppdep.py", line 643, in main calculate_graph(digraph) File "cppdep.py", line 570, in calculate_graph (cycles, dict_node2cycle) = make_DAG(digraph, key_node) File "/Users/juandent/Downloads/cppdep-master/networkx_ext.py", line 79, in make_DAG for ind in range(len(subgraphs)-1, -1, -1): TypeError: object of type 'generator' has no len() Please, I know no python and am in a hurry to get this working? Please help Regards, Juan From marko at pacujo.net Sat Mar 26 04:37:55 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 26 Mar 2016 10:37:55 +0200 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87d1qh1voc.fsf@elektro.pacujo.net> Steven D'Aprano : > On Sat, 26 Mar 2016 03:57 am, Marko Rauhamaa wrote: >> Yes, although the same could be true for Python as well. > > Is this a philosophical question? Yes, it *could* be true, in some > alternate universe, but it isn't actually true. > > Python does not have undefined behaviour in the C sense. [...] >> For example, you could have this program: >> >> ===begin poof.py======================================================== >> assert 1 < 0 >> ===end poof.py========================================================== > > The semantics of "assert condition" are equivalent to: > > if __debug__: > if not condition: > raise AssertionError > > so assert is intentionally a no-op when Python runs with debug mode disabled > (the -O command-line switch). Thing is, some aggressive JITters might make extensive optimization decisions based on assertions. An assertion is a developers declaration of certain knowledge. It is there mainly to document design principles to fellow developers (including the original coder), but since the assertions have a formal content, the VM could allow itself to rely on them. For example, def g(n): assert type(n) is int assert 0 <= n < 256 return (n + 1) % 256 def f(n): return g(n)**2 The optimizer can optimize f() *knowing* its argument is an unsigned byte. Essentially, the JIT would boldly decide that AssertionError is never raised. (Although I would hate seeing such assertions routinely sprinkled everywhere.) > Anything else would be a bug in the interpreter or compiler. We'll see what the JITters cook up. Marko From nick.a.sarbicki at gmail.com Sat Mar 26 06:02:49 2016 From: nick.a.sarbicki at gmail.com (Nick Sarbicki) Date: Sat, 26 Mar 2016 10:02:49 +0000 Subject: How to make Python interpreter a little more strict? In-Reply-To: <20160325150608.21c3827a@fujitsu> References: <20160325150608.21c3827a@fujitsu> Message-ID: On Sat, Mar 26, 2016 at 9:59 AM Aleksander Alekseev wrote: > Hello > > Recently I spend half an hour looking for a bug in code like this: > > eax at fujitsu:~/temp$ cat ./t.py > #!/usr/bin/env python3 > > for x in range(0,5): > if x % 2 == 0: > next > print(str(x)) > > eax at fujitsu:~/temp$ ./t.py > 0 > 1 > 2 > 3 > 4 > > Is it possible to make python complain in this case? Or maybe solve > such an issue somehow else? > > -- > Best regards, > Aleksander Alekseev > http://eax.me/ > -- > https://mail.python.org/mailman/listinfo/python-list What would it be complaining about? I don't see any issues, it does what I would expect. From breamoreboy at yahoo.co.uk Sat Mar 26 06:23:17 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 26 Mar 2016 10:23:17 +0000 Subject: Interpretation In-Reply-To: References: Message-ID: On 25/03/2016 16:33, Dennis Ngeno wrote: > My programs have never combile, they keep telling me , systax error even > after copy pasting > Please show us your code and the exact syntax error. What Python version and OS are you using? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at yahoo.co.uk Sat Mar 26 06:29:09 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 26 Mar 2016 10:29:09 +0000 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: <56f27d76$0$1600$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 26/03/2016 00:35, Marco Sulla wrote: > > I'd like to see vdict implemented anyway. It can't break old code and add a > map type that has a common interface with sequences. > I cannot see this happening unless you provide a patch on the bug tracker. However I suspect you can get the same thing by subclassing dict. Why don't you try it and let us know how you get on? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From steve at pearwood.info Sat Mar 26 06:39:18 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Mar 2016 21:39:18 +1100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f666d8$0$1583$c3e8da3$5496439d@news.astraweb.com> On Sat, 26 Mar 2016 04:30 pm, Rustom Mody wrote: > For one thing its good to remember that we wouldn't be here without python > Python wouldn't be what it is without CPython There is nothing about Python that relies on the C standard being as it is. There are Python implementations that are not written in C or C++: Jython (Java) IronPython (C# for .Net or Mono) CLPython (Lisp) Berp (Haskell) I haven't included others (such as PyPy), as I'm not sure whether the language they are implemented in are self-hosting or not.and But those four at least (in principle) don't rely on C/C++ in any way, shape or form (except perhaps inspiration). It is an accident of history that Python's first and major implementation happens to be written in C. (Although its use as a glue language, allowing people to safely use libraries written in C, probably played a role in ensuring Python's success.) -- Steven From breamoreboy at yahoo.co.uk Sat Mar 26 06:39:38 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 26 Mar 2016 10:39:38 +0000 Subject: PLEASE HELP -- TOTALLY NEW TO PYTHON In-Reply-To: <30049892-D089-451B-A839-03D825448588@mac.com> References: <30049892-D089-451B-A839-03D825448588@mac.com> Message-ID: On 26/03/2016 05:31, Juan Dent wrote: > > I am trying to run ?python cppdep.py? but get the following: > > @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ > analyzing dependencies among all components ... > Traceback (most recent call last): > File "cppdep.py", line 675, in > main() > File "cppdep.py", line 643, in main > calculate_graph(digraph) > File "cppdep.py", line 570, in calculate_graph > (cycles, dict_node2cycle) = make_DAG(digraph, key_node) > File "/Users/juandent/Downloads/cppdep-master/networkx_ext.py", line 79, in make_DAG > for ind in range(len(subgraphs)-1, -1, -1): > TypeError: object of type 'generator' has no len() > > Please, I know no python and am in a hurry to get this working? Please help > > Regards, > Juan > for ind in range(len(list(subgraphs))-1, -1, -1): However please note that the above is often a code smell in Python. The usual style is:- for item in container: doSomething(item) Your actual problem would translate into something like:- for subgraph in reversed(subgraphs): doSomething(subgraph) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From kwpolska at gmail.com Sat Mar 26 06:40:55 2016 From: kwpolska at gmail.com (Chris Warrick) Date: Sat, 26 Mar 2016 11:40:55 +0100 Subject: How to make Python interpreter a little more strict? In-Reply-To: <20160325150608.21c3827a@fujitsu> References: <20160325150608.21c3827a@fujitsu> Message-ID: On 25 March 2016 at 13:06, Aleksander Alekseev wrote: > Hello > > Recently I spend half an hour looking for a bug in code like this: > > eax at fujitsu:~/temp$ cat ./t.py > #!/usr/bin/env python3 > > for x in range(0,5): > if x % 2 == 0: > next > print(str(x)) > > eax at fujitsu:~/temp$ ./t.py > 0 > 1 > 2 > 3 > 4 > > Is it possible to make python complain in this case? Or maybe solve > such an issue somehow else? > > -- > Best regards, > Aleksander Alekseev > http://eax.me/ > -- > https://mail.python.org/mailman/listinfo/python-list You were probably looking for `continue`. This is just bad memory on your part, and Python can?t help. In the REPL, typing an object name is legal and helpful. Other languages might crash, sure ? but they usually don?t have a REPL like Python does. That said, this code is designed badly. Here?s a better idea (also, note the fixed print statement): for x in range(0, 5): if x % 2 != 0: print(x) Or even with a more suitable range() that adds 2 instead of 1 in each step: for x in range(1, 5, 2): print(x) -- Chris Warrick PGP: 5EAAEA16 From sanaaabdullah21 at gmail.com Sat Mar 26 06:54:43 2016 From: sanaaabdullah21 at gmail.com (sanaaabdullah21 at gmail.com) Date: Sat, 26 Mar 2016 03:54:43 -0700 (PDT) Subject: Urgent Question Please Message-ID: <0ed5a1bd-e8a0-4785-9804-2ce2c6fd1310@googlegroups.com> Hi Python developers, I am trying to click on the testInstance button using pywinauto but I couldn't do it, even it returns empty list when I try to print the controllers . Here is what I tried: app = application.Application() app=app.Connect(path = r"C:\\hdmt\\tos_2.5.2.0_release\\tosrelease\\bin\\release\\HdstSiteGuiWPF.exe") #app.PrintControlIdentifiers() #app['Site Controller GUI Command Center - Version 2.5.2.0 OfflineLSM'].MenuSelect('Tools->TestInstance') #app.top_window_().PrintControlIdentifiers() #app.HdstSiteGuiWPF.MenuSelect("Tools->TestInstance") #app.HdstSiteGuiWPF.PrintControlIdentifiers() app['Site Controller GUI Command Center - Version: 2.5.2.0 OfflineLSM'].ToolsCenter.TestInstance.Click() #app.MenuSelect("Tools") From breamoreboy at yahoo.co.uk Sat Mar 26 06:55:09 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 26 Mar 2016 10:55:09 +0000 Subject: How to make Python interpreter a little more strict? In-Reply-To: <20160325150608.21c3827a@fujitsu> References: <20160325150608.21c3827a@fujitsu> Message-ID: On 25/03/2016 12:06, Aleksander Alekseev wrote: > Hello > > Recently I spend half an hour looking for a bug in code like this: > > eax at fujitsu:~/temp$ cat ./t.py > #!/usr/bin/env python3 > > for x in range(0,5): > if x % 2 == 0: > next > print(str(x)) > > eax at fujitsu:~/temp$ ./t.py > 0 > 1 > 2 > 3 > 4 > > Is it possible to make python complain in this case? Or maybe solve > such an issue somehow else? > How does the interpreter work out that you've typed 'next' instead of 'continue'? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From ned at nedbatchelder.com Sat Mar 26 07:37:48 2016 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sat, 26 Mar 2016 04:37:48 -0700 (PDT) Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: <3039159.EZm1bvJSo6@PointedEars.de> References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <5038313.yTPFmuZgmt@PointedEars.de> <09151817-fc79-4077-89a0-66e0c6551f9f@googlegroups.com> <1686453.n4820qZuCL@PointedEars.de> <3039159.EZm1bvJSo6@PointedEars.de> Message-ID: On Friday, March 25, 2016 at 11:37:34 PM UTC-4, Thomas 'PointedEars' Lahn wrote: > Chris Angelico wrote: > > > On Sat, Mar 26, 2016 at 12:36 PM, Thomas 'PointedEars' Lahn > > wrote: > >>> Thomas is not typical of the Python community. We are mostly nice > >>> people. > >>> :) > >> > >> You do not even know me. I *am* a nice person, if only for the fact that > >> I do not let people suffer from their own ignorance, and I encourage them > >> to educate and enlighten themselves in order not be dependent on people > >> like you who tell them what they should think. > >> > >> So *evidentially*, *you* are not a nice person. According to your own > >> "logic", *you* do not belong in the Python community. Go away. > > > > King Gama is a nicer person than you are, and in very similar ways. > > I do not know a person called "King Gama", I do not think I need to know > them, I do not think that he is on-topic here either, and I think that you > should keep in mind that this is not a niceness contest, but a technical > newsgroup/mailing list. I for one prefer a direct, if blunt, correct answer > over a nice, evading or incorrect one any time. Thomas, you don't have to choose between correct and nice. It's possible to be both. Even more important than being nice is being effective. Do you think your answers are achieving your goal? Are people learning from you? Are there ways more people could? I can see that you are knowledgeable, and I really appreciate the energy you put into answering questions. You are very generous with your time. But when you bark correct things at people, they don't hear you. Your helpful energy is being overshadowed by your blunt rude manner. If your goal is to help people, you are missing the mark. You say you "encourage them to educate and enlighten themselves." I haven't seen encouragement. I've seen scolding and sneering and shaming. Has anyone ever thanked you for, "There is no Javascript"? It's not helpful, it's just pedantic. Correct, yes; helpful? No. Was "STFW first" meant to be encouraging? You have a different definition of that word than I do. I understand the desire to be right, and to point out incorrect things. Heck, in writing this post I'm partly motivated by that desire. But how you say things has a huge effect on whether they are heard. If you don't care if you are heard or not, then why say anything? And if you *do* care if you are heard or not, then you have to take into account how people perceive you and your message. Has anyone ever said to you, "Thanks, Thomas! Lots of people were giving me answers, but they were all so kind and polite about it, I couldn't see what they were saying. Finally, your blunt direct manner got through to me, so now I understand." Of course not. It's absurd. Bluntness doesn't help learning. It just makes *you* feel good. Points of correctness are useless without points of connection. You have to talk to people in a way that they will hear. If you can't be bothered, then you are just wasting your time, and earning a negative reputation for yourself. But worse, you are tainting the reputation of this community. Someone comes here looking for an answer, or perhaps just comraderie, and they get greeted by a rude condescending technocrat. They don't just think, "Thomas is a jerk," they think, "Python people are jerks." That matters a lot to me. > See also: An excellent link! Have you read it? It applies to this very case. You screwed up on this community forum. I am telling you how you screwed up. And what you just did is "whine about the experience, claim to have been verbally assaulted, demand apologies, scream, ..." ESR's post exactly describes this situation, except you don't understand how we map onto the roles he describes. Perhaps you (and ESR) think that because this is a technical forum, all that matters is technical correctness. That's wrong. This is a place that people communicate, and how they communicate matters. In fact, if they can't communicate well, then none of the technical content matters at all. I'm sure you've heard this criticism before. You seem to have made up your mind that your way is right and that all of us criticizing you are wrong. I hope you'll take some of these points to heart anyway. We can use all the helpful knowledgable people we can get. I know I can't change you. But I can help set the tone in this forum. Mostly by modeling good behavior, but occasionally by directly addressing bad behavior. --Ned. From steve at pearwood.info Sat Mar 26 07:41:58 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Mar 2016 22:41:58 +1100 Subject: Suggestion: make sequence and map interfaces more similar References: <56f27d76$0$1600$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f67588$0$1591$c3e8da3$5496439d@news.astraweb.com> On Sat, 26 Mar 2016 11:18 am, Marco Sulla wrote: >> That's a very superficial similarity: a list ['a', 'b', 'x', 'y'] is >> something like a mapping {0: 'a', 1: 'b', 2: 'x', 3: 'y'}. Seems logical, >> since in both cases we write collection[2] and get 'x' back. Marco, it is considered polite to give attribution to the person you are quoting. In this case, that would be me. But it is still polite to say so. >> But think about it a bit more, and you will see that the behaviour is in >> fact *very different*. For example: >> >> the_list = ['a', 'b', 'x', 'y'] >> # the_list is equivalent to {0: 'a', 1: 'b', 2: 'x', 3: 'y'} >> the_list.insert(0, 'z') >> # the_list is now equivalent to {0: 'z', 1: 'a', 2: 'b', 3: 'x', 4: 'y'} >> >> Every existing "key:value" pair has changed! What sort of mapping >> operates like that? > > It's like you said: "Animals with four legs can usually run, eat etc. But > birds can fly! What sort of animal flies?" > Well. birds. Er... okay. What's that got to do with what we are discussing? The point you might have missed is that treating lists as if they were mappings violates at least one critical property of mappings: that the relationship between keys and values are stable. Consider a simple address book, mapping between (let's say) a person's name and their address: address_book = { 'Fred': '123 Smiths Road', 'Ishmael': '37a Penny Lane', 'Jane': '2019 Short Street', 'Sam': '48 Main Road', } Now we add a new item: address_book['Annette'] = '97 The Boulevard' and then retrieve Jane's address. With a real mapping, like dict, then we know what will happen: print(address_book['Jane']) => prints '2019 Short Street' Adding or deleting entries in a mapping does not affect the remaining key:value pairs. It is absolutely critical and fundamental to mappings that the key:value pairs are stable. But suppose we had a mapping which lacked that stability: print(address_book['Jane']) # fundamentally broken mapping => prints '37a Penny Lane' # the address has mysteriously changed Do you think this would be reasonable behaviour for a mapping? I hope you would say "No". Now, let's imagine that we treat lists as if they were mappings, where the index is the key: address_book = [ '123 Smiths Road', # key = 0, Fred '37a Penny Lane', # key = 1, Ishmael '2019 Short Street', # key = 2, Jane '48 Main Road', # key = 3, Sam ] Now we add a new item: address_book.insert(0, '97 The Boulevard') # Annette and retrieve Jane's address, using Jane's "key": print(address_book[2]) => prints '37a Penny Lane' This is exactly the behaviour which (I hope) we have agreed would be broken for a dict or other mapping. We do not have stability of "key":value pairs. This violates the property that mapping key:value pairs should be stable. Inserting new entries into a mapping, or deleting them, shouldn't affect the remaining entries. But with a sequence, it can effect the relationship between index and item. That means that indexes are not keys, and sequences are not mappings. For a sequence, this does not matter. There is no promise that items will always be found at the same index you put them in. Many operations on sequences will move items around: sort reverse pop insert delete an item or slice some slice assignments shuffle and more. -- Steven From steve at pearwood.info Sat Mar 26 07:45:21 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Mar 2016 22:45:21 +1100 Subject: I need help References: Message-ID: <56f67653$0$1591$c3e8da3$5496439d@news.astraweb.com> On Sat, 26 Mar 2016 05:52 am, matthew thiel wrote: > So I downloaded python and made an account but when I run it all it does > is give me 3 options repair modify and uninstall I have clicked repair and > modify and let them run but at the end it just exit out so how do I get it > to work??? You made an account? An account where? What does this account have to do with Python? Where did you download Python from? Please give the actual URL. What operating system are you using? I can guess from the following that it is probably Windows 10: > Sent from Mail for Windows > 10 is that correct? 32-bit or 64-bit? -- Steven From ned at nedbatchelder.com Sat Mar 26 07:51:51 2016 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sat, 26 Mar 2016 04:51:51 -0700 (PDT) Subject: PLEASE HELP -- TOTALLY NEW TO PYTHON In-Reply-To: References: Message-ID: <770f81e2-02bc-4a9c-9bbf-a9abb257b4cb@googlegroups.com> On Saturday, March 26, 2016 at 5:59:30 AM UTC-4, Juan Dent wrote: > I am trying to run 'python cppdep.py' but get the following: > > @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ > analyzing dependencies among all components ... > Traceback (most recent call last): > File "cppdep.py", line 675, in > main() > File "cppdep.py", line 643, in main > calculate_graph(digraph) > File "cppdep.py", line 570, in calculate_graph > (cycles, dict_node2cycle) = make_DAG(digraph, key_node) > File "/Users/juandent/Downloads/cppdep-master/networkx_ext.py", line 79, in make_DAG > for ind in range(len(subgraphs)-1, -1, -1): > TypeError: object of type 'generator' has no len() > > > Please, I know no python and am in a hurry to get this working... Please help It looks like you are not the first to encounter this: https://github.com/yuzhichang/cppdep/issues/2 I don't see a quick fix to this in the code. If you fix this one spot, likely there will be other problem. It looks to me like you should install NetworkX 1.7 to get it to work. --Ned. From larry.martell at gmail.com Sat Mar 26 07:52:05 2016 From: larry.martell at gmail.com (Larry Martell) Date: Sat, 26 Mar 2016 07:52:05 -0400 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <5038313.yTPFmuZgmt@PointedEars.de> <09151817-fc79-4077-89a0-66e0c6551f9f@googlegroups.com> <1686453.n4820qZuCL@PointedEars.de> <3039159.EZm1bvJSo6@PointedEars.de> Message-ID: On Sat, Mar 26, 2016 at 7:37 AM, Ned Batchelder wrote: > Thomas, you don't have to choose between correct and nice. It's > possible to be both. "I'm not good, I'm not nice, I'm just right." That was written by Stephen Sondheim and it's from his musical Into The Woods. It's said by the witch. That used to be my sig back in usenet days, and more then one person said "Who said that? Rush Limbaugh?" > I can see that you are knowledgeable, and I really appreciate the energy > you put into answering questions. You are very generous with your time. > But when you bark correct things at people, they don't hear you. Your > helpful energy is being overshadowed by your blunt rude manner. As my wife once said, "If you start with 'Listen, asshole, ...' they probably won't hear what you have to say after that. From steve at pearwood.info Sat Mar 26 07:52:19 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Mar 2016 22:52:19 +1100 Subject: PLEASE HELP -- TOTALLY NEW TO PYTHON References: Message-ID: <56f677f5$0$1614$c3e8da3$5496439d@news.astraweb.com> On Sat, 26 Mar 2016 04:31 pm, Juan Dent wrote: > > I am trying to run ?python cppdep.py? but get the following: > > @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ > analyzing dependencies among all components ... > Traceback (most recent call last): > File "cppdep.py", line 675, in > main() > File "cppdep.py", line 643, in main > calculate_graph(digraph) > File "cppdep.py", line 570, in calculate_graph > (cycles, dict_node2cycle) = make_DAG(digraph, key_node) > File "/Users/juandent/Downloads/cppdep-master/networkx_ext.py", line 79, > in make_DAG > for ind in range(len(subgraphs)-1, -1, -1): > TypeError: object of type 'generator' has no len() > > > Please, I know no python and am in a hurry to get this working? Left your homework for the very last day, did you? I'm sorry that you are in a hurry, but that's not our problem. Look at the last two lines of the error traceback. The second last tells you the line that failed: for ind in range(len(subgraphs)-1, -1, -1): and the last line tells you the error: TypeError: object of type 'generator' has no len() The error tells you that "subgraphs" is a "generator", not a list. So you have two choices: - you can change "subgraphs" to be a list; - or you can change the for-loop to not need the length of subgraphs, or the index. The smaller change would probably be the first, changing subgraphs. But the better change would probably be to change the for-loop. -- Steven From steve at pearwood.info Sat Mar 26 08:00:09 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Mar 2016 23:00:09 +1100 Subject: How to make Python interpreter a little more strict? References: Message-ID: <56f679cb$0$1611$c3e8da3$5496439d@news.astraweb.com> On Fri, 25 Mar 2016 11:06 pm, Aleksander Alekseev wrote: > Is it possible to make python complain in this case? Or maybe solve > such an issue somehow else? This is a job for a "linter", such as pychecker, pylint or pyflakes. Google for more if you are interested. A linter will check your code for things which are *legal* code, but might not do what you expect, or are a sign of a potential error. For instance, dead code that will never be reached, or variables that are defined and then never used, or functions (such as next) which are named but not used. Another thing you can do is use an editor which colours functions like "next" differently from statements like "continue". -- Steven From rosuav at gmail.com Sat Mar 26 08:03:06 2016 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 26 Mar 2016 23:03:06 +1100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <56f666d8$0$1583$c3e8da3$5496439d@news.astraweb.com> References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <56f666d8$0$1583$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Mar 26, 2016 at 9:39 PM, Steven D'Aprano wrote: > It is an accident of history that Python's first and major implementation > happens to be written in C. (Although its use as a glue language, allowing > people to safely use libraries written in C, probably played a role in > ensuring Python's success.) Your parenthesis is more important than you may be giving it credit for, so IMO C is more than "an accident of history" in Python's success. There's a massive network effect surrounding programming languages, particularly glue languages. Suppose I were to develop a brand-new library of awesomeness, distributed as a Java .class file. Python (via Jython) could now use that, but many MANY other languages could not, ergo my library would languish. But if I design my library to have C bindings instead, Java programs can't use it, but any language that is able to connect to C code can. Conversely, if I'm developing a new language, I can look at the available C libraries and say "hey, look, access to C bindings gives me GUI toolkits, bignums, etc, etc, etc", so it's worth my while to connect to that. C may itself be immaterial, but the network surrounding it has been, and continues to be. Thanks to CPython, Python can be easily compiled for any CPU or OS that has the standard C build tools ported to it; that's a huge dependency, but it's a dependency of *so* many other programs that it's a high priority for OS developers. Python's success comes partly through leveraging that portability and power. The same could have been accomplished with any other language at the center of the network, but the same wasn't accomplished with any other language at the center of the network. It was done with C. Of course, that doesn't mean that C's *behaviour* has anything to do with Python's *behaviour*. That's a completely separate point. ChrisA From rosuav at gmail.com Sat Mar 26 08:05:38 2016 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 26 Mar 2016 23:05:38 +1100 Subject: How to make Python interpreter a little more strict? In-Reply-To: <20160325150608.21c3827a@fujitsu> References: <20160325150608.21c3827a@fujitsu> Message-ID: On Fri, Mar 25, 2016 at 11:06 PM, Aleksander Alekseev wrote: > Recently I spend half an hour looking for a bug in code like this: > > eax at fujitsu:~/temp$ cat ./t.py > #!/usr/bin/env python3 > > for x in range(0,5): > if x % 2 == 0: > next > print(str(x)) > > eax at fujitsu:~/temp$ ./t.py > 0 > 1 > 2 > 3 > 4 > > Is it possible to make python complain in this case? Or maybe solve > such an issue somehow else? I think what you're looking for here is an acknowledgement that evaluating the name "next" accomplishes nothing. That's not really something the Python interpreter should be looking at (hey, you might have good reason for doing that), but there are linters that can detect this kind of dead code. Some of them tie into programmer's editors, so you could get a nice little warning message right in the window where you're typing your code. Look into some of the top-end editors (free or commercial) and see what you think of them - they can save you no end of time. ChrisA From steve at pearwood.info Sat Mar 26 08:21:53 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Mar 2016 23:21:53 +1100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> Message-ID: <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> On Sat, 26 Mar 2016 01:59 pm, Paul Rubin wrote: > Steven D'Aprano writes: >> Culturally, C compiler writers have a preference for using undefined >> behaviour to allow optimizations, even if it means changing the semantics >> of your code. > > If your code has UB then by definition it has no semantics to change. > Code with UB has no meaning. Ah, a language lawyer, huh? :-P By the rules of the C standard, you're right, but those rules make use of a rather specialised definition of "no meaning" or "meaningless". I'm using the ordinary English sense. For example, would you consider that this isolated C code is "meaningless"? int i = n + 1; I'm not talking about type errors where n is not an int. We can assume that n is also an int. I bet that you know exactly what that line of code means. But according to the standard, it's "meaningless", since it might overflow, and signed int overflow is Undefined Behaviour. Even the C FAQ (as quoted by John Regehr) implies that code which is defined as "meaningless" may have meaning in the ordinary English sense: [quote] Anything at all can happen; the Standard imposes no requirements. The program may fail to compile, or it may execute incorrectly (either crashing or silently generating incorrect results), or it may fortuitously do EXACTLY WHAT THE PROGRAMMER INTENDED. [Emphasis added.] http://blog.regehr.org/archives/213 If the code is "meaningless", how can we say that it does what the programmer intended? In plain English, if the programmer had an intention for the code, and it was valid C syntax, it's not hard to conclude that the code has some meaning. Even if that meaning isn't quite what the programmer expected. Compilers are well known for only doing what you tell them to do, not what you want them to do. But in the case of C and C++ they don't even do what you tell them to do. When I talk about changing the semantics of the code you write, I'm using a plain English sense of "meaning". Start with a simple-minded, non- optimizing C compiler -- what Raymond Chen refers to as a "classical compiler". For example: int table[4]; bool exists_in_table(int v) { for (int i = 0; i <= 4; i++) { if (table[i] == v) return true; } return false; } There's an out-of-bounds error there, but as Chen puts it, a classical compiler would mindlessly generate code that reads past the end of the array. A bug, but a predictable one: you can reason about it, and the effect will be dependent on whatever arbitrary value happens to be in that memory location. A better compiler would generate an error and refuse to compile code for it. Either way, in plain English, the meaning is obvious: * Create an array of four ints, naming it "table". * Declare a function named "exists_in_table", which takes an int "v" as argument and returns a bool. * This function iterates over i = 0 to 4 inclusive, returning true if the i-th item of table equals the given v, and false if none of those items equals the given v. I don't believe for a second that you can't read that code well enough to infer the intended meaning of it. Even I can read C well enough to do that. Yet according to the C standard, that perfectly understandable code snippet is deemed to be gibberish, and instead of returning true or false, the compiler is permitted to erase your hard disk, or turn off your life- support, if it so chooses. And as Raymond Chen describes, a post-classical compiler will probably optimize that function to one which always returns true. As far as I know, there is no other language apart from C and C++ that takes such a cavalier approach. I cannot emphasis enough that the treatment of "undefined behaviour" is intentional by the C standards committee. Given the absolutely catastrophic effect it has had on the reliability, safety and security of code written in C, in my opinion the C standard borders on professional negligence. Programming in C becomes a battle to defeat the compiler and force it to do what you tell it to do, all because the C standard was written by a bunch of people whose number one priority was being able to make their benchmarks look good. Imagine a bridge builder who discovers a tiny, technical ambiguity or error in the blueprints for a bridge. On one page, the documentation states that there should be four rivets per metre in the supporting beams, but on another page, it is described as five rivets per metre. What should the builder do? - ask for clarification and get the blueprints and documentation corrected? - play it safe and use five rivets? - declare that therefore the entire blueprints are meaningless, and so he is free to optimize the bridge and reduce costs by using steel of a cheaper grade, half the thickness, and one rivet per metre? When the bridge collapses under the load of normal traffic, killing hundreds of people, what comfort should we take from the fact that the builder was able to optimize it so that it was half the weight, a quarter of the cost, and finished ahead of schedule, compared to a bridge that would have actually done the job it was designed for? -- Steven From rosuav at gmail.com Sat Mar 26 09:22:51 2016 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 27 Mar 2016 00:22:51 +1100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Mar 26, 2016 at 11:21 PM, Steven D'Aprano wrote: > In plain English, if the programmer had an intention for the code, and it > was valid C syntax, it's not hard to conclude that the code has some > meaning. Even if that meaning isn't quite what the programmer expected. > Compilers are well known for only doing what you tell them to do, not what > you want them to do. But in the case of C and C++ they don't even do what > you tell them to do. > Does this Python code have meaning? x = 5 while x < 10: print(x) ++x It's a fairly direct translation of perfectly valid C code, and it's syntactically valid. When the C spec talks about accidentally doing what you intended, that would be to have the last line here increment x. But that's never a requirement; compilers/interpreters are not mindreaders. The main reason the C int has undefined behaviour is that it's somewhere between "fixed size two's complement signed integer" and "integer with plenty of room". A C compiler is generally free to use a larger integer than you're expecting, which will cause numeric overflow to not happen. That's (part of[1]) why overflow of signed integers is undefined - it'd be too costly to emulate a smaller integer. So tell me... what happens in CPython if you incref an object more times than the native integer will permit? Are you bothered by this possibility, or do you simply assume that nobody will ever do that? Does C's definition of undefined behaviour mean that this code can be optimized away, thus achieving nothing? typedef struct _object { _PyObject_HEAD_EXTRA Py_ssize_t ob_refcnt; struct _typeobject *ob_type; } PyObject; #define Py_INCREF(op) ( \ _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ ((PyObject *)(op))->ob_refcnt++) The reftotal and debug comma are both empty in non-debug builds. The meat of this is simply a double-plus increment of a Py_ssize_t integer, which is defined in pyport.h as a signed integer. Of course this won't be optimized away, though. The only part that's undefined is "what exactly happens if you overflow an integer?". And you shouldn't be doing that at all; if you do, it's a bug, one way or another. The compiler cannot be expected to magically know what you intended to happen, so it's allowed to assume that this isn't what your code meant to do. If you care about capping refcounts, you need to do that yourself, somehow - don't depend on the compiler, because you can't even know exactly how wide that refcount is. ChrisA [1] The other part being that C didn't want to mandate two's complement, although I'm pretty sure that could be changed today without breaking any modern architectures. From cl at isbd.net Sat Mar 26 09:59:21 2016 From: cl at isbd.net (cl at isbd.net) Date: Sat, 26 Mar 2016 13:59:21 +0000 Subject: [OT'ish] Is there a list as good as this for Javascript References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <5038313.yTPFmuZgmt@PointedEars.de> Message-ID: Thomas 'PointedEars' Lahn wrote: > cl at isbd.net wrote: > > > Occasionally I have to make forays into Javascript, can anyone > > recommend a place similar to this list where Javascript questions can > > be asked? The trouble is that there are very many usenet Javascript > > lists and it's difficult to guess which one[es] might be good. > > There is no Javascript. > > There are no Usenet lists. > > This is not only a Python *mailing* list, it is also mirrored as an > international Usenet _newsgroup_, (which I am > reading). > Which is what (OP) do too. Life's too short to go into detail about how one is accessing a group/list in the context of a question like my original question. It's quite fun following all the resulting flak though! :-) > If you can accept all of that, then the international Usenet _newsgroup_ > (where I am posting primarily) is for you. > So are other national/language-specific newsgroups on the JavaScripts and > other ECMAScript implementations. In your newsreader, search for newsgroups > whose name contains ?javascript?. > > Next time, read and STFW first, and get a real name. > Ay? Thanks anyway, comp.lang.javascript it is, or I'll try it anyway. -- Chris Green ? From cl at isbd.net Sat Mar 26 10:01:28 2016 From: cl at isbd.net (cl at isbd.net) Date: Sat, 26 Mar 2016 14:01:28 +0000 Subject: [OT'ish] Is there a list as good as this for Javascript References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <5038313.yTPFmuZgmt@PointedEars.de> <09151817-fc79-4077-89a0-66e0c6551f9f@googlegroups.com> Message-ID: Ned Batchelder wrote: > On Friday, March 25, 2016 at 5:17:21 PM UTC-4, Thomas 'PointedEars' Lahn wrote: > > cl at isbd.net wrote: > > > > > Occasionally I have to make forays into Javascript, can anyone > > > recommend a place similar to this list where Javascript questions can > > > be asked? The trouble is that there are very many usenet Javascript > > > lists and it's difficult to guess which one[es] might be good. > > > > There is no Javascript. > > > > There are no Usenet lists. > > > > This is not only a Python *mailing* list, it is also mirrored as an > > international Usenet _newsgroup_, (which I am > > reading). > > > > If you can accept all of that, then the international Usenet _newsgroup_ > > (where I am posting primarily) is for you. > > So are other national/language-specific newsgroups on the JavaScripts and > > other ECMAScript implementations. In your newsreader, search for newsgroups > > whose name contains "javascript". > > > > Next time, read and STFW first, and get a real name. > > Chris, I apologize for Thomas. His main goal on this list seems to be > pointing out when people are wrong, over the smallest details. His > secondary goal is enforcing some imaginary rule about real names, though > he couldn't be bothered to read your post thoroughly enough to discover yours. > > Thomas is not typical of the Python community. We are mostly nice people. :) > Yes, I know, this is one of my favourite groups/lists. Just about every question I have ever asked here has received really helpful replies. Even this one has, though it does seem to have stirred a bit of a hornet's nest at the same time. :-) -- Chris Green ? From bc at freeuk.com Sat Mar 26 10:09:38 2016 From: bc at freeuk.com (BartC) Date: Sat, 26 Mar 2016 14:09:38 +0000 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 26/03/2016 13:22, Chris Angelico wrote: > On Sat, Mar 26, 2016 at 11:21 PM, Steven D'Aprano wrote: >> In plain English, if the programmer had an intention for the code, and it >> was valid C syntax, it's not hard to conclude that the code has some >> meaning. Even if that meaning isn't quite what the programmer expected. >> Compilers are well known for only doing what you tell them to do, not what >> you want them to do. But in the case of C and C++ they don't even do what >> you tell them to do. >> > > Does this Python code have meaning? > > x = 5 > while x < 10: > print(x) > ++x > > > It's a fairly direct translation of perfectly valid C code, and it's > syntactically valid. When the C spec talks about accidentally doing > what you intended, that would be to have the last line here increment > x. But that's never a requirement; compilers/interpreters are not > mindreaders. I'm surprised that both C and Python allow statements that apparently do nothing. In both, an example is: x on a line by itself. This expression is evaluated, but then any result discarded. If there was a genuine use for this (for example, reporting any error with the evaluation), then it would be simple enough to require a keyword in front. Not allowing these standalone expressions allows extra errors to be picked up including '++x' and 'next' in Python. (I think simply translating '++x' in Python to 'x+=1' has already been discussed in the past.) > The main reason the C int has undefined behaviour is that it's > somewhere between "fixed size two's complement signed integer" and > "integer with plenty of room". A C compiler is generally free to use a > larger integer than you're expecting, which will cause numeric > overflow to not happen. That's (part of[1]) why overflow of signed > integers is undefined - it'd be too costly to emulate a smaller > integer. So tell me... what happens in CPython if you incref an object > more times than the native integer will permit? Are you bothered by > this possibility, or do you simply assume that nobody will ever do > that? (On a ref-counted scheme I use, with 32-bit counts (I don't think it matters if they are signed or not), each reference implies a 16-byte object elsewhere. For the count to wrap around back to zero, that would mean 64GB of RAM being needed. On a 32-bit system, something else will go wrong first. Even on 64-bits, it's a possibility I suppose although you might notice memory problems sooner.) -- Bartc From rosuav at gmail.com Sat Mar 26 10:30:31 2016 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 27 Mar 2016 01:30:31 +1100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Mar 27, 2016 at 1:09 AM, BartC wrote: > I'm surprised that both C and Python allow statements that apparently do > nothing. In both, an example is: > > x > > on a line by itself. This expression is evaluated, but then any result > discarded. If there was a genuine use for this (for example, reporting any > error with the evaluation), then it would be simple enough to require a > keyword in front. Tell me, which of these is a statement that "does nothing"? foo foo.bar foo["bar"] foo.__call__ foo() int(foo) All of them are expressions to be evaluated and the result discarded. I'm sure you'll recognize "foo()" as useful code, but to the interpreter, they're all the same. And any one of them could raise an exception rather than emit a value; for instance, consider these code blocks: # Personally, I prefer doing it the other way, but # if you have a big Py2 codebase, this will help # port it to Py3. try: raw_input except NameError: raw_input = input try: int(sys.argv[1]) except IndexError: print("No argument given") except ValueError: print("Not an integer") In each case, the "dummy evaluation" of an expression is used as a way of asking "Will this throw?". That's why this has to be squarely in the hands of linters, not the main interpreter; there's nothing that can't in some way be useful. >> The main reason the C int has undefined behaviour is that it's >> somewhere between "fixed size two's complement signed integer" and >> "integer with plenty of room". A C compiler is generally free to use a >> larger integer than you're expecting, which will cause numeric >> overflow to not happen. That's (part of[1]) why overflow of signed >> integers is undefined - it'd be too costly to emulate a smaller >> integer. So tell me... what happens in CPython if you incref an object >> more times than the native integer will permit? Are you bothered by >> this possibility, or do you simply assume that nobody will ever do >> that? > > > (On a ref-counted scheme I use, with 32-bit counts (I don't think it matters > if they are signed or not), each reference implies a 16-byte object > elsewhere. For the count to wrap around back to zero, that would mean 64GB > of RAM being needed. On a 32-bit system, something else will go wrong first. > > Even on 64-bits, it's a possibility I suppose although you might notice > memory problems sooner.) C code can claim references to Python objects without having actual pointers anywhere. A naive object traversal algorithm could claim temporary references on all the objects it moves past (to ensure they don't get garbage collected in the middle), and then get stuck in an infinite loop traversing a reference loop, thus infinitely increasing reference counts. Yeah, it can happen... I've had bugs like that in my code... Point is, CPython can generally assume that bug-free code will never get anywhere *near* the limit of a signed integer. Consequently, C's undefined behaviour isn't a problem; it does NOT mean we need to be scared of signed integers. ChrisA From breamoreboy at yahoo.co.uk Sat Mar 26 10:38:13 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 26 Mar 2016 14:38:13 +0000 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: <3n0esc-r3p.ln1@esprimo.zbmc.eu> References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> Message-ID: On 24/03/2016 20:53, cl at isbd.net wrote: > I use Python wherever I can and find this list (as a usenet group via > gmane) an invaluable help at times. > > Occasionally I have to make forays into Javascript, can anyone > recommend a place similar to this list where Javascript questions can > be asked? The trouble is that there are very many usenet Javascript > lists and it's difficult to guess which one[es] might be good. > Perhaps this http://transcrypt.org/ is the way to go? :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From bc at freeuk.com Sat Mar 26 11:24:48 2016 From: bc at freeuk.com (BartC) Date: Sat, 26 Mar 2016 15:24:48 +0000 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 26/03/2016 14:30, Chris Angelico wrote: > On Sun, Mar 27, 2016 at 1:09 AM, BartC wrote: >> I'm surprised that both C and Python allow statements that apparently do >> nothing. In both, an example is: >> >> x >> >> on a line by itself. This expression is evaluated, but then any result >> discarded. If there was a genuine use for this (for example, reporting any >> error with the evaluation), then it would be simple enough to require a >> keyword in front. > > Tell me, which of these is a statement that "does nothing"? > > foo > foo.bar > foo["bar"] > foo.__call__ > foo() > int(foo) > > All of them are expressions to be evaluated and the result discarded. > I'm sure you'll recognize "foo()" as useful code, but to the > interpreter, they're all the same. Out of that lot, only foo() is something that is commonly written both as an expression and standalone statement. > And any one of them could raise an > exception rather than emit a value; for instance, consider these code > blocks: > > # Personally, I prefer doing it the other way, but > # if you have a big Py2 codebase, this will help > # port it to Py3. > try: raw_input > except NameError: raw_input = input > > try: int(sys.argv[1]) > except IndexError: > print("No argument given") > except ValueError: > print("Not an integer") > > In each case, the "dummy evaluation" of an expression is used as a way > of asking "Will this throw?". That's why this has to be squarely in > the hands of linters, not the main interpreter; there's nothing that > can't in some way be useful. But notice that to render such an evaluation 'useful', you've put 'try:' in front, which is also a cue to the reader. Now you can't just do that anyway (try expects an except block to follow). But my suggestion was to have required a keyword in front of such expressions. Then no linter is needed. And stops some head-scratching from people who have to read the code. -- Bartc From gheskett at wdtv.com Sat Mar 26 11:31:34 2016 From: gheskett at wdtv.com (Gene Heskett) Date: Sat, 26 Mar 2016 11:31:34 -0400 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> Message-ID: <201603261131.34365.gheskett@wdtv.com> On Saturday 26 March 2016 07:52:05 Larry Martell wrote: > On Sat, Mar 26, 2016 at 7:37 AM, Ned Batchelder wrote: > > Thomas, you don't have to choose between correct and nice. It's > > possible to be both. > > "I'm not good, I'm not nice, I'm just right." > > That was written by Stephen Sondheim and it's from his musical Into > The Woods. It's said by the witch. That used to be my sig back in > usenet days, and more then one person said "Who said that? Rush > Limbaugh?" > > > I can see that you are knowledgeable, and I really appreciate the > > energy you put into answering questions. You are very generous with > > your time. But when you bark correct things at people, they don't > > hear you. Your helpful energy is being overshadowed by your blunt > > rude manner. > > As my wife once said, "If you start with 'Listen, asshole, ...' they > probably won't hear what you have to say after that. She is 100% correct, but try as I might, I can't quite believe that your missus would ever use that plain a language. She is too good at dressing it up. She reminds me of our now passed Senator Bobbie Byrd, who could tell somebody to go to hell in such flowery language that they looked forward to the trip. 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) Genes Web page From larry.martell at gmail.com Sat Mar 26 11:35:52 2016 From: larry.martell at gmail.com (Larry Martell) Date: Sat, 26 Mar 2016 11:35:52 -0400 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: <201603261131.34365.gheskett@wdtv.com> References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <201603261131.34365.gheskett@wdtv.com> Message-ID: On Sat, Mar 26, 2016 at 11:31 AM, Gene Heskett wrote: > On Saturday 26 March 2016 07:52:05 Larry Martell wrote: >> As my wife once said, "If you start with 'Listen, asshole, ...' they >> probably won't hear what you have to say after that. > > She is 100% correct, but try as I might, I can't quite believe that your > missus would ever use that plain a language. She is too good at > dressing it up. She reminds me of our now passed Senator Bobbie Byrd, > who could tell somebody to go to hell in such flowery language that they > looked forward to the trip. Gene, she can curse like a sailor when needed. From gheskett at wdtv.com Sat Mar 26 12:06:09 2016 From: gheskett at wdtv.com (Gene Heskett) Date: Sat, 26 Mar 2016 12:06:09 -0400 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <201603261131.34365.gheskett@wdtv.com> Message-ID: <201603261206.09743.gheskett@wdtv.com> On Saturday 26 March 2016 11:35:52 Larry Martell wrote: > On Sat, Mar 26, 2016 at 11:31 AM, Gene Heskett wrote: > > On Saturday 26 March 2016 07:52:05 Larry Martell wrote: > >> As my wife once said, "If you start with 'Listen, asshole, ...' > >> they probably won't hear what you have to say after that. > > > > She is 100% correct, but try as I might, I can't quite believe that > > your missus would ever use that plain a language. She is too good > > at dressing it up. She reminds me of our now passed Senator Bobbie > > Byrd, who could tell somebody to go to hell in such flowery language > > that they looked forward to the trip. > > Gene, she can curse like a sailor when needed. The key is "when needed". Been known to do that myself. I did, 60 years ago have a 10 minute monologue of swearing practiced up, no 4 letter word used twice. But common sense has prevailed and I've forgotten 9 minutes of it by now. No longer 10' tall & bulletproof I guess. :) The years do that to a body, so now my std excuse is that if I had of known I was going to live this long, I would have taken better care of myself. But I would have had to start practicing that the summer of 1960 when, for lack of a better job, I spent several months in an iron foundry. Woman and at that point, 2 kids to feed. But I learned a lot about hot ($2400F) iron too. 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) Genes Web page From beliavsky at aol.com Sat Mar 26 12:49:35 2016 From: beliavsky at aol.com (beliavsky at aol.com) Date: Sat, 26 Mar 2016 09:49:35 -0700 (PDT) Subject: Exclude every nth element from list? Message-ID: <94237154-22af-4e64-85ee-9b4cf334fa6f@googlegroups.com> I can use x[::n] to select every nth element of a list. Is there a one-liner to get a list that excludes every nth element? From gherron at digipen.edu Sat Mar 26 12:50:48 2016 From: gherron at digipen.edu (Gary Herron) Date: Sat, 26 Mar 2016 09:50:48 -0700 Subject: PLEASE HELP -- TOTALLY NEW TO PYTHON In-Reply-To: <30049892-D089-451B-A839-03D825448588@mac.com> References: <30049892-D089-451B-A839-03D825448588@mac.com> Message-ID: <56F6BDE8.3040206@digipen.edu> On 03/25/2016 10:31 PM, Juan Dent wrote: > I am trying to run ?python cppdep.py? but get the following: I would guess that this code was written some time ago for Python2, but that you have downloaded and run it with Python3. Try installing Python2 instead of Python3. Or try talking whoever wrote it into converting it to Python3. Or my guess is completely wrong and the code is buggy and won't run until fixed. (Which brings up the questions: What is cppdep.py? Who wrote it? How do you know that it runs?) Gary Herron > > @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ > analyzing dependencies among all components ... > Traceback (most recent call last): > File "cppdep.py", line 675, in > main() > File "cppdep.py", line 643, in main > calculate_graph(digraph) > File "cppdep.py", line 570, in calculate_graph > (cycles, dict_node2cycle) = make_DAG(digraph, key_node) > File "/Users/juandent/Downloads/cppdep-master/networkx_ext.py", line 79, in make_DAG > for ind in range(len(subgraphs)-1, -1, -1): > TypeError: object of type 'generator' has no len() > > > Please, I know no python and am in a hurry to get this working? Please help > > > Regards, > Juan -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From gherron at digipen.edu Sat Mar 26 13:01:48 2016 From: gherron at digipen.edu (Gary Herron) Date: Sat, 26 Mar 2016 10:01:48 -0700 Subject: Exclude every nth element from list? In-Reply-To: <94237154-22af-4e64-85ee-9b4cf334fa6f@googlegroups.com> References: <94237154-22af-4e64-85ee-9b4cf334fa6f@googlegroups.com> Message-ID: <56F6C07C.8020405@digipen.edu> On 03/26/2016 09:49 AM, beliavsky--- via Python-list wrote: > I can use x[::n] to select every nth element of a list. Is there a one-liner to get a list that excludes every nth element? Yes: >>> L=list(range(20)) >>> [x for i,x in enumerate(L) if i%3 != 0] [1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19] Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From bgailer at gmail.com Sat Mar 26 13:03:17 2016 From: bgailer at gmail.com (Bob Gailer) Date: Sat, 26 Mar 2016 13:03:17 -0400 Subject: Exclude every nth element from list? In-Reply-To: <94237154-22af-4e64-85ee-9b4cf334fa6f@googlegroups.com> References: <94237154-22af-4e64-85ee-9b4cf334fa6f@googlegroups.com> Message-ID: On Mar 26, 2016 12:50 PM, "beliavsky--- via Python-list" < python-list at python.org> wrote: > > I can use x[::n] to select every nth element of a list. Is there a one-liner to get a list that excludes every nth element? [y for (i,y) in enumerate(x) if i % n] From python at lucidity.plus.com Sat Mar 26 13:06:01 2016 From: python at lucidity.plus.com (Erik) Date: Sat, 26 Mar 2016 17:06:01 +0000 Subject: Exclude every nth element from list? In-Reply-To: <94237154-22af-4e64-85ee-9b4cf334fa6f@googlegroups.com> References: <94237154-22af-4e64-85ee-9b4cf334fa6f@googlegroups.com> Message-ID: <56F6C179.5040100@lucidity.plus.com> On 26/03/16 16:49, beliavsky--- via Python-list wrote: > I can use x[::n] to select every nth element of a list. Is there a one-liner to get a list that excludes every nth element? (e for i, e in enumerate(x) if i % n) K. From vincent.vande.vyvre at telenet.be Sat Mar 26 13:06:10 2016 From: vincent.vande.vyvre at telenet.be (Vincent Vande Vyvre) Date: Sat, 26 Mar 2016 18:06:10 +0100 Subject: Exclude every nth element from list? In-Reply-To: <94237154-22af-4e64-85ee-9b4cf334fa6f@googlegroups.com> References: <94237154-22af-4e64-85ee-9b4cf334fa6f@googlegroups.com> Message-ID: <56F6C182.1000106@telenet.be> Le 26/03/2016 17:49, beliavsky--- via Python-list a ?crit : > I can use x[::n] to select every nth element of a list. Is there a one-liner to get a list that excludes every nth element? Something like that: >>> l = list("lkodjuyhrtgfedcvfg") >>> l ['l', 'k', 'o', 'd', 'j', 'u', 'y', 'h', 'r', 't', 'g', 'f', 'e', 'd', 'c', 'v', 'f', 'g'] >>> ll = [c for i, c in enumerate(l) if i % 3] >>> ll.insert(0, l[0]) >>> ll ['l', 'k', 'o', 'j', 'u', 'h', 'r', 'g', 'f', 'd', 'c', 'f', 'g'] Vincent From __peter__ at web.de Sat Mar 26 13:06:40 2016 From: __peter__ at web.de (Peter Otten) Date: Sat, 26 Mar 2016 18:06:40 +0100 Subject: Exclude every nth element from list? References: <94237154-22af-4e64-85ee-9b4cf334fa6f@googlegroups.com> Message-ID: beliavsky--- via Python-list wrote: > I can use x[::n] to select every nth element of a list. Is there a > one-liner to get a list that excludes every nth element? del x[::n] ;) From best_lay at yahoo.com Sat Mar 26 13:10:30 2016 From: best_lay at yahoo.com (Wildman) Date: Sat, 26 Mar 2016 12:10:30 -0500 Subject: Another Key Binding Question Message-ID: I use some key bindings in my program. They are declared like this: root.bind("" + "q", quit) root.bind("" + "q", quit) root.bind("" + "Q", quit) root.bind("" + "Q", quit) The above binds both Alt keys with upper and lower case 'q'. Is there a way to combine the statements above into one statement? -- GNU/Linux user #557453 May the Source be with you. From vincent.vande.vyvre at telenet.be Sat Mar 26 13:12:35 2016 From: vincent.vande.vyvre at telenet.be (Vincent Vande Vyvre) Date: Sat, 26 Mar 2016 18:12:35 +0100 Subject: Exclude every nth element from list? In-Reply-To: <56F6C182.1000106@telenet.be> References: <94237154-22af-4e64-85ee-9b4cf334fa6f@googlegroups.com> <56F6C182.1000106@telenet.be> Message-ID: <56F6C303.2050702@telenet.be> Le 26/03/2016 18:06, Vincent Vande Vyvre a ?crit : > Le 26/03/2016 17:49, beliavsky--- via Python-list a ?crit : >> I can use x[::n] to select every nth element of a list. Is there a >> one-liner to get a list that excludes every nth element? > Something like that: > > >>> l = list("lkodjuyhrtgfedcvfg") > >>> l > ['l', 'k', 'o', 'd', 'j', 'u', 'y', 'h', 'r', 't', 'g', 'f', 'e', 'd', > 'c', 'v', 'f', 'g'] > >>> ll = [c for i, c in enumerate(l) if i % 3] > >>> ll.insert(0, l[0]) > >>> ll > ['l', 'k', 'o', 'j', 'u', 'h', 'r', 'g', 'f', 'd', 'c', 'f', 'g'] > > > > Vincent Correction, it's more correct with the insert before the list comprehension >>> l.insert(0, "_") >>> ll = [c for i, c in enumerate(l) if i % 3] >>> ll ['l', 'k', 'd', 'j', 'y', 'h', 't', 'g', 'e', 'd', 'v', 'f'] From joel.goldstick at gmail.com Sat Mar 26 13:26:52 2016 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 26 Mar 2016 13:26:52 -0400 Subject: PLEASE HELP -- TOTALLY NEW TO PYTHON In-Reply-To: <30049892-D089-451B-A839-03D825448588@mac.com> References: <30049892-D089-451B-A839-03D825448588@mac.com> Message-ID: On Sat, Mar 26, 2016 at 1:31 AM, Juan Dent wrote: > > I am trying to run ?python cppdep.py? but get the following: > > > @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ > analyzing dependencies among all components ... > Traceback (most recent call last): > File "cppdep.py", line 675, in > main() > File "cppdep.py", line 643, in main > calculate_graph(digraph) > File "cppdep.py", line 570, in calculate_graph > (cycles, dict_node2cycle) = make_DAG(digraph, key_node) > File "/Users/juandent/Downloads/cppdep-master/networkx_ext.py", line 79, > in make_DAG > for ind in range(len(subgraphs)-1, -1, -1): > TypeError: object of type 'generator' has no len() > > > Please, I know no python and am in a hurry to get this working? Please help > > > Regards, > Juan > -- > https://mail.python.org/mailman/listinfo/python-list > As a painless quick try I would change this line: for ind in range(len(subgraphs)-1, -1, -1): to this: for ind in range(len(list(subgraphs))-1, -1, -1): If that works, when you have time track down what is really going on. -- Joel Goldstick http://joelgoldstick.com/ http://cc-baseballstats.info/ From rustompmody at gmail.com Sat Mar 26 13:43:39 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 26 Mar 2016 10:43:39 -0700 (PDT) Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <56f666d8$0$1583$c3e8da3$5496439d@news.astraweb.com> References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <56f666d8$0$1583$c3e8da3$5496439d@news.astraweb.com> Message-ID: <2e1ce88d-fae2-4aa0-ace9-4faa4878459b@googlegroups.com> On Saturday, March 26, 2016 at 4:09:41 PM UTC+5:30, Steven D'Aprano wrote: > On Sat, 26 Mar 2016 04:30 pm, Rustom Mody wrote: > > > For one thing its good to remember that we wouldn't be here without python > > Python wouldn't be what it is without CPython > > There is nothing about Python that relies on the C standard being as it is. Um lets see... There is this nice piece of OO called the exception hierarchy: https://docs.python.org/2/library/exceptions.html#exception-hierarchy So we have BaseException ? Exception ? EnvironmentError ? IOError At this point it would have been completely natural for IOError to continue subclassing to all the typical errors - File not found - No Space left on device etc etc But instead we have an integer errno and we must inquire what that is to figure out what the exact IOError was Are you suggesting that python's errno module: https://docs.python.org/2/library/errno.html And C's http://man7.org/linux/man-pages/man3/errno.3.html are coincidentally related? > There are Python implementations that are not written in C or C++: > > Jython (Java) > IronPython (C# for .Net or Mono) > CLPython (Lisp) > Berp (Haskell) As best as I know - Java is written in C - Lisp is written in C - Haskell is written in C Notice a certain pattern? Yeah some of them may be self-hosting eg haskell (ghc) is written in ghc Where did the first bootstrap start from? And if you think those levels of distance render the C origin irrelevant, here is a famous Turing award lecture: https://www.ece.cmu.edu/~ganger/712.fall02/papers/p761-thompson.pdf by (surprise-surprise!) the creator of C-Unix ... shows how to make a Trojan and ends with The moral is obvious. You can't trust code that you did not totally create yourself. (Especially code from companies that employ people like me.) No amount of source-level verification or scrutiny will protect you from using untrusted code. So... Ahem... C is unsafe... Right... Prefer C++ ?? From python at mrabarnett.plus.com Sat Mar 26 13:47:02 2016 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 26 Mar 2016 17:47:02 +0000 Subject: Another Key Binding Question In-Reply-To: References: Message-ID: <56F6CB16.1010606@mrabarnett.plus.com> On 2016-03-26 17:10, Wildman via Python-list wrote: > I use some key bindings in my program. They are declared > like this: > > root.bind("" + "q", quit) > root.bind("" + "q", quit) > root.bind("" + "Q", quit) > root.bind("" + "Q", quit) > > The above binds both Alt keys with upper and lower case 'q'. > Is there a way to combine the statements above into one > statement? > Try this: root.bind("", quit) root.bind("", quit) The first is for either "Alt" key plus the "Q" key and Caps Lock turned off. The second is for either "Alt" key plus the "Q" key and Caps Lock turned on. From torriem at gmail.com Sat Mar 26 13:49:45 2016 From: torriem at gmail.com (Michael Torrie) Date: Sat, 26 Mar 2016 11:49:45 -0600 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <5038313.yTPFmuZgmt@PointedEars.de> <09151817-fc79-4077-89a0-66e0c6551f9f@googlegroups.com> <1686453.n4820qZuCL@PointedEars.de> <3039159.EZm1bvJSo6@PointedEars.de> Message-ID: <56F6CBB9.9030800@gmail.com> On 03/26/2016 05:37 AM, Ned Batchelder wrote: > [...] > Has anyone ever said to you, "Thanks, Thomas! Lots of people were giving > me answers, but they were all so kind and polite about it, I couldn't > see what they were saying. Finally, your blunt direct manner got > through to me, so now I understand." Of course not. It's absurd. > Bluntness doesn't help learning. It just makes *you* feel good. > > Points of correctness are useless without points of connection. You > have to talk to people in a way that they will hear. If you can't be > bothered, then you are just wasting your time, and earning a negative > reputation for yourself. > [...] Well said, Ned, and a good reminder for me, and I suspect all of us, to considering how we communicate. It's our nature to think problems lie with everyone else but us (as witnessed by recent posts from another list member in this own thread), and it's good to be reminded to look inward as well. From bc at freeuk.com Sat Mar 26 13:50:03 2016 From: bc at freeuk.com (BartC) Date: Sat, 26 Mar 2016 17:50:03 +0000 Subject: Exclude every nth element from list? In-Reply-To: <94237154-22af-4e64-85ee-9b4cf334fa6f@googlegroups.com> References: <94237154-22af-4e64-85ee-9b4cf334fa6f@googlegroups.com> Message-ID: On 26/03/2016 16:49, beliavsky at aol.com wrote: > I can use x[::n] to select every nth element of a list. I would use x[n-1::n] if 'nth' means the 3rd element of [10,20,30,40,...] is 30. Otherwise every selection will include the first, no matter what n is. -- Bartc From PointedEars at web.de Sat Mar 26 13:58:36 2016 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Sat, 26 Mar 2016 18:58:36 +0100 Subject: [OT'ish] Is there a list as good as this for Javascript References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> Message-ID: <2351733.ZyMq8HvUEo@PointedEars.de> Mark Lawrence wrote: > On 24/03/2016 20:53, cl at isbd.net wrote: >> I use Python wherever I can and find this list (as a usenet group via >> gmane) an invaluable help at times. >> >> Occasionally I have to make forays into Javascript, can anyone >> recommend a place similar to this list where Javascript questions can >> be asked? The trouble is that there are very many usenet Javascript >> lists and it's difficult to guess which one[es] might be good. > > Perhaps this http://transcrypt.org/ is the way to go? :) Unfortunately, no. It needs attention from an expert in the targeted field. To begin with, the ?JavaScript? version (actually, only an ECMAScript *2015*-compliant version) of the original Python code considers a "class" as sealed (properties being only accessor properties with a getter), when in Python that is not the case: class C: def foo (self): pass o = C() C.foo = lambda self, bar: print(bar) # prints "baz" o.foo("baz") Further, to set up multiple inheritance in a conforming implementation of ECMAScript, one must not only set up the instance properties as by the constructor of a type, but also the *prototype* chain. In fact, a Proxy instance would be required to really set up the *emulation* of such a branching prototype chain for any ECMAScript object. This list of implementation mistakes is not exhaustive, but ECMAScript implementations are beyond the scope of this newsgroup/mailing list. -- PointedEars Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail. From torriem at gmail.com Sat Mar 26 14:01:10 2016 From: torriem at gmail.com (Michael Torrie) Date: Sat, 26 Mar 2016 12:01:10 -0600 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: <56F6CBB9.9030800@gmail.com> References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <5038313.yTPFmuZgmt@PointedEars.de> <09151817-fc79-4077-89a0-66e0c6551f9f@googlegroups.com> <1686453.n4820qZuCL@PointedEars.de> <3039159.EZm1bvJSo6@PointedEars.de> <56F6CBB9.9030800@gmail.com> Message-ID: <56F6CE66.4030907@gmail.com> On 03/26/2016 11:49 AM, Michael Torrie wrote: > Well said, Ned, and a good reminder for me, and I suspect all of us, to > considering how we communicate. It's our nature to think problems lie ^^^^^^^^^^^^^^ Sigh. Consider. And proof read. > with everyone else but us (as witnessed by recent posts from another > list member in this own thread), and it's good to be reminded to look > inward as well. From jmartens2 at ameritech.net Sat Mar 26 16:38:35 2016 From: jmartens2 at ameritech.net (Jerry Martens) Date: Sat, 26 Mar 2016 20:38:35 +0000 (UTC) Subject: help with program References: <1392737302.749065.1459024715818.JavaMail.yahoo.ref@mail.yahoo.com> Message-ID: <1392737302.749065.1459024715818.JavaMail.yahoo@mail.yahoo.com> hi im trying to run this program and it opens a screen really ast and closes it faster withou any results. im totally a noob. everything i google is confusing. do i need to place this is in a folder or just run from command line? i have the latest version of python. im running win 7. any help would be appreciated! or could you please point me to a good forum for total noobs?thank you for your time and effort! From tjreedy at udel.edu Sat Mar 26 16:44:41 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Mar 2016 16:44:41 -0400 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <2e1ce88d-fae2-4aa0-ace9-4faa4878459b@googlegroups.com> References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <56f666d8$0$1583$c3e8da3$5496439d@news.astraweb.com> <2e1ce88d-fae2-4aa0-ace9-4faa4878459b@googlegroups.com> Message-ID: On 3/26/2016 1:43 PM, Rustom Mody wrote: > There is this nice piece of OO called the exception hierarchy: > https://docs.python.org/2/library/exceptions.html#exception-hierarchy https://docs.python.org/3/library/exceptions.html#exception-hierarchy > BaseException ? Exception ? EnvironmentError ? IOError BaseException ? Exception ? ? OSError > At this point it would have been completely natural for IOError to continue > subclassing to all the typical errors > - File not found > - No Space left on device Which is why we now have +-- OSError | +-- BlockingIOError | +-- ChildProcessError | +-- ConnectionError | | +-- BrokenPipeError | | +-- ConnectionAbortedError | | +-- ConnectionRefusedError | | +-- ConnectionResetError | +-- FileExistsError | +-- FileNotFoundError | +-- InterruptedError | +-- IsADirectoryError | +-- NotADirectoryError | +-- PermissionError | +-- ProcessLookupError | +-- TimeoutError 'no space' is MemoryError, but that is a hardward, not OS matter. > But instead we have an integer errno and we must inquire what that is to > figure out what the exact IOError was This statement is obsolete, but explains why the above was added in 3.3. -- Terry Jan Reedy From rosuav at gmail.com Sat Mar 26 17:58:42 2016 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 27 Mar 2016 08:58:42 +1100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <2e1ce88d-fae2-4aa0-ace9-4faa4878459b@googlegroups.com> References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <56f666d8$0$1583$c3e8da3$5496439d@news.astraweb.com> <2e1ce88d-fae2-4aa0-ace9-4faa4878459b@googlegroups.com> Message-ID: On Sun, Mar 27, 2016 at 4:43 AM, Rustom Mody wrote: > On Saturday, March 26, 2016 at 4:09:41 PM UTC+5:30, Steven D'Aprano wrote: >> On Sat, 26 Mar 2016 04:30 pm, Rustom Mody wrote: >> >> > For one thing its good to remember that we wouldn't be here without python >> > Python wouldn't be what it is without CPython >> >> There is nothing about Python that relies on the C standard being as it is. > > Um lets see... > There is this nice piece of OO called the exception hierarchy: > https://docs.python.org/2/library/exceptions.html#exception-hierarchy > > So we have > BaseException ? Exception ? EnvironmentError ? IOError > At this point it would have been completely natural for IOError to continue > subclassing to all the typical errors > - File not found > - No Space left on device > etc etc > > But instead we have an integer errno and we must inquire what that is to > figure out what the exact IOError was > Are you suggesting that python's errno module: > https://docs.python.org/2/library/errno.html > And C's http://man7.org/linux/man-pages/man3/errno.3.html > are coincidentally related? You're reading documentation that's aimed at C programmers for the same reason as above - aiming at C makes it accessible to the most people. But errno is not inherently bound to C; if I were to build a language interpreter in Fortran, I could make errno available to it. What you're looking at isn't so much a C thing as a Linux thing; Python makes available the Linux error code as a means of disambiguating similar errors. ChrisA From cs at zip.com.au Sat Mar 26 18:01:15 2016 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 27 Mar 2016 09:01:15 +1100 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: <1686453.n4820qZuCL@PointedEars.de> References: <1686453.n4820qZuCL@PointedEars.de> Message-ID: <20160326220115.GA77218@cskk.homeip.net> On 26Mar2016 02:36, Thomas 'PointedEars' Lahn wrote: >Ned Batchelder wrote: >> Chris, I apologize for Thomas. > >How dare you to speak for me, Because it is something you never say: sorry for my rudeness. >and *again* the rest of the subscribers? He speaks for me at least, on this topic. I was tempted to say this yesterday after Ned, but didn't because his words were well chosen. But now: Chris, I too apologise for Thomas' tone. With one or two exceptions, I have found this to be one of the most civil and welcoming fora on the net and hope you get good help and discussion here. >There is nothing to apologize for when I am *helping* someone by giving them >useful information. Items of useful information shielded behind concealing walls of apparent anger and contempt. That is not a helpful delivery style, and it actively drives away new people. May I recommend the film "Harvey"? As the lead character says at one point: "I used to be smart. I recommend nice." I used to be something of a hothead myself; I hope that I have matured. [...] >Politeness is another thing you should try sometime, as I see that, your >having no valid argument at all, you like to throw dirt instead. [...] Your previous tone makes this admonition ineffective. Based on my samples, Ned is far beyond you in politeness. My personal practice is usually to leave post that offend or disparage or otherwise have an agressive tone alone, or to snip the rant-like sections and address _only_ the technical content to try to keep the discussion on topic and civil. But not always, as evidenced here. Thomas: your tone and delivery _is_ unhelpful to others, and comes across as hostile, at least to my eyes and evidently to others. Cheers, Cameron Simpson From beliavsky at aol.com Sat Mar 26 18:08:24 2016 From: beliavsky at aol.com (beliavsky at aol.com) Date: Sat, 26 Mar 2016 15:08:24 -0700 (PDT) Subject: Exclude every nth element from list? In-Reply-To: References: <94237154-22af-4e64-85ee-9b4cf334fa6f@googlegroups.com> Message-ID: On Saturday, March 26, 2016 at 1:02:06 PM UTC-4, Gary Herron wrote: > On 03/26/2016 09:49 AM, beliavsky--- via Python-list wrote: > > I can use x[::n] to select every nth element of a list. Is there a one-liner to get a list that excludes every nth element? > > Yes: > > >>> L=list(range(20)) > >>> [x for i,x in enumerate(L) if i%3 != 0] > [1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19] > > > Gary Herron > > > -- > Dr. Gary Herron > Department of Computer Science > DigiPen Institute of Technology > (425) 895-4418 Thanks to you and others who replied. I see that enumerate is a useful function. From beliavsky at aol.com Sat Mar 26 18:12:37 2016 From: beliavsky at aol.com (beliavsky at aol.com) Date: Sat, 26 Mar 2016 15:12:37 -0700 (PDT) Subject: repeat items in a list Message-ID: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> I can create a list that has repeated elements of another list as follows: xx = ["a","b"] nrep = 3 print xx yy = [] for aa in xx: for i in range(nrep): yy.append(aa) print yy output: ['a', 'b'] ['a', 'a', 'a', 'b', 'b', 'b'] Is there a one-liner to create a list with repeated elements? From rosuav at gmail.com Sat Mar 26 18:48:47 2016 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 27 Mar 2016 09:48:47 +1100 Subject: help with program In-Reply-To: <1392737302.749065.1459024715818.JavaMail.yahoo@mail.yahoo.com> References: <1392737302.749065.1459024715818.JavaMail.yahoo.ref@mail.yahoo.com> <1392737302.749065.1459024715818.JavaMail.yahoo@mail.yahoo.com> Message-ID: On Sun, Mar 27, 2016 at 7:38 AM, Jerry Martens wrote: > hi im trying to run this program and it opens a screen really ast and closes it faster withou any results. im totally a noob. everything i google is confusing. do i need to place this is in a folder or just run from command line? i have the latest version of python. im running win 7. any help would be appreciated! or could you please point me to a good forum for total noobs?thank you for your time and effort! > Hi! There are a few ways you could do this. One is to run it from the command line. Another is to put this line at the end of the program: input("Press enter to exit. ") That should bring up the same screen (called a "console") and then have it wait until you're done reading it. A third way is to edit your code using Idle, and run it from there. I haven't done that in a while, though, so the details might have changed in the recent versions. All the best! ChrisA From ghorab_1995 at hotmail.com Sat Mar 26 18:52:21 2016 From: ghorab_1995 at hotmail.com (Youssef Ghorab) Date: Sun, 27 Mar 2016 00:52:21 +0200 Subject: setup Message-ID: dear python,i'm having a problem when i'm setting up the program 0x80070570 problem if you please could give me any advice will be cool. thanks in advance From breamoreboy at yahoo.co.uk Sat Mar 26 18:57:39 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 26 Mar 2016 22:57:39 +0000 Subject: Exclude every nth element from list? In-Reply-To: References: <94237154-22af-4e64-85ee-9b4cf334fa6f@googlegroups.com> Message-ID: On 26/03/2016 22:08, beliavsky--- via Python-list wrote: > On Saturday, March 26, 2016 at 1:02:06 PM UTC-4, Gary Herron wrote: >> On 03/26/2016 09:49 AM, beliavsky--- via Python-list wrote: >>> I can use x[::n] to select every nth element of a list. Is there a one-liner to get a list that excludes every nth element? >> >> Yes: >> >> >>> L=list(range(20)) >> >>> [x for i,x in enumerate(L) if i%3 != 0] >> [1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19] >> >> >> Gary Herron >> > > Thanks to you and others who replied. I see that enumerate is a useful function. > It is, but you may like to note that you don't have to count from zero. The 'start' keyword can be set to anything you like. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at yahoo.co.uk Sat Mar 26 19:03:27 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 26 Mar 2016 23:03:27 +0000 Subject: help with program In-Reply-To: <1392737302.749065.1459024715818.JavaMail.yahoo@mail.yahoo.com> References: <1392737302.749065.1459024715818.JavaMail.yahoo.ref@mail.yahoo.com> <1392737302.749065.1459024715818.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 26/03/2016 20:38, Jerry Martens wrote: > any help would be appreciated! or could you please point me to a good forum for total noobs?thank you for your time and effort! > https://mail.python.org/mailman/listinfo/tutor also available at gmane.comp.python.tutor. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From cs at zip.com.au Sat Mar 26 19:05:47 2016 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 27 Mar 2016 10:05:47 +1100 Subject: repeat items in a list In-Reply-To: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> Message-ID: <20160326230547.GA37070@cskk.homeip.net> On 26Mar2016 15:12, beliavsky at aol.com wrote: >I can create a list that has repeated elements of another list as follows: > >xx = ["a","b"] >nrep = 3 >print xx >yy = [] >for aa in xx: > for i in range(nrep): > yy.append(aa) >print yy > >output: >['a', 'b'] >['a', 'a', 'a', 'b', 'b', 'b'] > >Is there a one-liner to create a list with repeated elements? Sure. As with all one liners, there comes a degree of complexity when it gets in the way of readability; you must decide what is better in your use case. Look up the chain() function from the itertools module. Generate 2 (or nrep) length lists from each element of the original list and chain() them together. That gets you an iterable of all the elements. If you really need a list out the end instead of the iterable of the elements, convert the iterable to a list (hint: lists can be initialised with iterables). Cheers, Cameron Simpson From joel.goldstick at gmail.com Sat Mar 26 19:20:08 2016 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 26 Mar 2016 19:20:08 -0400 Subject: setup In-Reply-To: References: Message-ID: On Sat, Mar 26, 2016 at 6:52 PM, Youssef Ghorab wrote: > dear python,i'm having a problem when i'm setting up the program > 0x80070570 problem > if you please could give me any advice will be cool. > thanks in advance > -- > https://mail.python.org/mailman/listinfo/python-list > I'm guessing you are on windows and you could google the error code, but also search the list because this question has been asked and answered I believe -- Joel Goldstick http://joelgoldstick.com/ http://cc-baseballstats.info/ From python at lucidity.plus.com Sat Mar 26 19:23:53 2016 From: python at lucidity.plus.com (Erik) Date: Sat, 26 Mar 2016 23:23:53 +0000 Subject: repeat items in a list In-Reply-To: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> Message-ID: <56F71A09.7020300@lucidity.plus.com> Hi, On 26/03/16 22:12, beliavsky--- via Python-list wrote: > I can create a list that has repeated elements of another list as follows: > > xx = ["a","b"] > nrep = 3 > print xx > yy = [] > for aa in xx: > for i in range(nrep): > yy.append(aa) > print yy > > output: > ['a', 'b'] > ['a', 'a', 'a', 'b', 'b', 'b'] > > Is there a one-liner to create a list with repeated elements? yy = reduce(lambda a, b: a + b, ([i] * nrep for i in xx), []) Or, if you want to "import operator" first, you can use 'operator.add' instead of the lambda (but you _did_ ask for a one-liner ;)). Out of interest, why the fascination with one-liners? E. From breamoreboy at yahoo.co.uk Sat Mar 26 19:28:59 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 26 Mar 2016 23:28:59 +0000 Subject: repeat items in a list In-Reply-To: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> Message-ID: On 26/03/2016 22:12, beliavsky--- via Python-list wrote: > I can create a list that has repeated elements of another list as follows: > > xx = ["a","b"] > nrep = 3 > print xx > yy = [] > for aa in xx: > for i in range(nrep): > yy.append(aa) > print yy > > output: > ['a', 'b'] > ['a', 'a', 'a', 'b', 'b', 'b'] > > Is there a one-liner to create a list with repeated elements? > yy = [aa for aa in xx for _ in range(nrep)] I suggest that you try this sort of the thing at an interactive prompt, it's a great way to learn. You might also want to take a look at the itertools module https://docs.python.org/3/library/itertools.html. This is often used in building structures like the ones you've been asking about today. To me it is the Swiss Army Knife of the stdlib. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From johnhpote at o2.co.uk Sat Mar 26 19:30:30 2016 From: johnhpote at o2.co.uk (John Pote) Date: Sat, 26 Mar 2016 23:30:30 +0000 Subject: How to make Python interpreter a little more strict? In-Reply-To: References: <20160325150608.21c3827a@fujitsu> Message-ID: <56F71B96.7000408@o2.co.uk> On 26/03/2016 12:05, Chris Angelico wrote: > On Fri, Mar 25, 2016 at 11:06 PM, Aleksander Alekseev wrote: >> Recently I spend half an hour looking for a bug in code like this: >> >> eax at fujitsu:~/temp$ cat ./t.py >> #!/usr/bin/env python3 >> >> for x in range(0,5): >> if x % 2 == 0: >> next >> print(str(x)) >> >> eax at fujitsu:~/temp$ ./t.py >> 0 >> 1 >> 2 >> 3 >> 4 >> >> Is it possible to make python complain in this case? Or maybe solve >> such an issue somehow else? > I think what you're looking for here is an acknowledgement that > evaluating the name "next" accomplishes nothing. That's not really > something the Python interpreter should be looking at (hey, you might > have good reason for doing that), but there are linters that can > detect this kind of dead code. Some of them tie into programmer's > editors, so you could get a nice little warning message right in the > window where you're typing your code. Look into some of the top-end > editors (free or commercial) and see what you think of them - they can > save you no end of time. > > ChrisA So intrigued by this question I tried the following def fnc( n ): print "fnc called with parameter '%d'" % n return n for i in range(0,5): if i%2 == 0: fnc next print i and got the same result as the OP D:\projects\python >>python next.py 0 1 2 3 4 D:\projects\python >> A couple of tests showed that the only important thing about the name in the if clause is that it is known at runtime and then it is silently ignored. However, if the name is not known/accessible at run time a 'NameError' is raised, NameError: name 'mynewfn123' is not defined On the other hand the following if clause if i%2 == 0: fnc next results in a compiler error, D:\projects\python >>python next.py File "next.py", line 9 fnc next ^ SyntaxError: invalid syntax This is all for Python 2.7.9. (Don't know about Python 3....). So I have sympathy with the OP, I would expect the compiler to pick this up - indeed it does so for two (or more ?) unused names on a single line. That is unless someone can give a useful use of this behaviour or is there something going on under the Python hood I'm not aware of? It would be all to easy to write a series of lines just calling functions and forget the () on one of them. Not fun programming. It's also a good reminder that the meaning of a keyword in language A is not necessarily the same in language B (ie 'next', Python) So on this last point is this behaviour of Python defined somewhere in the docs? Regards all, John From beliavsky at aol.com Sat Mar 26 19:36:46 2016 From: beliavsky at aol.com (beliavsky at aol.com) Date: Sat, 26 Mar 2016 16:36:46 -0700 (PDT) Subject: repeat items in a list In-Reply-To: References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> Message-ID: On Saturday, March 26, 2016 at 7:24:10 PM UTC-4, Erik wrote: > Hi, > > On 26/03/16 22:12, beliavsky--- via Python-list wrote: > > I can create a list that has repeated elements of another list as follows: > > > > xx = ["a","b"] > > nrep = 3 > > print xx > > yy = [] > > for aa in xx: > > for i in range(nrep): > > yy.append(aa) > > print yy > > > > output: > > ['a', 'b'] > > ['a', 'a', 'a', 'b', 'b', 'b'] > > > > Is there a one-liner to create a list with repeated elements? > > yy = reduce(lambda a, b: a + b, ([i] * nrep for i in xx), []) > > Or, if you want to "import operator" first, you can use 'operator.add' > instead of the lambda (but you _did_ ask for a one-liner ;)). > > Out of interest, why the fascination with one-liners? Thanks for your reply. Sometimes when I program in Python I think I am not using the full capabilities of the language, so I want to know if there are more concise ways of doing things. From beliavsky at aol.com Sat Mar 26 19:54:36 2016 From: beliavsky at aol.com (beliavsky at aol.com) Date: Sat, 26 Mar 2016 16:54:36 -0700 (PDT) Subject: repeat items in a list In-Reply-To: References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> Message-ID: <6f1ab11b-da4a-49d5-8dcd-bd9b0c6fe8b3@googlegroups.com> On Saturday, March 26, 2016 at 7:30:14 PM UTC-4, Mark Lawrence wrote: > On 26/03/2016 22:12, beliavsky--- via Python-list wrote: > > I can create a list that has repeated elements of another list as follows: > > > > xx = ["a","b"] > > nrep = 3 > > print xx > > yy = [] > > for aa in xx: > > for i in range(nrep): > > yy.append(aa) > > print yy > > > > output: > > ['a', 'b'] > > ['a', 'a', 'a', 'b', 'b', 'b'] > > > > Is there a one-liner to create a list with repeated elements? > > > > yy = [aa for aa in xx for _ in range(nrep)] > > I suggest that you try this sort of the thing at an interactive prompt, > it's a great way to learn. > > You might also want to take a look at the itertools module > https://docs.python.org/3/library/itertools.html. This is often used in > building structures like the ones you've been asking about today. To me > it is the Swiss Army Knife of the stdlib. Thanks for the one-liner, which I prefer to the one I made up using itertools: yy = list(chain.from_iterable([list(repeat(aa,nrep)) for aa in xx])) From bc at freeuk.com Sat Mar 26 20:36:12 2016 From: bc at freeuk.com (BartC) Date: Sun, 27 Mar 2016 00:36:12 +0000 Subject: How to make Python interpreter a little more strict? In-Reply-To: References: <20160325150608.21c3827a@fujitsu> Message-ID: On 26/03/2016 23:30, John Pote wrote: > So intrigued by this question I tried the following > def fnc( n ): > print "fnc called with parameter '%d'" % n > return n > > for i in range(0,5): > if i%2 == 0: > fnc > next > print i > > and got the same result as the OP > A couple of tests showed that the only important thing about the name in > the if clause is that it is known at runtime and then it is silently > ignored. > However, if the name is not known/accessible at run time a 'NameError' > is raised, > NameError: name 'mynewfn123' is not defined > > On the other hand the following if clause > if i%2 == 0: > fnc next The results aren't surprising once you know what's going on. If you have: fnc then this name is evaluated (it refers to a function object given your definition. Then that value is discarded. But this: kljgkjhgjk is not defined anywhere, and it can't evaluate it, raising the name error. While in: fnc() the 'fnc' is evaluated, and then it's called (when it should give a parameter error as your def expects one). But abc def is just a syntax error as usually two identifiers can't be adjacent (AFAIK) except where the first is a reserved word. > So I have sympathy with the OP, I would expect the compiler to pick this > up - indeed it does so for two (or more ?) unused names on a single > line. That is unless someone can give a useful use of this behaviour or > is there something going on under the Python hood I'm not aware of? This one of those features I think that do have the odd use but most of the time just result in perplexing results or hard-to-find bugs. It could have been eliminated from the language (especially as many people aren't even aware of the possibilities) with little loss. Someone who desperately wants to evaluate a name or expression can always use something like: def test(x):pass test(fnc) for the same purpose. But this time it's obvious. (Ideally it would be a built-in construct to avoid the call overhead.) -- Bartc From gvimrc at gmail.com Sat Mar 26 21:46:08 2016 From: gvimrc at gmail.com (gvim) Date: Sun, 27 Mar 2016 02:46:08 +0100 Subject: Why lambda in loop requires default? Message-ID: <56F73B60.9020603@gmail.com> Given that Python, like Ruby, is an object-oriented language why doesn't this: def m(): a = [] for i in range(3): a.append(lambda: i) return a b = m() for n in range(3): print(b[n]()) # => 2 2 2 ... work the same as this in Ruby: def m a = [] (0..2).each {|i| a << ->(){i}} a end aa = m (0..2).each {|n| puts aa[n].()} # => 0 1 2 lambda i=i: i ... is needed to make it work in Python. Just wondered why? gvim From steve at pearwood.info Sat Mar 26 22:44:08 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 27 Mar 2016 13:44:08 +1100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <56f666d8$0$1583$c3e8da3$5496439d@news.astraweb.com> <2e1ce88d-fae2-4aa0-ace9-4faa4878459b@googlegroups.com> Message-ID: <56f748fa$0$1612$c3e8da3$5496439d@news.astraweb.com> On Sun, 27 Mar 2016 04:43 am, Rustom Mody wrote: > On Saturday, March 26, 2016 at 4:09:41 PM UTC+5:30, Steven D'Aprano wrote: >> On Sat, 26 Mar 2016 04:30 pm, Rustom Mody wrote: >> >> > For one thing its good to remember that we wouldn't be here without >> > python Python wouldn't be what it is without CPython >> >> There is nothing about Python that relies on the C standard being as it >> is. > > Um lets see... > There is this nice piece of OO called the exception hierarchy: > https://docs.python.org/2/library/exceptions.html#exception-hierarchy > > So we have > BaseException ? Exception ? EnvironmentError ? IOError > At this point it would have been completely natural for IOError to > continue subclassing to all the typical errors > - File not found > - No Space left on device > etc etc You cannot possibly be serious. Are you *really* trying to argue that it is because of the C standard that the Python exception hierarchy isn't sufficiently nuanced for your taste? The air conditioner in my car struggles on hot days. The compressor of the air condition was designed by an engineer using software running on a computer running Windows. Windows is written in C or C++. Therefore the C standard is responsible for my car being hot. In any case, you might like to consider the Python 3 exception hierarchy before trying to defend your proposition: https://docs.python.org/3/library/exceptions.html#exception-hierarchy > But instead we have an integer errno and we must inquire what that is to > figure out what the exact IOError was > Are you suggesting that python's errno module: > https://docs.python.org/2/library/errno.html > And C's http://man7.org/linux/man-pages/man3/errno.3.html > are coincidentally related? Of course it's not a coincidence. The documentation explicitly states that the names and values of the constants are taken from the C header file errno.h. So what? If I somehow convince Guido to add a list of standard Go error codes into the standard library, does that mean that the Python language is dependent on Go? >> There are Python implementations that are not written in C or C++: >> >> Jython (Java) >> IronPython (C# for .Net or Mono) >> CLPython (Lisp) >> Berp (Haskell) > > As best as I know > - Java is written in C > - Lisp is written in C > - Haskell is written in C To my knowledge, all four of Java, C#, Lisp and Haskell are self-hosted languages. Even if a particular (say) Haskell compiler happens to have been written in C, it could have been written using Rust, D, Ada, Forth, PL/I, Modula 2, Java, Pascal, assembly language, etc. without changing anything about Haskell. You could replace "C" with any systems language such as "Fortran", and the Python language would be absolutely identical. You could even write the C ABI using Fortran. (CPython can call Fortran libraries even though it is written in C -- why couldn't a Fortran implementation call C libraries? There's no reason it couldn't -- Nim, for example, has a foreign function interface capable of calling C code even though the compiler was written in Pascal.) I'm not saying that the amount of effort required would be the same. I'm not saying that there are no influences in the design and practice of the Python interpreter due to C -- obviously that would be silly, Guido is a C programmer, of course he has been influenced by C. But many of those influences are "Don't do what C does!". Clearly C is important in the real world, and for practical and historical reasons Python was written in C. But those reasons aren't fundamental to the Python language, in the way that compatibility with C is fundamental to C++. If Donald Trump takes over the world and bans C, insisting that it be replaced with a new language of his own design called "T", the *implementation* of CPython would have to change, but the *interface*, the language itself, won't have to change one iota. > Notice a certain pattern? > Yeah some of them may be self-hosting > eg haskell (ghc) is written in ghc > Where did the first bootstrap start from? Where did the first C compiler start from? C is not some magical language that exists at the very heart of all programming. Programming existed before it, and even today there are corners of the computing world which don't rely on C, not even indirectly. The development of C started in 1969, and it is generally agreed to have first been more-or-less complete in 1972. The famous K&R C book didn't come out until 1978, and C wasn't standarized until 1989. There were many years of high-level computing before C was even a concept in Dennis Richie's mind. The first Fortran compiler wasn't written in C. Due to the ubiquity of C in 2016, it may be *convenient* to write your first compiler for a language in C, but it is not *necessary*. The first Nim compiler was written in Pascal, and if Nim isn't self-hosting, that doesn't mean it couldn't be. [...] > So... Ahem... C is unsafe... Right... Prefer C++ ?? No, of course not. C++ is exactly as unsafe as C, because it includes the same concept of Undefined Behaviour (which, I stress, is not the same as implementation-specific behaviour, or undocumented behaviour), and C++ is (mostly) backwards compatible with C. If I were to get involved with modern systems programming, I would start with D, or perhaps Rust. -- Steven From steve at pearwood.info Sat Mar 26 22:48:08 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 27 Mar 2016 13:48:08 +1100 Subject: help with program References: <1392737302.749065.1459024715818.JavaMail.yahoo.ref@mail.yahoo.com> Message-ID: <56f749e9$0$1612$c3e8da3$5496439d@news.astraweb.com> On Sun, 27 Mar 2016 07:38 am, Jerry Martens wrote: > hi im trying to run this program and it opens a screen really ast and > closes it faster withou any results. Put this at the very end of your program: # Python 2 version raw_input('Press the Enter key to exit... ') # Python 3 version input('Press the Enter key to exit... ') That will halt and wait for you to press the exit key before closing the window. -- Steven From rosuav at gmail.com Sat Mar 26 22:52:53 2016 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 27 Mar 2016 13:52:53 +1100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <56f748fa$0$1612$c3e8da3$5496439d@news.astraweb.com> References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <56f666d8$0$1583$c3e8da3$5496439d@news.astraweb.com> <2e1ce88d-fae2-4aa0-ace9-4faa4878459b@googlegroups.com> <56f748fa$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Mar 27, 2016 at 1:44 PM, Steven D'Aprano wrote: > If [anyone] takes over the world and bans C, insisting that it be > replaced with a new language of his own design called "T", the > *implementation* of CPython would have to change, but the *interface*, the > language itself, won't have to change one iota. Nah. We'd just be rebels and rename "gcc" to "t" and keep right on going :) ChrisA From steve at pearwood.info Sat Mar 26 23:01:19 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 27 Mar 2016 14:01:19 +1100 Subject: Threading is foobared? Message-ID: <56f74d00$0$1620$c3e8da3$5496439d@news.astraweb.com> Am I the only one who has noticed that threading of posts here is severely broken? It's always been the case that there have been a few posts here and there that break threading, but now it seems to be much more common. For instance, I see Jerry Martens' post "help with program". According to my newsreader, KNode, there are no replies to that thread. But I see a reply from Chris A. Chris' reply has a header line: In-Reply-To: <1392737302.749065.1459024715818.JavaMail.yahoo at mail.yahoo.com> but Jerry's original has: References: <1392737302.749065.1459024715818.JavaMail.yahoo.ref at mail.yahoo.com> Notice the difference? Here the two values lined up: <1392737302.749065.1459024715818.JavaMail.yahoo.ref at mail.yahoo.com> <1392737302.749065.1459024715818.JavaMail.yahoo at mail.yahoo.com> -- Steven From ben+python at benfinney.id.au Sat Mar 26 23:18:52 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 27 Mar 2016 14:18:52 +1100 Subject: Threading is foobared? References: <56f74d00$0$1620$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8560w8d2w3.fsf@benfinney.id.au> Steven D'Aprano writes: > Am I the only one who has noticed that threading of posts here is > severely broken? It's always been the case that there have been a few > posts here and there that break threading, but now it seems to be much > more common. I can't give an objective assessment of whether it has increased or to what extent. Thanks for pointing out an objective symptom, though: munging of the message ID values in various fields. The resulting broken threads are a constant source of annoyance. I don't know whether any one host is the culprit, or whether there are many hosts that are munging the message IDs. What you've demonstrated is that at least one host is violating communication standards by altering existing reference fields on messages in transit. -- \ ?It is difficult to get a man to understand something when his | `\ salary depends upon his not understanding it.? ?Upton Sinclair, | _o__) 1935 | Ben Finney From nimbiotics at gmail.com Sat Mar 26 23:22:27 2016 From: nimbiotics at gmail.com (Mario R. Osorio) Date: Sat, 26 Mar 2016 20:22:27 -0700 (PDT) Subject: Interpretation In-Reply-To: References: Message-ID: On Saturday, March 26, 2016 at 5:59:04 AM UTC-4, Dennis Ngeno wrote: > My programs have never combile, they keep telling me , systax error even > after copy pasting No pun intended, but I hope you are not typing your code like you typed your message. OTOH, python code is not supposed to be compiled. Another tip: If you really are copying and pasting, I'd recommend you first paste the code to the text editor of your like and MAKE SURE YOU ARE NOT MIXING SPACES AND TAB CHARACTERS FOR INDENTATION PURPOSES. Use either, or but do not mix them, specially not on the same line. IMHO, it is best to always use spaces, but some people do prefer tabs. From steve at pearwood.info Sat Mar 26 23:28:41 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 27 Mar 2016 14:28:41 +1100 Subject: How to make Python interpreter a little more strict? References: <20160325150608.21c3827a@fujitsu> Message-ID: <56f7536b$0$22140$c3e8da3$5496439d@news.astraweb.com> On Sun, 27 Mar 2016 10:30 am, John Pote wrote: > So intrigued by this question I tried the following > def fnc( n ): > print "fnc called with parameter '%d'" % n > return n > > for i in range(0,5): > if i%2 == 0: > fnc > next > print i > > and got the same result as the OP In this case, the two lines "fnc" and "next" simply look up the function names, but without actually calling them. They're not quite "no-ops", since they can fail and raise NameError if the name doesn't exist, but otherwise they might as well be no-ops. > A couple of tests showed that the only important thing about the name in > the if clause is that it is known at runtime and then it is silently > ignored. Right. What actually happens is that Python evaluates the expression, generates the result, and then if that result isn't used, a microsecond later the garbage collector deletes it. In this case, the expression consists of only a single name: "fnc", or "next". If you have a more complex expression, Python can do significant work before throwing it away: [x**3 for x in range(10000)] generates a list of cubed numbers [0, 1, 8, 27, ...]. Then the garbage collector sees that nothing refers to that list, and it is available to be deleted, so it deletes it. Why does Python bother generating the list only to throw it away a microsecond later? Because the interpreter can't easily tell if the calculations will have any side-effects. It might turn out that something in the expression ends up setting a global variable, or printing output, or writing to a file, or who knows what? Now, you and I can read the line and see that (assuming range hasn't been overridden) there are no side-effects from calculating cubes of numbers. But the Python interpreter is very simple-minded and not as smart as you or I, so it can't tell, and so it plays it safe and does the calculations just in case. Future versions of the interpreter may be smarter. In cases where Python *can* tell that there are no side-effects, it may ignore stand-alone expressions that don't do anything useful. > However, if the name is not known/accessible at run time a 'NameError' > is raised, > NameError: name 'mynewfn123' is not defined Correct. > On the other hand the following if clause > if i%2 == 0: > fnc next > > results in a compiler error, > D:\projects\python > >>python next.py > File "next.py", line 9 > fnc next > ^ > SyntaxError: invalid syntax > > This is all for Python 2.7.9. (Don't know about Python 3....). Python 3 will be more-or-less the same. Python 3 might be a bit smarter about recognising expressions that have no side-effects and that can be ignored, but not much more. > So I have sympathy with the OP, I would expect the compiler to pick this > up - indeed it does so for two (or more ?) unused names on a single > line. That is unless someone can give a useful use of this behaviour or > is there something going on under the Python hood I'm not aware of? In Python, variables AND FUNCTIONS are created dynamically, and can be deleted or created as needed. So Python doesn't know if your function "fnc" actually exists or not until runtime. Just because you defined it using def doesn't mean that it will still be around later: maybe you have called: del fnc or possibly reassigned the variable: fnc = "Surprise! Not a function any more!" So the compiler can't tell whether fnc is a legal line or not. Maybe fnc exists, maybe it doesn't, it will have to actually evaluate the expression to find out, and that happens at runtime. But the compiler can recognise syntax errors: fnc next is illegal syntax, as are: 1234fnc fnc? x = ) ( and for those, you will get an immediate SyntaxError before the code starts running. > It would be all to easy to write a series of lines just calling > functions and forget the () on one of them. Not fun programming. In theory, you are correct. But in practice, it's not really as big a problem as you might think. Very, very few functions take no arguments. There is this one: import random r = random.random # oops, forgot to call the function for example, but most functions take at least one argument: r = random.randint(1, 6) There are a few functions or methods that you call for their side-effects, like Pascal "procedures" or C "void functions": mylist.sort() and yes, it is annoying when you forget the brackets (round brackets or parentheses for any Americans reading) and the list doesn't sort, but that's the exception rather than the rule. And if you're worried about that, you can run a "linter" which check your source code for such potential problems. Google for PyLint, PyFlakes, PyChecker, Jedi, etc if you want more information about linters, or just ask here. I can't tell you too much about them, as I don't use them, but somebody will probably answer. -- Steven From ben+python at benfinney.id.au Sat Mar 26 23:35:40 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 27 Mar 2016 14:35:40 +1100 Subject: Interpretation References: Message-ID: <851t6wd243.fsf@benfinney.id.au> "Mario R. Osorio" writes: > On Saturday, March 26, 2016 at 5:59:04 AM UTC-4, Dennis Ngeno wrote: > > My programs have never combile, they keep telling me , systax error even > > after copy pasting > > No pun intended, but I hope you are not typing your code like you > typed your message. Many people don't have English as a first language, or are otherwise impaired from typing English text. The issue is important though, Dennis: communication is at the core of programming. You'll need to take care with what you write in your code, and in your messages; both are communications and clear writing is very helpful. > OTOH, python code is not supposed to be compiled. That's simply untrue: Python code is compiled every day on countless machines. It is compiled to various formats, but the process is none the less compilation. Don't make the mistake of a narrow definition of ?compile? which is unhelpful in modern languages like Python. > Another tip: If you really are copying and pasting, I'd recommend you > first paste the code to the text editor of your like and MAKE SURE YOU > ARE NOT MIXING SPACES AND TAB CHARACTERS FOR INDENTATION PURPOSES. Dennis, you should choose a text editor that handles program code well. A ?word processor? program makes different trade-offs, altering text in a way that is not helpful for writing program code. For an overview of the range of programmer's text editors, see . To start with you can use the ?IDLE? development environment that comes installed with Python. -- \ ?Puritanism: The haunting fear that someone, somewhere, may be | `\ happy.? ?Henry L. Mencken | _o__) | Ben Finney From steve at pearwood.info Sat Mar 26 23:45:28 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 27 Mar 2016 14:45:28 +1100 Subject: Interpretation References: Message-ID: <56f75759$0$1615$c3e8da3$5496439d@news.astraweb.com> On Sun, 27 Mar 2016 02:22 pm, Mario R. Osorio wrote: > OTOH, python code is not supposed to be compiled. Technically, Python code is compiled, to byte-code rather than machine-code, but still compiled. That's what is inside the .pyc files you will often see after importing modules. And Python even has a built-in function called "compile" that takes source code and compiles it a code object: py> x = compile("value = 23", "", "single") py> type(x) py> print(x) at 0xb7993300, file "", line 1> py> eval(x) py> print(value) 23 -- Steven From steve at pearwood.info Sat Mar 26 23:49:24 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 27 Mar 2016 14:49:24 +1100 Subject: Interpretation References: Message-ID: <56f75845$0$1615$c3e8da3$5496439d@news.astraweb.com> On Sat, 26 Mar 2016 03:33 am, Dennis Ngeno wrote: > My programs have never combile, they keep telling me , systax error even > after copy pasting Dennis, if Python is complaining that you have a SyntaxError, it means you have written something which the interpreter cannot understand. We cannot possibly tell what you have done wrong if you don't show us what you wrote, and what the error message says. SyntaxError can mean many different errors, for example: - you have misspelled a keyword (e.g. "dfe" instead of "def", "clas" instead of "class", "ipmort" instead of "import"); - you tried to use a keyword as a variable (e.g. "class = 23"); - you have not indented a code block correctly, e.g. inconsistent indentation in a single code block: def function(): print(1) # four spaces indent print(2) # eight spaces! this is inconsistent print(3) # now two spaces! or forgetting to indent a code block: def function(): print(1) # no indentation at all If you mix spaces and tabs, Python can sometimes get confused about the indentation, so you should always use *only* spaces or *only* tabs, never both in the same block. - you have too many, or too few, brackets and parentheses, or they are in the wrong place, e.g.: def function(): result = math.sin(1.245 # oops, forgot the closing parenthesis return result + 1 Errors with brackets and parentheses can be the most annoying ones, because sometimes Python cannot tell that there is an error until the line *after* where the error is. So in this case, it will say that there's a SyntaxError in the last line, "return result + 1", when the real error is in the previous line. SyntaxError tells you that your code is written wrongly and Python doesn't understand what you mean. You have to look at the code and fix the syntax problem. If you show us the line of code that Python is complaining about, and maybe the line before it, we can help. -- Steven From greg.ewing at canterbury.ac.nz Sun Mar 27 00:05:30 2016 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 27 Mar 2016 17:05:30 +1300 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <201603261131.34365.gheskett@wdtv.com> Message-ID: Gene Heskett wrote: > But I learned a lot about hot ($2400F) iron too. 2400 dollars farenheit? That's an intriguing unit... Or is it meant to be the temperature in hex? -- Greg From eryksun at gmail.com Sun Mar 27 00:07:23 2016 From: eryksun at gmail.com (eryk sun) Date: Sat, 26 Mar 2016 23:07:23 -0500 Subject: setup In-Reply-To: References: Message-ID: On Sat, Mar 26, 2016 at 6:20 PM, Joel Goldstick wrote: > I'm guessing you are on windows and you could google the error code, but > also search the list because this question has been asked and answered I > believe A little knowledge helps. An upper word of 0x8007 indicates a COM HRESULT error (0x8000) that originated as a Windows error (facility 7). Se we know that the lower word value of 0x0570 is a common Windows error code that can be found in the following list: https://msdn.microsoft.com/en-us/library/ms681381 You'll find that it's ERROR_FILE_CORRUPT, i.e. the file or directory is corrupted and unreadable. The most likely cause is a bad download. I wonder whether the OP used the web installer, which downloads components as required. If there's something dubious about the way it downloads from python.org, that would explain the relative frequency of this error for 3.5 installs. From rosuav at gmail.com Sun Mar 27 00:16:26 2016 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 27 Mar 2016 15:16:26 +1100 Subject: [OT'ish] Is there a list as good as this for Javascript In-Reply-To: References: <3n0esc-r3p.ln1@esprimo.zbmc.eu> <201603261131.34365.gheskett@wdtv.com> Message-ID: On Sun, Mar 27, 2016 at 3:05 PM, Gregory Ewing wrote: > Gene Heskett wrote: >> >> But I learned a lot about hot ($2400F) iron too. > > > 2400 dollars farenheit? That's an intriguing unit... > > Or is it meant to be the temperature in hex? Hex, obviously. Which is something like five thousand Kelvin, in decimal. Yeah that's hot. ChrisA From rustompmody at gmail.com Sun Mar 27 01:02:18 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 26 Mar 2016 22:02:18 -0700 (PDT) Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <56f666d8$0$1583$c3e8da3$5496439d@news.astraweb.com> <2e1ce88d-fae2-4aa0-ace9-4faa4878459b@googlegroups.com> Message-ID: <777df6e3-3e5c-4c59-913e-c9447d20173e@googlegroups.com> On Sunday, March 27, 2016 at 2:15:22 AM UTC+5:30, Terry Reedy wrote: > On 3/26/2016 1:43 PM, Rustom Mody wrote: > > > There is this nice piece of OO called the exception hierarchy: > > > https://docs.python.org/2/library/exceptions.html#exception-hierarchy > > https://docs.python.org/3/library/exceptions.html#exception-hierarchy > > > BaseException ? Exception ? EnvironmentError ? IOError > > BaseException ? Exception ? ? OSError > > > At this point it would have been completely natural for IOError to continue > > subclassing to all the typical errors > > - File not found > > - No Space left on device > > Which is why we now have > > +-- OSError > | +-- BlockingIOError > | +-- ChildProcessError > | +-- ConnectionError > | | +-- BrokenPipeError > | | +-- ConnectionAbortedError > | | +-- ConnectionRefusedError > | | +-- ConnectionResetError > | +-- FileExistsError > | +-- FileNotFoundError > | +-- InterruptedError > | +-- IsADirectoryError > | +-- NotADirectoryError > | +-- PermissionError > | +-- ProcessLookupError > | +-- TimeoutError > > 'no space' is MemoryError, but that is a hardward, not OS matter. > > > But instead we have an integer errno and we must inquire what that is to > > figure out what the exact IOError was > > This statement is obsolete, but explains why the above was added in 3.3. Thanks Terry for the correction I had an impression of seeing some discussion on this and resolved not to incorporate. Glad to be wrong on that However my general point is hardly about errno but about the lineage/legacy of python. And this is only strengthened by your correction Thanks to American politics being in the air I learnt a new word the other day: 'birther'. My point is python is 'birthed' in Unix-land From best_lay at yahoo.com Sun Mar 27 01:04:40 2016 From: best_lay at yahoo.com (Wildman) Date: Sun, 27 Mar 2016 00:04:40 -0500 Subject: Another Key Binding Question References: Message-ID: On Sat, 26 Mar 2016 17:47:02 +0000, MRAB wrote: > On 2016-03-26 17:10, Wildman via Python-list wrote: >> I use some key bindings in my program. They are declared >> like this: >> >> root.bind("" + "q", quit) >> root.bind("" + "q", quit) >> root.bind("" + "Q", quit) >> root.bind("" + "Q", quit) >> >> The above binds both Alt keys with upper and lower case 'q'. >> Is there a way to combine the statements above into one >> statement? >> > Try this: > > root.bind("", quit) > root.bind("", quit) > > The first is for either "Alt" key plus the "Q" key and Caps Lock turned off. Works perfectly. > The second is for either "Alt" key plus the "Q" key and Caps Lock turned on. Also works, however, I discovered if I leave out 'Lock' it still works with caps on. It also works with caps off while holding either Shift key and hitting Alt-q. I tested it with Python 2.7 and 3.4. Well at least I can cut the number of lines down to two per binding like this: root.bind("", quit) root.bind("", quit) Once again I am in your debt. Thank you. -- GNU/Linux user #557453 The cow died so I don't need your bull! From no.email at nospam.invalid Sun Mar 27 01:35:28 2016 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 26 Mar 2016 22:35:28 -0700 Subject: repeat items in a list References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> <6f1ab11b-da4a-49d5-8dcd-bd9b0c6fe8b3@googlegroups.com> Message-ID: <8737rc7aan.fsf@nightsong.com> beliavsky at aol.com writes: > yy = list(chain.from_iterable([list(repeat(aa,nrep)) for aa in xx])) The chain approach seems more natural to me: yy = list(chain.from_iterable(map(lambda x: [x,x], xx))) may make the doubling more obvious, and in Python 3 it should avoid the intermediate lists since map creates a generator. Depending on the usage, you might also not need the outermost list, making yy a lazy generator as well. From rustompmody at gmail.com Sun Mar 27 01:54:25 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 26 Mar 2016 22:54:25 -0700 (PDT) Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <777df6e3-3e5c-4c59-913e-c9447d20173e@googlegroups.com> References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <56f666d8$0$1583$c3e8da3$5496439d@news.astraweb.com> <2e1ce88d-fae2-4aa0-ace9-4faa4878459b@googlegroups.com> <777df6e3-3e5c-4c59-913e-c9447d20173e@googlegroups.com> Message-ID: On Sunday, March 27, 2016 at 10:32:34 AM UTC+5:30, Rustom Mody wrote: > I had an impression of seeing some discussion on this and resolved not > to incorporate. Meaning: I think I remember something about a resolution -- after some debate -- not to OO-ify the C/Unix errno system From no.email at nospam.invalid Sun Mar 27 02:13:21 2016 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 26 Mar 2016 23:13:21 -0700 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87twjs5tz2.fsf@nightsong.com> Steven D'Aprano writes: > For example, would you consider that this isolated C code is > "meaningless"? > int i = n + 1; It's meaningful as long as n is in a certain range of values so there's no overflow. > But according to the standard, it's "meaningless", since it might > overflow, and signed int overflow is Undefined Behaviour. No it's not meaningless if it "might" overflow, it's meaningless if it -does- overflow, so the compiler can do whatever it wants in that case. The compiler is only obliged to do anything specific in the case where there is no overflow, so if it can get some speedups by only generating code for the non-overflow case, it does so: http://kristerw.blogspot.com/2016/02/how-undefined-signed-overflow-enables.html > Compilers are well known for only doing what you tell them to do, not what > you want them to do. But in the case of C and C++ they don't even do what > you tell them to do. They do what you tell them, not what you meant to tell them or what you thought you were telling them. That goes way back before compilers and computers. Think of all the stories about a guy rubbing lamps and getting three wishes. Srsly though, the conclusion is that C and C++ are terrible languages if you want to code anything really solid, not that the compilers are doing anything bad. Unfortunately there's a mountain of legacy code full of such errors, and still a lot of C programmers out there who don't understand the issue. From random832 at fastmail.com Sun Mar 27 02:25:41 2016 From: random832 at fastmail.com (Random832) Date: Sun, 27 Mar 2016 02:25:41 -0400 Subject: Threading is foobared? In-Reply-To: <8560w8d2w3.fsf@benfinney.id.au> References: <56f74d00$0$1620$c3e8da3$5496439d@news.astraweb.com> <8560w8d2w3.fsf@benfinney.id.au> Message-ID: <1459059941.1944713.560644738.2587A129@webmail.messagingengine.com> On Sat, Mar 26, 2016, at 23:18, Ben Finney wrote: > What you've demonstrated is that at least one host is violating > communication standards by altering existing reference fields on > messages in transit. The usenet gateway relays posts that originated on the mailing list to usenet with their *Message-ID* replaced wholesale with "" - 90% of the time when I've traced a broken thread this has been to blame, and I've complained at least twice of this before, once not two weeks ago. From tjreedy at udel.edu Sun Mar 27 02:28:15 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Mar 2016 02:28:15 -0400 Subject: help with program In-Reply-To: References: <1392737302.749065.1459024715818.JavaMail.yahoo.ref@mail.yahoo.com> <1392737302.749065.1459024715818.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 3/26/2016 6:48 PM, Chris Angelico wrote: > On Sun, Mar 27, 2016 at 7:38 AM, Jerry Martens > wrote: >> hi im trying to run this program and it opens a screen really ast >> and closes it faster withou any results. > There are a few ways you could do this. One is to run it from the > command line. Another is to put this line at the end of the program: > > input("Press enter to exit. ") For a tkinter program, use 'root.mainloop()' instead, where root is usually an instance of tkinter.Tk. > That should bring up the same screen (called a "console") and then > have it wait until you're done reading it. If at a terminal, 'python -i file.py' not only keeps the program open, but brings up an interactive prompt so you can interact with the program. This is useful for development. > A third way is to edit your code using Idle, and run it from there. IDLE emulates 'python -i file-in-editor.py' > I haven't done that in a while, though, so the details might have > changed in the recent versions. Still F5 or the menu entry. -- Terry Jan Reedy From no.email at nospam.invalid Sun Mar 27 02:34:11 2016 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 26 Mar 2016 23:34:11 -0700 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87poug5t0c.fsf@nightsong.com> BartC writes: > But my suggestion was to have required a keyword in front of > such expressions. Should there be a keyword in front of a line containing "sqrt(x)" ? What about "launch(missiles)" ? The compiler can't tell which of those expressions has a side effect. The first might be buggy code but the second is idiomatic. From no.email at nospam.invalid Sun Mar 27 02:34:50 2016 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 26 Mar 2016 23:34:50 -0700 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <56f666d8$0$1583$c3e8da3$5496439d@news.astraweb.com> <2e1ce88d-fae2-4aa0-ace9-4faa4878459b@googlegroups.com> Message-ID: <87lh545sz9.fsf@nightsong.com> Rustom Mody writes: > eg haskell (ghc) is written in ghc > Where did the first bootstrap start from? The very earliest Haskell implementation was written in Lisp. From rustompmody at gmail.com Sun Mar 27 03:13:24 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 27 Mar 2016 00:13:24 -0700 (PDT) Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <87lh545sz9.fsf@nightsong.com> References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <56f666d8$0$1583$c3e8da3$5496439d@news.astraweb.com> <2e1ce88d-fae2-4aa0-ace9-4faa4878459b@googlegroups.com> <87lh545sz9.fsf@nightsong.com> Message-ID: On Sunday, March 27, 2016 at 12:05:01 PM UTC+5:30, Paul Rubin wrote: > Rustom Mody writes: > > eg haskell (ghc) is written in ghc > > Where did the first bootstrap start from? > > The very earliest Haskell implementation was written in Lisp. Ummm So you found a little chink in my argument -- Ok :-) Yeah I remember that Paul Hudak of Yale (now deceased) was working on Haskell in Yale-scheme (T). I did not know it ever materialized. However in pragmatic terms I dont think the argument changes; viz. If you take any technology today (and it may not be remotely connected to computers eg the chip that controls the car, the credit card's ATM network layer etc etc, you will invariably find C. All that you need to do is to work out the transitive-closure of the implemented-in/interpreted-by relation. So a C program uses C at 0 removes A CPython program uses C at at 1 A PyPy program at 2 (or 3 or 4 not likely more than that). On a funny note: I was teaching APL and one of the students came and asked me: Did C exist in 1960? No Why? Well You said APL was implemented in 1960 and APL is implemented in C Nothing to match the power of syllogism :-) So yes one can in *principle* have a completely C-less world Just like one can in principle compute the square-root of Graham's number Likewise a cost of a billion dollars de-C-ification is probably a gross underestimate: See https://en.wikipedia.org/wiki/Rock's_law From steve at pearwood.info Sun Mar 27 03:13:30 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 27 Mar 2016 18:13:30 +1100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] References: <56e7483d$0$1608$c3e8da3$5496439d@news.astraweb.com> <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f7881b$0$1604$c3e8da3$5496439d@news.astraweb.com> On Sat, 26 Mar 2016 08:23 am, Chris Angelico wrote: > On Sat, Mar 26, 2016 at 2:50 AM, Steven D'Aprano > wrote: >> Undefined behaviour does not mean "implementation specific behaviour". >> Nor does it mean "something sensible will happen but we don't promise >> what it will be". It means "the compiler can do anything", including >> ignoring the code you actually wrote and substituting its own faster >> code, which may or may not do what your original code did. > > C's undefined behaviour is basically "you're not allowed to do this". > The compiler is free to assume that you will never do this, ergo it is > free to write out machine code that is correct only so long as you do > not do this. Yes, but it's worse than that. The compiler can write out that machine code *even if you do, in fact, do what it assumes you don't do*. Am I the only one that thinks that's rather perverse? Probably not, since most programming languages are safer than C. You don't get this sort of thing happening even in other low-level languages like Forth. And there is a lot of work actively trying to build systems languages that are safer than C, e.g. D and Rust. > Let me draw a Python analogy: > > 1) A well-behaved iterator will return values until it raises > StopIteration, and then raise StopIteration thereafter. > 2) An iterator which raises and then returns is thus badly written and > should not exist. The first part of this is correct: iterators which raise StopIterator, and then later yield values, are indeed *officially* known as "broken". Here is a broken iterator: class Broken: def __init__(self): self.x = 0 def __iter__(self): return self def __next__(self): self.x += 1 if self.x < 6: return self.x if self.x % 2: return "NOBODY expects the Spanish Inquisition!" raise StopIteration I once asked Guido if "broken" iterators should be considered illegal, or an error, and if I remember correctly (I'm pretty sure I do, but don't ask me for a link) he said that they're legal, but you shouldn't write them. If you want to shoot yourself in the foot with a broken iterator, you can. So broken iterators (what you call ill-behaved) are not forbidden. They're just discouraged. For example, if you create an iterator with a "restart" method, that's officially broken. But I don't believe anyone would agree that people should be prohibited from creating a custom iterator that can be restarted. That sort of heavy-handed prescriptivist approach goes against the "consenting adults" philosophy of Python. > 3) A consumer of an iterator is allowed to misbehave in the event that > the iterator returns after raising. Define "misbehave". I think that's the crux of the matter. It's not just Undefined Behaviour *alone* that is so problematic, but that it is linked to a culture of aggressive optimization that is prepared to radically change the semantics of code as compared to what the C abstract machine would do. The iterator protocol is defined such that once an iterator raises, it should continue to raise forever. If you violate that, you're not following the iterator protocol precisely. That's okay, nobody says you have to. But if you don't, you can't complain if code behaves strangely. A similar situation occurs with reflexivity of equality. Python built-ins are allowed to assume that x == x is always true, and optimize equality checks as if a is b: # fast path return True else: # slow path That's great, unless you have NANs or other "weird" objects that violate the assumption that an object is always equal to itself. It's not just built-ins: any class or function is allowed to make the same assumption. In that case, ideally the class or function should document the fact that it assumes reflexivity, but that's a "quality of implementation" detail, and we all know that most coders are crap at documentation. > 4) Therefore an optimizer is free to *cause* the consumer to misbehave > when given an ill-behaved iterator. Unlike C, Python has no official IEC standard where the definitive answer to this (implied) question is written down. We can't look up in the standard to see what Python implementations can do, but we can try to channel Guido and the core developers and guess their attitude based on their public behaviour and the behaviour of the Python reference implementation, CPython. I don't believe that Guido or the core developers would take that position. I expect that they would call that a bug in the optimizer. For example, here's that broken iterator in action: py> x = Broken() py> list(x) [1, 2, 3, 4, 5] py> list(x) ['NOBODY expects the Spanish Inquisition!'] py> list(x) ['NOBODY expects the Spanish Inquisition!'] py> list(x) ['NOBODY expects the Spanish Inquisition!'] So the reference implementation shows clearly that broken iterators are allowed. Until such time as Guido changes his mind, an optimizer that changed this would be officially(?) buggy. My guess is that Guido might accept an optimizer that changed the behaviour is this way, provided it explicitly documented that it was doing so. But possibly not: Guido doesn't seem to care much for optimizers, especially not "clever" ones, and my reading of his attitude is that he somewhat grudgingly accepts them only if they don't change the semantics of Python code. It's hard to tell which he would dislike more: broken iterators, or an optimizer that changed semantics of Python. My money is the second one. (Guido's even expressed disdain for simple keyhole optimizers that perform constant folding.) I'm pretty sure Guido wouldn't allow a general carte blanche for Python compilers to radically change the semantics of code in the name of optimization. So optimizing "x = 1 + 1" to "x = 2" is okay, but: x = Broken() list(x) value = next(x) print("x is technically broken") should not be optimized to: os.system("rm -rf /") no matter how much faster it is. *wink* (In practice, I would expect a C compiler to probably decide that the code I showed was dead code, and throw it all away. But there's no guarantee, and the complexity and aggressiveness of the optimizer is such that it is very difficult to predict what will actually happen.) > Consider this code: > > def zip_forever(*iters, fillvalue=None): > """Like zip_longest, but without the silly rule that > it should terminate once they all finish""" > while True: > yield tuple(next(it, fillvalue) for it in iters) > > If all its iterators are well-behaved, this is identical (modulo > monkey-patching of names like "tuple" and "next") to: > > def zip_forever(*iters, fillvalue=None): > yield from zip_longest(*iters, fillvalue=fillvalue) > tup = (None,) * len(iters) > while True: yield tup > > Is PyPy/FAT Python/some other optimizer permitted to make this change? It's free software, they can make that change if they like. Consenting adults, don'cha know? But then they have to deal with the bug reports when they break people's code. > The only difference between C's "undefined behaviour" and Python's way > of doing the spec is the answer to that one question. C says yes, > you're totally allowed to assume that; the end result in all cases > should be indistinguishable; any time you can detect that it optimized > this away, it's because of a bug somewhere else. Is your code allowed > to misbehave when other code has bugs? That, ultimately, is the > question. No, that's not the difference at all. I'm afraid you have not understood just how radical the C "Undefined Behaviour" standard is, at least in principle (and often in practice as well). > Imagine a tightened up subset of the Python language that restricts > certain unusual behaviours. (This has the same purpose as PyPy's > RPython, and for all I know, RPython might do exactly this.) It's a > narrowly-used single purpose language, and its sole guarantee is that > well-written SubPython code will behave the same way in SubPython as > it does in CPython. It might then, for instance, not permit rebinding > of builtins, nor of function default argument replacements, without an > explicit "drop_caches()" call. Code could then be far more > aggressively optimized - but behaviour would become undefined in the > event that you break one of its rules. That's really all that C's > done, and you honestly don't have to get so panicky at the word > "undefined". It's simply "don't do this". No. It really isn't. Please read the links I provided. All of them. > And let's face it... there's a *lot* of undefined behaviour in CPython > once you play with ctypes. Do we have any language guarantees as to > what will happen if you change the value of the integer 7 to now be 8? > Or will you just say "don't do that"? No, that's not what undefined behaviour means in C. It really does not mean "implementation specific". It is separate and distinct from implementation-defined behaviour. The actual number of bits in a byte is implementation-defined. Almost all C compilers will use 8 bits, but the standard only says it must be *at least* 8 bits. As John Regehr writes: "For now, we can ignore the existence of compilers. There is only the ?C implementation? which ? if the implementation conforms to the C standard ? acts the same as the ?C abstract machine? when executing a conforming program. The C abstract machine is a simple interpreter for C that is described in the C standard. We can use it to determine the meaning of any C program." http://blog.regehr.org/archives/213 (This C abstract machine is what I described earlier as a naive, simple-minded, non-optimizing C compiler, what Raymond Chen calls a "classical compiler". Abstract machine is a much better term than what I used.) Regehr goes on: "Note that even well-defined executions may not have a unique result due to unspecified and implementation-defined behavior; we?ll ignore both of these here." So *undefined behaviour* is not the same as unspecified and implementation-defined behaviour. That's important. What any specific compiler *actually* does is implementation-defined, and in practice, C compilers do not make any backwards-compatibility promises. One compiler might quietly and safely treat integer overflow using wrap-around arithmetic for release after release, and then suddenly without any fanfare erase your hard drive. Regehr again: "If any step in a program?s execution has undefined behavior, then THE ENTIRE EXECUTION IS WITHOUT MEANING. This is important: it?s not that evaluating (1<<32) has an unpredictable result, but rather that the ENTIRE EXECUTION of a program that evaluates this expression is meaningless. Also, it?s not that the execution is meaningful up to the point where undefined behavior happens: the bad effects can actually precede the undefined operation." [Emphasis added.] In Python terms, suppose we have this: arr = [1, 2, 3] for i in range(4): print(arr[i]) # and more code following... The Python virtual machine says that execution should proceed up to the point where the loop prints 3, and then raise IndexError, then halt (if the exception is not caught). The error message given by the IndexError is implementation-specific. But the C virtual machine says that *entire* program (translated into C syntax, obviously) is gibberish, and the compiler can replace the entire program, or any part it likes, with anything it likes. There's no requirement that any specific error occurs, or even that an error occurs. No real C compiler is intentionally going to replace those three lines (translated into C, of course) with a call to erase the hard drive. But the optimizations being applied by real C compilers are sufficiently complex and aggressive that this is something which may occur inadvertently. Here is somebody on Stackoverflow who claims it happened to him: http://stackoverflow.com/a/18506556 and specifically note his later comment: "Oh, explicitly creating the command would have involved only well-defined behavior. The actual bug was UB, and the question was how UB could lead to the deletion of a harddisk. Well, like this: a variable gets corrupted, in this case a path variable, and other bug-free code now starts behaving in unexpected ways. That's a general problem with UB: it breaks strong assumptions about OTHER code." [Emphasis added.] -- Steven From steve at pearwood.info Sun Mar 27 03:40:35 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 27 Mar 2016 18:40:35 +1100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87twjs5tz2.fsf@nightsong.com> Message-ID: <56f78e74$0$1616$c3e8da3$5496439d@news.astraweb.com> On Sun, 27 Mar 2016 05:13 pm, Paul Rubin wrote: > Steven D'Aprano writes: >> For example, would you consider that this isolated C code is >> "meaningless"? >> int i = n + 1; > > It's meaningful as long as n is in a certain range of values so there's > no overflow. > >> But according to the standard, it's "meaningless", since it might >> overflow, and signed int overflow is Undefined Behaviour. > > No it's not meaningless if it "might" overflow, it's meaningless if it > -does- overflow, No! That's exactly wrong! Paul, thank you for inadvertently proving the point I am trying to get across. People, even experienced C coders, simply don't understand what the C standard says and what C compilers can and will do. If the C compiler cannot prove that n is strictly less than MAXINT (or is that spelled INT_MAX?), the *entire program* (or at least the bits reachable from this line, in both directions) is Undefined, and the compiler has no obligations at all. You probably don't believe me because this sounds crazy, something that no sane person would design a programming language to behave. Well, yeah, exactly. It does allow C a lot of powerful optimizations, but only at the cost of making it impossible to reason about the behaviour of code that is Undefined. No real compiler is going to intentionally erase your hard disk, but in non-toy code, it can introduce serious bugs even though you explicitly wrote code to avoid the buggy case. But don't believe me. What do I know about C, I don't even know whether to spell the biggest int MAXINT or INT_MAX or MAX_INT. Instead, believe these guys: http://blog.regehr.org/archives/213 http://blog.regehr.org/archives/226 http://blog.regehr.org/archives/232 http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_21.html https://blogs.msdn.microsoft.com/oldnewthing/20140627-00/?p=633/ https://randomascii.wordpress.com/2014/05/19/undefined-behavior-can-format-your-drive/ I've emphasised all the bad things that undefined behaviour causes, but the above (written by C programmers who presumably like C) are much more even-handed, describing the good things that compilers can get out of this. -- Steven From steve at pearwood.info Sun Mar 27 03:50:58 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 27 Mar 2016 18:50:58 +1100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f790e5$0$1603$c3e8da3$5496439d@news.astraweb.com> On Sun, 27 Mar 2016 01:30 am, Chris Angelico wrote: > On Sun, Mar 27, 2016 at 1:09 AM, BartC wrote: >> I'm surprised that both C and Python allow statements that apparently do >> nothing. In both, an example is: >> >> x >> >> on a line by itself. This expression is evaluated, but then any result >> discarded. If there was a genuine use for this (for example, reporting >> any error with the evaluation), then it would be simple enough to require >> a keyword in front. > > Tell me, which of these is a statement that "does nothing"? > > foo > foo.bar > foo["bar"] > foo.__call__ > foo() > int(foo) > > All of them are expressions to be evaluated and the result discarded. Right. And with the exception of the first, all of them could call arbitrary code (a property, __getattr__, __getitem__, etc.) and hence could have side-effects. But the first one is special. It can only do two things: evaluate a name, then silently throw the result away, or raise NameError. Bart's point is that Python *could* (and arguably should) define the first one, a bare name, as a SyntaxError. If you want to test for the existence of a name, you would have to write something like (let's say): ifundef raw_input: raw_input = input One might argue that according to the Zen, this is more Pythonic than the status quo of a try...except. It's an explicit test of whether a name is undefined, and it avoids at least some silent errors (where an expression with no side-effects is evaluated, and the result silently thrown away). We could argue the pros and cons of the two approaches, or even a more radical approach like Javascripts where names evaluate as undef if they haven't been defined yet. But one thing is certain: there is a class of error which only occurs because it is legal to evaluate a bare name and do nothing with the result. > Point is, CPython can generally assume that bug-free code will never > get anywhere *near* the limit of a signed integer. Consequently, C's > undefined behaviour isn't a problem; it does NOT mean we need to be > scared of signed integers. I think you have badly misunderstood the nature of the problem. My C is a bit rusty, so excuse me if I get the syntax wrong. I have a function: void foo(int n) { int i = n + 1; bar(i); } There's a possible overflow of a signed int in there. This is undefined behaviour. Now, you might think to yourself: "Well, that's okay. So long as n is not equal to MAXINT, the overflow will never occur, which means the undefined behaviour will never occur, which means that bar will be called with (n+1) as argument. So foo is safe, so long as n is smaller than MAXINT in practice." And then go on to write something like: # my C is getting rustier by the second, sorry int n = read_from_instrument(); foo(n); secure in the knowledge that your external hardware instrument generates values 0 to 1000 and will never go near MAXINT. But the C compiler doesn't know that, so it has to assume that n can be any int, including MAXINT. Consequently your foo is "meaningless" and your code can legally be replaced by: int n = read_from_instrument(); erase_hard_drive(); regardless of the actual value of n. Taken in isolation, of course this is absurd, and no compiler would actually do that. But in the context of an entire application, it is very difficult to predict what optimizations the compiler will take, what code will be eliminated, what code will be reordered, and the nett result is that hard drives may be erased, life support systems could be turned off, safety systems can be disabled, passwords may be exposed, arbitrary code may be run. I'm sure that there are ways of guarding against this. There are compiler directives that you can use to tell the compiler not to optimize the call to foo, or command line switches to give warnings, or you might be able to guard against this: int n = read_from_instrument(); if n < MAXINT { foo(n); } But even the Linux kernel devs have been bitten by this sort of thing. With all the warnings and linters and code checkers and multiple reviews by experts, people get bitten by undefined behaviour. What you can't do is say "foo is safe unless n actually equals MAXINT". That's wrong. foo is unsafe if the C compiler is unable to determine at compile-time whether or not n could ever, under any circumstances, be MAXINT. If n might conceivably ever be MAXINT, then the behaviour of foo is undefined. Not implementation-specific, or undocumented. Undefined, in the special C meaning of the term. -- Steven From rustompmody at gmail.com Sun Mar 27 03:52:04 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 27 Mar 2016 00:52:04 -0700 (PDT) Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <56f78e74$0$1616$c3e8da3$5496439d@news.astraweb.com> References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87twjs5tz2.fsf@nightsong.com> <56f78e74$0$1616$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sunday, March 27, 2016 at 1:10:51 PM UTC+5:30, Steven D'Aprano wrote: > On Sun, 27 Mar 2016 05:13 pm, Paul Rubin wrote: > > > No it's not meaningless if it "might" overflow, it's meaningless if it > > -does- overflow, > > No! That's exactly wrong! > > Paul, thank you for inadvertently proving the point I am trying to get > across. People, even experienced C coders, simply don't understand what the > C standard says and what C compilers can and will do. Yeah this misunderstanding is a deep one People find it hard to get the halting problem: for(;;) ; is an infinite loop. Whats the big deal? Why is it 'impossible' to detect? Its hard because we have to reason all possible inputs (and for language implementations, all possible programs) when these are yet unavailable unwritten JFTR I am not remotely arguing that C is not dangerous. http://blog.languager.org/2013/02/c-in-education-and-software-engineering.html It was bad in 1991 and has probably got worse with a totally networked world of nameless hoods. I am just saying no-C is no-option [Considering the day it is you may wish to consider prayer :-) ] From tonycamgar at gmail.com Sun Mar 27 04:02:14 2016 From: tonycamgar at gmail.com (Antonio Caminero Garcia) Date: Sun, 27 Mar 2016 01:02:14 -0700 (PDT) Subject: repeat items in a list In-Reply-To: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> Message-ID: <74fc27bf-22fe-4f7e-ac54-78be6b518562@googlegroups.com> On Saturday, March 26, 2016 at 11:12:58 PM UTC+1, beli... at aol.com wrote: > I can create a list that has repeated elements of another list as follows: > > xx = ["a","b"] > nrep = 3 > print xx > yy = [] > for aa in xx: > for i in range(nrep): > yy.append(aa) > print yy > > output: > ['a', 'b'] > ['a', 'a', 'a', 'b', 'b', 'b'] > > Is there a one-liner to create a list with repeated elements? What about this? def rep_elements(sequence, nrep): #return [ritem for item in sequence for ritem in [item]*nrep] return list(chain.from_iterable(([item]*nrep for item in sequence))) sequence = ['h','o','l','a'] print(rep_elements(sequence, 3)) From tonycamgar at gmail.com Sun Mar 27 04:30:01 2016 From: tonycamgar at gmail.com (Antonio Caminero Garcia) Date: Sun, 27 Mar 2016 01:30:01 -0700 (PDT) Subject: repeat items in a list In-Reply-To: <74fc27bf-22fe-4f7e-ac54-78be6b518562@googlegroups.com> References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> <74fc27bf-22fe-4f7e-ac54-78be6b518562@googlegroups.com> Message-ID: <20935e0a-0b54-4213-b651-b33ad3910510@googlegroups.com> On Sunday, March 27, 2016 at 10:02:44 AM UTC+2, Antonio Caminero Garcia wrote: > On Saturday, March 26, 2016 at 11:12:58 PM UTC+1, beli... at aol.com wrote: > > I can create a list that has repeated elements of another list as follows: > > > > xx = ["a","b"] > > nrep = 3 > > print xx > > yy = [] > > for aa in xx: > > for i in range(nrep): > > yy.append(aa) > > print yy > > > > output: > > ['a', 'b'] > > ['a', 'a', 'a', 'b', 'b', 'b'] > > > > Is there a one-liner to create a list with repeated elements? > > What about this? > > def rep_elements(sequence, nrep): > #return [ritem for item in sequence for ritem in [item]*nrep] > return list(chain.from_iterable(([item]*nrep for item in sequence))) > > sequence = ['h','o','l','a'] > print(rep_elements(sequence, 3)) I prefer the commented solution :). [ritem for item in sequence for ritem in [item]*nrep] # O(len(sequence)*2nrep) and the chain solution would be # O(len(sequence)*nrep). The constants ate gone so I prefer the first one for its readibility. On a practical level: https://bpaste.net/show/fe3431a13732 From oscar.j.benjamin at gmail.com Sun Mar 27 05:51:20 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 27 Mar 2016 10:51:20 +0100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <56f790e5$0$1603$c3e8da3$5496439d@news.astraweb.com> References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <56f790e5$0$1603$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 27 Mar 2016 10:56, "Steven D'Aprano" wrote: > > > My C is a bit rusty, so excuse me if I get the syntax wrong. I have a > function: > > void foo(int n) { > int i = n + 1; > bar(i); > } > > There's a possible overflow of a signed int in there. This is undefined > behaviour. Now, you might think to yourself: > > "Well, that's okay. So long as n is not equal to MAXINT, the overflow will > never occur, which means the undefined behaviour will never occur, which > means that bar will be called with (n+1) as argument. So foo is safe, so > long as n is smaller than MAXINT in practice." > > And then go on to write something like: > > # my C is getting rustier by the second, sorry > int n = read_from_instrument(); > foo(n); > > > secure in the knowledge that your external hardware instrument generates > values 0 to 1000 and will never go near MAXINT. But the C compiler doesn't > know that, so it has to assume that n can be any int, including MAXINT. > Consequently your foo is "meaningless" and your code can legally be > replaced by: > > int n = read_from_instrument(); > erase_hard_drive(); This is incorrect. Provided n does not take the value INT_MAX the code is conforming and the standard mandates how it should behave. The compiler is allowed to make optimisations that assume n never takes that value such that in the circumstances where n *would* take that value any behaviour is acceptable. The compiler is not free to say "I don't know if it would take that value so I'm unconstrained even if it does not". > > regardless of the actual value of n. Taken in isolation, of course this is > absurd, and no compiler would actually do that. But in the context of an > entire application, it is very difficult to predict what optimizations the > compiler will take, what code will be eliminated, what code will be > reordered, and the nett result is that hard drives may be erased, life > support systems could be turned off, safety systems can be disabled, > passwords may be exposed, arbitrary code may be run. > > I'm sure that there are ways of guarding against this. There are compiler > directives that you can use to tell the compiler not to optimize the call > to foo, or command line switches to give warnings, or you might be able to > guard against this: > > int n = read_from_instrument(); > if n < MAXINT { > foo(n); > } This is correct. It is now impossible for the addition n+1 to overflow since we cannot hit that code if n is INT_MAX. > But even the Linux kernel devs have been bitten by this sort of thing. With > all the warnings and linters and code checkers and multiple reviews by > experts, people get bitten by undefined behaviour. I think you're overegging this a bit. Many experienced programmers get bitten by bugs while working in many languages. C is more troublesome than many and there is room for improvement but it's not as dramatic as you suggest. > What you can't do is say "foo is safe unless n actually equals MAXINT". > That's wrong. foo is unsafe if the C compiler is unable to determine at > compile-time whether or not n could ever, under any circumstances, be > MAXINT. If n might conceivably ever be MAXINT, then the behaviour of foo is > undefined. Not implementation-specific, or undocumented. Undefined, in the > special C meaning of the term. I think you've misunderstood this: signed addition that would not overflow is well defined so the optimiser cannot alter the semantics in that case. It is free to assume that values that would overflow will not occur and alter execution in surprising ways but that's not the same as rewriting valid code on the assumption that an invalid value cannot be proven not to occur. Rather the onus is on the optimiser to prove that the optimised code is equivalent for all inputs where behaviour is defined. -- Oscar From larudwer at freenet.de Sun Mar 27 05:52:05 2016 From: larudwer at freenet.de (larudwer) Date: Sun, 27 Mar 2016 11:52:05 +0200 Subject: repeat items in a list References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> Message-ID: how about >>>> sorted(["a", "b"]*3) ['a', 'a', 'a', 'b', 'b', 'b'] From mail at timgolden.me.uk Sun Mar 27 06:29:14 2016 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 27 Mar 2016 11:29:14 +0100 Subject: Threading is foobared? In-Reply-To: <1459059941.1944713.560644738.2587A129@webmail.messagingengine.com> References: <56f74d00$0$1620$c3e8da3$5496439d@news.astraweb.com> <8560w8d2w3.fsf@benfinney.id.au> <1459059941.1944713.560644738.2587A129@webmail.messagingengine.com> Message-ID: <56F7B5FA.4040002@timgolden.me.uk> On 27/03/2016 07:25, Random832 wrote: > On Sat, Mar 26, 2016, at 23:18, Ben Finney wrote: >> What you've demonstrated is that at least one host is violating >> communication standards by altering existing reference fields on >> messages in transit. > > The usenet gateway relays posts that originated on the mailing list to > usenet with their *Message-ID* replaced wholesale with > "" - 90% of the time when I've traced > a broken thread this has been to blame, and I've complained at least > twice of this before, once not two weeks ago. And I apologise because I saw that complaint and had meant to reply. In short, it's not the list owners who manage the gateway but rather the mailman administrators for the whole of the python.org lists. I do remember some discussion / explanation of possible problems when the mailman version was upgraded a few months ago. I'll try to dig those out and follow up with the people involved. FWIW I assume the issue is with the mail -> news gateway as I see no problems with the mailing list threading (at least using TB on Windows) and the archive doesn't appear to lose threading either AFAICT. Please feel free to point out if I'm wrong about that. TJG From jussi.piitulainen at helsinki.fi Sun Mar 27 07:09:27 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Sun, 27 Mar 2016 14:09:27 +0300 Subject: repeat items in a list References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> <74fc27bf-22fe-4f7e-ac54-78be6b518562@googlegroups.com> Message-ID: Antonio Caminero Garcia writes: > On Saturday, March 26, 2016 at 11:12:58 PM UTC+1, beli... at aol.com wrote: >> I can create a list that has repeated elements of another list as >> follows: >> >> xx = ["a","b"] >> nrep = 3 >> print xx >> yy = [] >> for aa in xx: >> for i in range(nrep): >> yy.append(aa) >> print yy >> >> output: >> ['a', 'b'] >> ['a', 'a', 'a', 'b', 'b', 'b'] >> >> Is there a one-liner to create a list with repeated elements? > > What about this? > > def rep_elements(sequence, nrep): > #return [ritem for item in sequence for ritem in [item]*nrep] > return list(chain.from_iterable(([item]*nrep for item in sequence))) > > sequence = ['h','o','l','a'] > print(rep_elements(sequence, 3)) A thing to know about the comprehension-syntaxes is that they correspond precisely to nested loops (and conditions, but conditions don't appear in the present example) with an .append inside. xx = "ab" nrep = 3 print([ aa for aa in xx for i in range(nrep) ]) (This has been posted in this thread a few times already, but I think the systematic correspondence to the original loops was left unstated. Apologies in advance if I missed something.) The resulting list has some hidden name. The original loops should be re-mentalized for an even closer correspondence as follows. g47 = [] for aa in xx: # Loopy ... for i in range(nrep): # ... do! g47.append(aa) # <-- _This_ aa is one of the result items. yy = g47 A thing about range objects is that they can be reused, so the present example could also reuse just one. xx = "ab" reps = range(3) print([ aa for aa in xx for i in reps ]) From tonycamgar at gmail.com Sun Mar 27 07:13:54 2016 From: tonycamgar at gmail.com (Antonio Caminero Garcia) Date: Sun, 27 Mar 2016 04:13:54 -0700 (PDT) Subject: repeat items in a list In-Reply-To: References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> Message-ID: <29bb9c16-eef4-4c00-9e41-ce8419405c29@googlegroups.com> On Sunday, March 27, 2016 at 11:52:22 AM UTC+2, larudwer wrote: > how about > > >>>> sorted(["a", "b"]*3) > ['a', 'a', 'a', 'b', 'b', 'b'] that's cooler, less efficient though and do not maintain the original order. In case such order was important, you should proceed as follows: If the elements are unique, this would work: sorted(sequence*nrep, key=sequence.index) Otherwise you'd need a more complex key function (maybe a method of a class with a static variable that tracks the number of times that such method is called and with a "dynamic index functionality" that acts accordingly (i-th nrep-group of value v)) and imo it does not worth it. From bc at freeuk.com Sun Mar 27 07:31:26 2016 From: bc at freeuk.com (BartC) Date: Sun, 27 Mar 2016 12:31:26 +0100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <87poug5t0c.fsf@nightsong.com> References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> Message-ID: On 27/03/2016 07:34, Paul Rubin wrote: > BartC writes: >> But my suggestion was to have required a keyword in front of >> such expressions. > > Should there be a keyword in front of a line containing "sqrt(x)" ? > What about "launch(missiles)" ? They both look like function calls. Function calls are *very* commonly used as standalone expressions. You /could/ stipulate that they be written: call launch(missiles) # like Fortran iirc but that wouldn't be popular and is unnecessary. > The compiler can't tell which of those expressions has a side effect. > The first might be buggy code but the second is idiomatic. Whether there are side-effects is not quite as important as picking up things that are likely to be errors: f() # Probably OK g() # Probably OK f()+g() # Probably not OK Maybe there is some legitimate, obscure reason for writing the latter, but stick some indicator in front to tell the language (and whoever happens to be reading the code) that this is what you intend. In the case of sqrt(), many languages appear to treat maths operators as regular functions, so would be hard to justify special treatment. And in Python, 'sqrt' could be reassigned to do something different. -- Bartc From mal at europython.eu Sun Mar 27 08:14:21 2016 From: mal at europython.eu (M.-A. Lemburg) Date: Sun, 27 Mar 2016 14:14:21 +0200 Subject: EuroPython 2016: More than 150 sessions waiting for you Message-ID: <56F7CE9D.1000208@europython.eu> Just in case you didn?t find enough Easter eggs today, we have a whole basket of them waiting for you: the first set of accepted sessions for EuroPython 2016 in Bilbao. *** EuroPython 2016 Session List *** https://ep2016.europython.eu/en/events/sessions/ The sessions were selected on the basis of your talk voting and the work of the EuroPython program work group. From the around 300 proposals, 156 sessions were chosen for EuroPython 2016 in the first round: * 125 talks * 20 training sessions * 11 local track talks We still have several other session types coming (helpdesks, posters, panels, interactive sessions). These will announced separately. Early in June we will have a short second Call for Proposals, limited to hot topics and most recent developments in software and technology. We will announce details soon. Many thanks to everyone who submitted proposals. EuroPython wouldn?t be possible without our speakers. The program work group will now work on the schedule. Given the number of sessions, this may take a while, but we?ll try to get it done as quickly as possible. The WG is also putting together a submission waiting list, which will be used to fill slots of speakers who cannot attend. Speakers on the waiting list will be contacted by the end of next week. Happy Easter Weekend ! With gravitational regards, -- EuroPython 2016 Team http://ep2016.europython.eu/ http://www.europython-society.org/ From hongyi.zhao at gmail.com Sun Mar 27 09:24:05 2016 From: hongyi.zhao at gmail.com (Hongyi Zhao) Date: Sun, 27 Mar 2016 13:24:05 +0000 (UTC) Subject: Calling the source command from subprocess.popen to update the os.environ. Message-ID: Hi all, Based on the methods here: http://stackoverflow.com/questions/7040592/calling-the-source-command- from-subprocess-popen/18897007#comment30954741_12708396 I use the following code the update the os.environ: import os from subprocess import check_output # POSIX: name shall not contain '=', value doesn't contain '\0' output = check_output("source /home/werner/env-intel-toolchains.sh; env -0", shell=True, executable="/bin/bash") # replace env os.environ.clear() os.environ.update(line.partition('=')[::2] for line in output.split('\0')) In the above code, the file /home/werner/env-intel-toolchains.sh will be sourced and its settings should be combined into the current os.environ of python. But, I find that the above code will fail on the `os.environ.clear()' command as follows: In[24]: import os from subprocess import check_output # POSIX: name shall not contain '=', value doesn't contain '\0' output = check_output("source /home/werner/env-intel-toolchains.sh; env -0", shell=True, executable="/bin/bash") # replace env os.environ.clear() os.environ.update(line.partition('=')[::2] for line in output.split('\0')) Traceback (most recent call last): File "/home/werner/anaconda2/lib/python2.7/site-packages/IPython/core/ interactiveshell.py", line 3066, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "", line 10, in os.environ.clear() File "/home/werner/anaconda2/lib/python2.7/os.py", line 501, in clear unsetenv(key) OSError: [Errno 22] Invalid argument If I don't use the `os.environ.clear()' code line, it will work smoothly. Any hints? Regards -- .: Hongyi Zhao [ hongyi.zhao AT gmail.com ] Free as in Freedom :. From darinc at gmail.com Sun Mar 27 09:26:15 2016 From: darinc at gmail.com (Darin Gordon) Date: Sun, 27 Mar 2016 09:26:15 -0400 Subject: Announcing the release of Yosai: a security framework for python applications Message-ID: Hey Everyone! I am very glad to announce the first release of Yosai, a security framework for python applications. Details, including link to project: http://www.daringordon.com/introducing_yosai Regards Darin From ben+python at benfinney.id.au Sun Mar 27 09:59:58 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 28 Mar 2016 00:59:58 +1100 Subject: Calling the source command from subprocess.popen to update the os.environ. References: Message-ID: <85mvpkaun5.fsf@benfinney.id.au> Hongyi Zhao writes: > I use the following code the update the os.environ: > > import os > from subprocess import check_output > > # POSIX: name shall not contain '=', value doesn't contain '\0' > output = check_output("source /home/werner/env-intel-toolchains.sh; > env -0", shell=True, executable="/bin/bash") That will start a new process (running ?/bin/bash?), then execute some commands from a script file in that process. When that new process ends, any changes in its environment also disappear. At no point do changes to that new process's environment have any effect on the Python process. A Unix process is *completely unable* to change the environment variables of its parent. It can change its own variables, and optionally those of its child processes. This is by design. It's a good thing. So if you want the Python process's environment to change, then it needs to be: * Inherited from an *already* changed environment when it starts. Or: * Changed within the Python process, by the Python API for that purpose (?os.environ?). You will not be able to change a Python process environment by starting new processes. -- \ ?Faith, n. Belief without evidence in what is told by one who | `\ speaks without knowledge, of things without parallel.? ?Ambrose | _o__) Bierce, _The Devil's Dictionary_, 1906 | Ben Finney From ben+python at benfinney.id.au Sun Mar 27 10:01:33 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 28 Mar 2016 01:01:33 +1100 Subject: Announcing the release of Yosai: a security framework for python applications References: Message-ID: <85io08auki.fsf@benfinney.id.au> Darin Gordon writes: > I am very glad to announce the first release of Yosai, a security > framework for python applications. > > Details, including link to project: > http://www.daringordon.com/introducing_yosai Rather than just a link, can you please give a couple of paragraphs explaining what is the purpose of the library, and why we might be interested? -- \ ?Value your freedom or you will lose it, teaches history. | `\ ?Don't bother us with politics,? respond those who don't want | _o__) to learn.? ?Richard M. Stallman, 2002 | Ben Finney From oscar.j.benjamin at gmail.com Sun Mar 27 10:15:54 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 27 Mar 2016 15:15:54 +0100 Subject: Calling the source command from subprocess.popen to update the os.environ. In-Reply-To: <85mvpkaun5.fsf@benfinney.id.au> References: <85mvpkaun5.fsf@benfinney.id.au> Message-ID: On 27 Mar 2016 17:01, "Ben Finney" wrote: > > Hongyi Zhao writes: > > > I use the following code the update the os.environ: > > > > import os > > from subprocess import check_output > > > > # POSIX: name shall not contain '=', value doesn't contain '\0' > > output = check_output("source /home/werner/env-intel-toolchains.sh; > > env -0", shell=True, executable="/bin/bash") > > That will start a new process (running ?/bin/bash?), then execute some > commands from a script file in that process. > > When that new process ends, any changes in its environment also > disappear. ...unless the subprocess prints them out or something. I think you skimmed the code and question a little too quickly. From jussi.piitulainen at helsinki.fi Sun Mar 27 10:16:23 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Sun, 27 Mar 2016 17:16:23 +0300 Subject: Why lambda in loop requires default? References: Message-ID: gvim writes: > Given that Python, like Ruby, is an object-oriented language why > doesn't this: > > def m(): > a = [] > for i in range(3): a.append(lambda: i) > return a > > b = m() > for n in range(3): print(b[n]()) # => 2 2 2 I'm going to suggest two variations that may or may not work for you, with very brief glosses. Just ignore them if you don't see their relevance. First, consider: def w(): a = [] for i in range(3): a.append(lambda: i) i = "!" return a b = w() for f in b: print(f()) # => ! ! ! (Those functions depend on the i in the loop.) > lambda i=i: i > > ... is needed to make it work in Python. Just wondered why? And second, consider: lambda x=i: x (Those functions are independent of the i in the loop.) From bgailer at gmail.com Sun Mar 27 10:18:24 2016 From: bgailer at gmail.com (Bob Gailer) Date: Sun, 27 Mar 2016 10:18:24 -0400 Subject: help with program In-Reply-To: References: <1392737302.749065.1459024715818.JavaMail.yahoo.ref@mail.yahoo.com> <1392737302.749065.1459024715818.JavaMail.yahoo@mail.yahoo.com> Message-ID: The problem with putting input at the end of a program is: if the program raises an exception you won't see it. From rosuav at gmail.com Sun Mar 27 10:34:06 2016 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 28 Mar 2016 01:34:06 +1100 Subject: Calling the source command from subprocess.popen to update the os.environ. In-Reply-To: References: Message-ID: On Mon, Mar 28, 2016 at 12:24 AM, Hongyi Zhao wrote: > # replace env > os.environ.clear() > os.environ.update(line.partition('=')[::2] for line in output.split('\0')) > > Traceback (most recent call last): > File "/home/werner/anaconda2/lib/python2.7/site-packages/IPython/core/ > interactiveshell.py", line 3066, in run_code > exec(code_obj, self.user_global_ns, self.user_ns) > File "", line 10, in > os.environ.clear() > File "/home/werner/anaconda2/lib/python2.7/os.py", line 501, in clear > unsetenv(key) > OSError: [Errno 22] Invalid argument > > If I don't use the `os.environ.clear()' code line, it will work smoothly. Do you need to clear the environment first? Anything that's been overwritten will replace stuff in os.environ, so the only reason to clear it would be if you expect your env script to unset things. Is that the case? I'm not sure why the clear is a problem. Here's how I'd start debugging it: for var in os.environ: try: del os.environ[var] except OSError: print(var) Two possibilities: Either that raises OSError errno 22, same as clear() does; or it doesn't. If it doesn't, you should have a clear env, and all should be working (if a little odd) - and then you can look into the possible bug with clear(). But more likely it will, and then you'll be able to see exactly which key triggered the error. Check out what that key is; maybe there's some kind of special environment variable that can't be cleared?? Worst case, you can always do this "clear whatever you can", and then do your environ.update(). Assuming you never need to clear one of the unclearables, this'll give you the same env update as sourcing the script did. And worst worst case, you could probably exec to bash, source the script, and exec back into Python. That should properly update the environment, but it's a somewhat hamfisted way to go about it :) ChrisA From mohamadmaaz5 at gmail.com Sun Mar 27 10:38:50 2016 From: mohamadmaaz5 at gmail.com (mohamadmaaz5 at gmail.com) Date: Sun, 27 Mar 2016 07:38:50 -0700 (PDT) Subject: Help with python script for NMR Message-ID: <89a6c69e-5f60-47d7-99db-4004966fc7c5@googlegroups.com> Hello there, I found a python script in a scientific article that enables a simple calculation on an NMR spectrum. I have no experience in programming and i would appreciate it if i can communicate with someone who can write this script and send it to me by mail in py format. It's a short script but i keep making alot of mistaken and it fails every time. Anyone's interested in helping me ? Thanks From bc at freeuk.com Sun Mar 27 10:43:33 2016 From: bc at freeuk.com (BartC) Date: Sun, 27 Mar 2016 15:43:33 +0100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> Message-ID: On 27/03/2016 14:47, Dennis Lee Bieber wrote: > On Sun, 27 Mar 2016 12:31:26 +0100, BartC declaimed the > following: > >> On 27/03/2016 07:34, Paul Rubin wrote: >>> BartC writes: >>>> But my suggestion was to have required a keyword in front of >>>> such expressions. >>> >>> Should there be a keyword in front of a line containing "sqrt(x)" ? >>> What about "launch(missiles)" ? >> >> They both look like function calls. Function calls are *very* commonly >> used as standalone expressions. >> >> You /could/ stipulate that they be written: >> >> call launch(missiles) # like Fortran iirc >> > Except that FORTRAN also explicitly defines them as > > subroutine xxx() > vs > return-type function yyy() > > and will generate a compile error if you "call" the latter, or put the > former in-line of an expression > > This would be the equivalent of removing "def" from Python, and adding > two new keywords: "sub" and "fun"; modifying the behavior so that "fun"s > must have an explicit return statement (preferably with an explicit return > value), whereas "sub"s have no return and just ... end... Well, that could be done in Python (not so usefully because you can't take account of such info until a call is attempted), but that's not what I'm talking about, which is simply allowing: fn(...) whether fn has an explicit return or not, and not allowing: fn # and other kinds of expression unless some keyword is used. (I've no idea what that might be; all the best ones are taken. But I've already said a keyword can be emulated via a dummy function call.) -- Bartc From joel.goldstick at gmail.com Sun Mar 27 10:49:37 2016 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 27 Mar 2016 10:49:37 -0400 Subject: Help with python script for NMR In-Reply-To: <89a6c69e-5f60-47d7-99db-4004966fc7c5@googlegroups.com> References: <89a6c69e-5f60-47d7-99db-4004966fc7c5@googlegroups.com> Message-ID: On Sun, Mar 27, 2016 at 10:38 AM, wrote: > Hello there, > I found a python script in a scientific article that enables a simple > calculation on an NMR spectrum. > I have no experience in programming and i would appreciate it if i can > communicate with someone who can write this script and send it to me by > mail in py format. It's a short script but i keep making alot of mistaken > and it fails every time. > Anyone's interested in helping me ? > Thanks > -- > https://mail.python.org/mailman/listinfo/python-list > copy the code here. You will get help, but people don't generally write programs for others here -- Joel Goldstick http://joelgoldstick.com/ http://cc-baseballstats.info/ From mohamadmaaz5 at gmail.com Sun Mar 27 11:13:49 2016 From: mohamadmaaz5 at gmail.com (mohamadmaaz5 at gmail.com) Date: Sun, 27 Mar 2016 08:13:49 -0700 (PDT) Subject: Help with python script for NMR In-Reply-To: References: <89a6c69e-5f60-47d7-99db-4004966fc7c5@googlegroups.com> Message-ID: <5f7ff60d-0297-4bee-b3e4-3af0ca757dfe@googlegroups.com> On Sunday, March 27, 2016 at 4:50:01 PM UTC+2, Joel Goldstick wrote: > On Sun, Mar 27, 2016 at 10:38 AM, wrote: > > > Hello there, > > I found a python script in a scientific article that enables a simple > > calculation on an NMR spectrum. > > I have no experience in programming and i would appreciate it if i can > > communicate with someone who can write this script and send it to me by > > mail in py format. It's a short script but i keep making alot of mistaken > > and it fails every time. > > Anyone's interested in helping me ? > > Thanks > > -- > > https://mail.python.org/mailman/listinfo/python-list > > > > copy the code here. You will get help, but people don't generally write > programs for others here > > -- > Joel Goldstick > http://joelgoldstick.com/ > http://cc-baseballstats.info/ this is the script. the thing is that i have zero experience in writing and i cant find the error. all i need is to embed this script to perfome a relatively simple calculation on a spectra. hope anyone can help. thanks #! /usr /bin/envpython #encoding:utf- 8 i m p o r tnmrtec . nmrNotebook . c o n t r o l l e r . C o n t r o l l e r as Cont i m p o r tnmrtec . u t i l as u t i l i m p o r tnmrtec . nmrNotebook . model . common .nmrCommon as nmrcom c l a s sBarycentre : """ computesthebarycenterofeach definedr e c t a n g l eanddeducesthe p o l y d i s p e r s i t yindexofthes o l u t i o n """ d e fi n i t( s e l f ) : """ i n i t i a l i z e sandgetthei n t e g r a t i o ncoo rdin ates """ df =1.86#tobechangedf o reachtypeof... ... molecule f r o mNNBlibimportDialogText , l i s t O f R e c t a n g l e s s e l f . d a t a = NNB . l o a d C u r r e n t D a t a ( ) i f( getdim () != 2 ) : s e l f . die (" Tobeappliedon2Donly" ) i flen ( listOfRectangles () ) == 1 : s e l f . die (" Youmustaddarectangletodefineazoomregion. " ) i flen ( listOfRectangles () )>2 : s e l f . die (" expectedtwozoomregion. %dzoomregionsweredefined. " % ... ...len ( listOfRectangles () ) ) f o riin[ 0 , 1 ] : indexRect = listOfRectangles () [ i ] dim (2) s e l f . F1Left = int ( indexRect [ 0 ] ) s e l f . F1Right = int ( indexRect [ 2 ] ) s e l f . F2Left = int ( indexRect [ 1 ] ) s e l f . F2Right = int ( indexRect [ 3 ] ) i fi==0 : b = s e l f . pointToDamping ( s e l f . barycenter () ) b = b* *(- df ) else: a = s e l f . pointToDamping ( s e l f . barycenter () ) a = a * *(- df ) ip=a/b i fip<1.0: ip= 1/ ip r e s u l t=" p o l y d i s p e r s i t yindex: %s" %ip DialogText (" Resultat" , r e s u l t ) #--------------------------------------------------------------------------- defpointToDamping ( s e l f , value ) : " " " p o i n t T o D a m p i n gc o n v e r t sp o i n t su n i t si n t od i f f u s i o nu n i t s """ c = Cont . getCurrentControllerDeDocument ( ) f o l d = c . getCurrentNMRFolder ( ) nsa = f o l d . getNNBNMRSpectrum ( ) . getAxisF ( 1 ) p r i n tvalue newdamping = u t i l . NMRUnitToolKit . pointToUnit (nmrcom . NMRUnit . ... ...UNITDAMPING, nsa , value ) r e t u r nnewdamping #--------------------------------------------------------------------------- d e fbarycenter ( s e l f ) : """ r e a l i z ethei n t e g r a t i o noverthei n t e g r a t i o nzones (obtainedati n i t i a l i z a t i o n) """ #i n i t i a l i s a t i o ndud a t a b u f f e razero dim ( 1 ) zero ( ) put (" data" ) #onmetl apremierecolonne dim ( 2 ) c o l ( i n t ( s e l f . F2Left ) ) dim ( 1 ) put (" data" ) f o rcolumninrange ( s e l f . F2Left +1, s e l f . F2Right +1) : dim ( 2 ) c o l ( i n t ( column ) ) dim ( 1 ) a d d d a t a ( ) p u t (" data" ) dim(1) get (" data" ) m=0 n=0 f o riinrange ( s e l f . F1Left , s e l f . F1Right+1) : m += float ( val1d ( i ) )*i n += float ( val1d ( i ) ) b = m/n returnb #thenexecute Barycentre () i fname==" main" : try: Barycentre () except: fromNNBlibimportalert , formatExceptionInfo try: alert ( formatExceptionInfo () ) except: raise" shouldneverhappen" From jussi.piitulainen at helsinki.fi Sun Mar 27 11:15:59 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Sun, 27 Mar 2016 18:15:59 +0300 Subject: Why lambda in loop requires default? References: Message-ID: gvim writes: > Given that Python, like Ruby, is an object-oriented language why > doesn't this: > > def m(): > a = [] > for i in range(3): a.append(lambda: i) > return a > > b = m() > for n in range(3): print(b[n]()) # => 2 2 2 > > ... work the same as this in Ruby: > > def m > a = [] > (0..2).each {|i| a << ->(){i}} > a > end > > aa = m > (0..2).each {|n| puts aa[n].()} # => 0 1 2 No, I'm not taking this to private correspondence, and *I'm* not going to talk about why Python "couldn't" do certain things differently when other languages apparently can. I don't know Ruby. It looks gibberish to me, but my *guess* is that the following way to make Python give you what you want is not "fiddling" at all but the exact *same* thing that Ruby makes you do. fs = [ (lambda i: (lambda : i))(i) for i in range(3) ] print([ f() for f in fs ]) # => [0, 1, 2] The following is the same as above. I find it preferable. fs = [ (lambda k: (lambda : k))(i) for i in range(3) ] print([ f() for f in fs ]) # => [0, 1, 2] And the following may be even more same as your Ruby thing. fs = list(map(lambda k: (lambda : k), range(3))) print([ f() for f in fs ]) # => [0, 1, 2] So it's not at all like Python can't do this at all. From ned at nedbatchelder.com Sun Mar 27 11:29:54 2016 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sun, 27 Mar 2016 08:29:54 -0700 (PDT) Subject: Why lambda in loop requires default? In-Reply-To: References: Message-ID: <5bd6b719-8b8c-4c1c-8863-0781e2ba3099@googlegroups.com> On Sunday, March 27, 2016 at 9:55:16 AM UTC-4, g vim wrote: > Given that Python, like Ruby, is an object-oriented language It turns out that "object-oriented" means very little, and lots of languages that are object-oriented will behave differently from each other, even where object behavior is concerned. > why doesn't > this: > > def m(): > a = [] > for i in range(3): a.append(lambda: i) > return a > > b = m() > for n in range(3): print(b[n]()) # => 2 2 2 > > ... work the same as this in Ruby: > > def m > a = [] > (0..2).each {|i| a << ->(){i}} > a > end > > aa = m > (0..2).each {|n| puts aa[n].()} # => 0 1 2 > Like Jussi, I don't know Ruby enough to tell you why Ruby *does* work as you want, but I can help explain why Python doesn't work as you want. When you write "lambda: i", you are creating a closure, because i is a name from outside the lambda. In that case, the function you create with the lambda refers to the variable i, not to the value i had when you made the lambda. Later, when you run the function, it will use the current value of the variable i. In this case, you have three functions, all of which refer to the same i, and when you run them all, i is 2, so they all produce 2. > > lambda i=i: i > > ... is needed to make it work in Python. Just wondered why? Here you are using the local i as the default value for the function parameter i. Function parameter defaults are evaluated when the function is defined, and the value is stored as part of the function. So all three of your functions store a different value as the default for i. When the functions are called, they each use their distinct value as the default for the missing argument, and they produce 0, 1, 2. --Ned. From tjreedy at udel.edu Sun Mar 27 11:47:43 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Mar 2016 11:47:43 -0400 Subject: help with program In-Reply-To: References: <1392737302.749065.1459024715818.JavaMail.yahoo.ref@mail.yahoo.com> <1392737302.749065.1459024715818.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 3/27/2016 10:18 AM, Bob Gailer wrote: > The problem with putting input at the end of a program is: if the program > raises an exception you won't see it. What you are saying is that putting input() at the end of a program (or before any exit point) is insufficient for keeping a window alive if the program has a bug that causes an exception. If that is considered possible, wrap the entire code in try-except and print or log the exception before using input to keep the window alive. During development, it is easier to just run the program in a persistent environment, whether console or IDE such as IDLE. -- Terry Jan Reedy From ned at nedbatchelder.com Sun Mar 27 11:48:10 2016 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sun, 27 Mar 2016 08:48:10 -0700 (PDT) Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> Message-ID: <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> On Sunday, March 27, 2016 at 10:43:49 AM UTC-4, BartC wrote: > On 27/03/2016 14:47, Dennis Lee Bieber wrote: > > On Sun, 27 Mar 2016 12:31:26 +0100, BartC declaimed the > > following: > > > >> On 27/03/2016 07:34, Paul Rubin wrote: > >>> BartC writes: > >>>> But my suggestion was to have required a keyword in front of > >>>> such expressions. > >>> > >>> Should there be a keyword in front of a line containing "sqrt(x)" ? > >>> What about "launch(missiles)" ? > >> > >> They both look like function calls. Function calls are *very* commonly > >> used as standalone expressions. > >> > >> You /could/ stipulate that they be written: > >> > >> call launch(missiles) # like Fortran iirc > >> > > Except that FORTRAN also explicitly defines them as > > > > subroutine xxx() > > vs > > return-type function yyy() > > > > and will generate a compile error if you "call" the latter, or put the > > former in-line of an expression > > > > This would be the equivalent of removing "def" from Python, and adding > > two new keywords: "sub" and "fun"; modifying the behavior so that "fun"s > > must have an explicit return statement (preferably with an explicit return > > value), whereas "sub"s have no return and just ... end... > > Well, that could be done in Python (not so usefully because you can't > take account of such info until a call is attempted), but that's not > what I'm talking about, which is simply allowing: > > fn(...) > > whether fn has an explicit return or not, and not allowing: > > fn # and other kinds of expression > > unless some keyword is used. (I've no idea what that might be; all the > best ones are taken. But I've already said a keyword can be emulated via > a dummy function call.) Python *could* have made it an error to have a useless expression as a statement. It would prevent certain kinds of errors. But it would also complicate the language. How do we decide what is a "useless expression"? As we've seen this might be an expression with a side-effect: foo.bar though it would be unusual. Should it be forbidden? And how do we make docstrings, which are simply string literals as statements? Or do we allow those? Perhaps we only allow those if they are the first statement in a module, class, or function? How complicated do we want these criteria to become? One of Guido's principles in designing Python was to keep it simple, even where that might mean people could make errors with it. This part of the language is no different: any expression can be a statement. Any real language is designed with a number of competing factors in mind. It isn't a simple matter. Usually the answer to, "why was it done this way?" is, "Because the designer had a different set of criteria, ordered differently, than you do." Python cares about preventing errors. It also cares about simplicity of design. --Ned. From best_lay at yahoo.com Sun Mar 27 12:07:23 2016 From: best_lay at yahoo.com (Wildman) Date: Sun, 27 Mar 2016 11:07:23 -0500 Subject: Help with python script for NMR References: <89a6c69e-5f60-47d7-99db-4004966fc7c5@googlegroups.com> <5f7ff60d-0297-4bee-b3e4-3af0ca757dfe@googlegroups.com> Message-ID: On Sun, 27 Mar 2016 08:13:49 -0700, mohamadmaaz5 wrote: >> > Hello there, >> > I found a python script The formatting of the script is all wrong. There are many spaces that should not be there and no indentations. It could take a long time to figure it out. It could be just a copy/paste problem on the part of the website. Do you have the link to the original article? -- GNU/Linux user #557453 The cow died so I don't need your bull! From tjreedy at udel.edu Sun Mar 27 12:12:39 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Mar 2016 12:12:39 -0400 Subject: Why lambda in loop requires default? In-Reply-To: <56F73B60.9020603@gmail.com> References: <56F73B60.9020603@gmail.com> Message-ID: On 3/26/2016 9:46 PM, gvim wrote: > Given that Python, like Ruby, is an object-oriented language why doesn't > this: > > def m(): > a = [] > for i in range(3): a.append(lambda: i) > return a > >def echo_i: return i > b = m() > for n in range(3): print(b[n]()) # => 2 2 2 ) # => 2 2 2 > > ... work the same as this in Ruby: > > def m > a = [] > (0..2).each {|i| a << ->(){i}} > a > end > > aa = m > (0..2).each {|n| puts aa[n].()} # => 0 1 2 Since Python came first, and Ruby was partly inspired by and derived from Python, perhaps you should ask Ruby folk why it does not work the same as Python. (Because Matz wanted it different.) > lambda i=i: i > > ... is needed to make it work in Python. Just wondered why? Your Python def m is essentially equivalent to def m(): def echo_i(): return i i = 2 return [echo_i]*3 -- Terry Jan Reedy From mohamadmaaz5 at gmail.com Sun Mar 27 12:15:39 2016 From: mohamadmaaz5 at gmail.com (mohamadmaaz5 at gmail.com) Date: Sun, 27 Mar 2016 09:15:39 -0700 (PDT) Subject: Help with python script for NMR In-Reply-To: References: <89a6c69e-5f60-47d7-99db-4004966fc7c5@googlegroups.com> <5f7ff60d-0297-4bee-b3e4-3af0ca757dfe@googlegroups.com> Message-ID: On Sunday, March 27, 2016 at 6:07:43 PM UTC+2, Wildman wrote: > On Sun, 27 Mar 2016 08:13:49 -0700, mohamadmaaz5 wrote: > > >> > Hello there, > >> > I found a python script > > The formatting of the script is all wrong. There are many > spaces that should not be there and no indentations. It > could take a long time to figure it out. It could be just > a copy/paste problem on the part of the website. Do you > have the link to the original article? > > -- > GNU/Linux user #557453 > The cow died so I don't need your bull! yeah this is exactly the problem, and i eliminated the spaces but still failed. this is the article (script in supporting info): http://www.sciencedirect.com/science/article/pii/S1090780711002072 From best_lay at yahoo.com Sun Mar 27 12:27:44 2016 From: best_lay at yahoo.com (Wildman) Date: Sun, 27 Mar 2016 11:27:44 -0500 Subject: Help with python script for NMR References: <89a6c69e-5f60-47d7-99db-4004966fc7c5@googlegroups.com> <5f7ff60d-0297-4bee-b3e4-3af0ca757dfe@googlegroups.com> Message-ID: <3oWdnRJsGbqdl2XLnZ2dnUU7-eWdnZ2d@giganews.com> On Sun, 27 Mar 2016 09:15:39 -0700, mohamadmaaz5 wrote: > On Sunday, March 27, 2016 at 6:07:43 PM UTC+2, Wildman wrote: >> On Sun, 27 Mar 2016 08:13:49 -0700, mohamadmaaz5 wrote: >> >> >> > Hello there, >> >> > I found a python script >> >> The formatting of the script is all wrong. There are many >> spaces that should not be there and no indentations. It >> could take a long time to figure it out. It could be just >> a copy/paste problem on the part of the website. Do you >> have the link to the original article? >> >> -- >> GNU/Linux user #557453 >> The cow died so I don't need your bull! > > yeah this is exactly the problem, and i eliminated the spaces but still failed. this is the article (script in supporting info): > http://www.sciencedirect.com/science/article/pii/S1090780711002072 I am not finding a link to the script. The website says that I have "Guest" access. Does this mean I have to pay to see the script? -- GNU/Linux user #557453 The cow died so I don't need your bull! From pkpearson at nowhere.invalid Sun Mar 27 12:32:35 2016 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 27 Mar 2016 16:32:35 GMT Subject: Help with python script for NMR References: <89a6c69e-5f60-47d7-99db-4004966fc7c5@googlegroups.com> <5f7ff60d-0297-4bee-b3e4-3af0ca757dfe@googlegroups.com> Message-ID: On Sun, 27 Mar 2016 08:13:49 -0700 (PDT), mohamadmaaz5 at gmail.com wrote: > On Sunday, March 27, 2016 at 4:50:01 PM UTC+2, Joel Goldstick wrote: >> On Sun, Mar 27, 2016 at 10:38 AM, wrote: >> >> > Hello there, >> > I found a python script in a scientific article that enables a simple >> > calculation on an NMR spectrum. >> > I have no experience in programming and i would appreciate it if i can >> > communicate with someone who can write this script and send it to me by >> > mail in py format. It's a short script but i keep making alot of mistaken >> > and it fails every time. >> > Anyone's interested in helping me ? [snip] >> >> copy the code here. You will get help, but people don't generally write >> programs for others here >> >> -- >> Joel Goldstick >> http://joelgoldstick.com/ >> http://cc-baseballstats.info/ > > this is the script. the thing is that i have zero experience in > writing and i cant find the error. all i need is to embed this script > to perfome a relatively simple calculation on a spectra. hope anyone > can help. thanks > > #! /usr /bin/envpython > #encoding:utf- 8 > i m p o r tnmrtec . nmrNotebook . c o n t r o l l e r . C o n t r o [snip] > i m p o r tnmrtec . u t i l as u t i l > i m p o r tnmrtec . nmrNotebook . model . common .nmrCommon as nmrcom > c l a s sBarycentre : > """ > computesthebarycenterofeach > definedr e c t a n g l eanddeducesthe > p o l y d i s p e r s i t yindexofthes o l u t i o n [snip] It appears that spaces have been inserted and deleted at many points in this code, and anybody deciding to help with your project will start with the task of guessing where spaces need to be inserted and deleted in order to restore the original code. Since indentation is important in Python, this will not be a trivial problem. If the scientific article that presented this script shows correct spacing, you should take your best shot at correcting the spacing. Also, it appears that several lines begin "import nmrtec", indicating that this script requires a module named nmrtec. -- To email me, substitute nowhere->runbox, invalid->com. From tjreedy at udel.edu Sun Mar 27 12:39:30 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Mar 2016 12:39:30 -0400 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> Message-ID: On 3/27/2016 11:48 AM, Ned Batchelder wrote: > On Sunday, March 27, 2016 at 10:43:49 AM UTC-4, BartC wrote: >> whether fn has an explicit return or not, and not allowing: >> >> fn # and other kinds of expression >> >> unless some keyword is used. > > Python *could* have made it an error to have a useless expression as a > statement. In interactive mode, which is an essential part of Python, expression statements print the value of the expression. Thus no expression is useless. So Bart is proposing to either disable an extremely useful feature or split Python into two slightly different dialects. I think both are bad ideas. -- Terry Jan Reedy From mohamadmaaz5 at gmail.com Sun Mar 27 12:40:57 2016 From: mohamadmaaz5 at gmail.com (mohamadmaaz5 at gmail.com) Date: Sun, 27 Mar 2016 09:40:57 -0700 (PDT) Subject: Help with python script for NMR In-Reply-To: <3oWdnRJsGbqdl2XLnZ2dnUU7-eWdnZ2d@giganews.com> References: <89a6c69e-5f60-47d7-99db-4004966fc7c5@googlegroups.com> <5f7ff60d-0297-4bee-b3e4-3af0ca757dfe@googlegroups.com> <3oWdnRJsGbqdl2XLnZ2dnUU7-eWdnZ2d@giganews.com> Message-ID: On Sunday, March 27, 2016 at 6:27:59 PM UTC+2, Wildman wrote: > On Sun, 27 Mar 2016 09:15:39 -0700, mohamadmaaz5 wrote: > > > On Sunday, March 27, 2016 at 6:07:43 PM UTC+2, Wildman wrote: > >> On Sun, 27 Mar 2016 08:13:49 -0700, mohamadmaaz5 wrote: > >> > >> >> > Hello there, > >> >> > I found a python script > >> > >> The formatting of the script is all wrong. There are many > >> spaces that should not be there and no indentations. It > >> could take a long time to figure it out. It could be just > >> a copy/paste problem on the part of the website. Do you > >> have the link to the original article? > >> > >> -- > >> GNU/Linux user #557453 > >> The cow died so I don't need your bull! > > > > yeah this is exactly the problem, and i eliminated the spaces but still failed. this is the article (script in supporting info): > > http://www.sciencedirect.com/science/article/pii/S1090780711002072 > > I am not finding a link to the script. The website says that I > have "Guest" access. Does this mean I have to pay to see the > script? > > -- > GNU/Linux user #557453 > The cow died so I don't need your bull! can you please give me your email to send you the article ? From bc at freeuk.com Sun Mar 27 12:58:06 2016 From: bc at freeuk.com (BartC) Date: Sun, 27 Mar 2016 17:58:06 +0100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> Message-ID: On 27/03/2016 16:48, Ned Batchelder wrote: > On Sunday, March 27, 2016 at 10:43:49 AM UTC-4, BartC wrote: >> On 27/03/2016 14:47, Dennis Lee Bieber wrote: >> Well, that could be done in Python (not so usefully because you can't >> take account of such info until a call is attempted), but that's not >> what I'm talking about, which is simply allowing: >> >> fn(...) >> >> whether fn has an explicit return or not, and not allowing: >> >> fn # and other kinds of expression >> >> unless some keyword is used. (I've no idea what that might be; all the >> best ones are taken. But I've already said a keyword can be emulated via >> a dummy function call.) > > Python *could* have made it an error to have a useless expression as a > statement. It would prevent certain kinds of errors. But it would also > complicate the language. How do we decide what is a "useless expression"? Probably one that would raise eyebrows when used as an expression. Such as 'f()+1', even though f() might have useful side-effects. > As we've seen this might be an expression with a side-effect: > > foo.bar > > though it would be unusual. Should it be forbidden? No. The language can require a prefix, or the coder can put it into a legal form (pass it to a dummy function for example). > And how do we make docstrings, which are simply string literals as > statements? Or do we allow those? Perhaps we only allow those if they > are the first statement in a module, class, or function? How complicated > do we want these criteria to become? There would be a list of expression terms that can also form independent statements. Not knowing Python, the list would comprise function calls (ie. the function call is top node in the AST of the expression), and docstrings. (In other languages it might also include assignments and increments.) The suggestion has also been made only bare names should be disallowed, which would probably trap most of the errors it causes, early on. > One of Guido's principles in designing Python was to keep it simple, > even where that might mean people could make errors with it. This part > of the language is no different: any expression can be a statement. Yeah, but even simpler would be that any statement can also be an expression! He didn't go that far though. -- Bartc From best_lay at yahoo.com Sun Mar 27 13:07:19 2016 From: best_lay at yahoo.com (Wildman) Date: Sun, 27 Mar 2016 12:07:19 -0500 Subject: Help with python script for NMR References: <89a6c69e-5f60-47d7-99db-4004966fc7c5@googlegroups.com> <5f7ff60d-0297-4bee-b3e4-3af0ca757dfe@googlegroups.com> <3oWdnRJsGbqdl2XLnZ2dnUU7-eWdnZ2d@giganews.com> Message-ID: On Sun, 27 Mar 2016 09:40:57 -0700, mohamadmaaz5 wrote: > On Sunday, March 27, 2016 at 6:27:59 PM UTC+2, Wildman wrote: >> On Sun, 27 Mar 2016 09:15:39 -0700, mohamadmaaz5 wrote: >> >> > On Sunday, March 27, 2016 at 6:07:43 PM UTC+2, Wildman wrote: >> >> On Sun, 27 Mar 2016 08:13:49 -0700, mohamadmaaz5 wrote: >> >> >> >> >> > Hello there, >> >> >> > I found a python script >> >> >> >> The formatting of the script is all wrong. There are many >> >> spaces that should not be there and no indentations. It >> >> could take a long time to figure it out. It could be just >> >> a copy/paste problem on the part of the website. Do you >> >> have the link to the original article? >> >> >> >> -- >> >> GNU/Linux user #557453 >> >> The cow died so I don't need your bull! >> > >> > yeah this is exactly the problem, and i eliminated the spaces but still failed. this is the article (script in supporting info): >> > http://www.sciencedirect.com/science/article/pii/S1090780711002072 >> >> I am not finding a link to the script. The website says that I >> have "Guest" access. Does this mean I have to pay to see the >> script? >> >> -- >> GNU/Linux user #557453 >> The cow died so I don't need your bull! > > can you please give me your email to send you the article ? The email address in my header is valid. -- GNU/Linux user #557453 The cow died so I don't need your bull! From ned at nedbatchelder.com Sun Mar 27 13:19:44 2016 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sun, 27 Mar 2016 10:19:44 -0700 (PDT) Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> Message-ID: <38a7607d-cbd5-4f70-bfd2-49b2bb3ecc1e@googlegroups.com> On Sunday, March 27, 2016 at 12:58:23 PM UTC-4, BartC wrote: > On 27/03/2016 16:48, Ned Batchelder wrote: > > On Sunday, March 27, 2016 at 10:43:49 AM UTC-4, BartC wrote: > >> On 27/03/2016 14:47, Dennis Lee Bieber wrote: > > >> Well, that could be done in Python (not so usefully because you can't > >> take account of such info until a call is attempted), but that's not > >> what I'm talking about, which is simply allowing: > >> > >> fn(...) > >> > >> whether fn has an explicit return or not, and not allowing: > >> > >> fn # and other kinds of expression > >> > >> unless some keyword is used. (I've no idea what that might be; all the > >> best ones are taken. But I've already said a keyword can be emulated via > >> a dummy function call.) > > > > Python *could* have made it an error to have a useless expression as a > > statement. It would prevent certain kinds of errors. But it would also > > complicate the language. How do we decide what is a "useless expression"? > > Probably one that would raise eyebrows when used as an expression. Such > as 'f()+1', even though f() might have useful side-effects. > > > As we've seen this might be an expression with a side-effect: > > > > foo.bar > > > > though it would be unusual. Should it be forbidden? > > No. The language can require a prefix, or the coder can put it into a > legal form (pass it to a dummy function for example). Yes, I misspoke, by "forbidden" of course I meant, "forbidden as statement on its own," which is what we are talking about. > > > And how do we make docstrings, which are simply string literals as > > statements? Or do we allow those? Perhaps we only allow those if they > > are the first statement in a module, class, or function? How complicated > > do we want these criteria to become? > > There would be a list of expression terms that can also form independent > statements. Not knowing Python, the list would comprise function calls > (ie. the function call is top node in the AST of the expression), and > docstrings. It's a little frustrating to discuss language design when you claim not to know Python. Perhaps you could devote some off-list time to learning it? :) > The suggestion has also been made only bare names should be disallowed, > which would probably trap most of the errors it causes, early on. As Terry pointed out, the interactive interpreter would then need different rules, since of course using bare names there is essential. The interactive interpreter is already a bit different, but you can see this is starting to snowball. > > > One of Guido's principles in designing Python was to keep it simple, > > even where that might mean people could make errors with it. This part > > of the language is no different: any expression can be a statement. > > Yeah, but even simpler would be that any statement can also be an > expression! He didn't go that far though. Nope, he didn't. As I said, it's a complex set of design considerations. No single factor is going to be pushed to the maximum. I'm not sure what point you are making. --Ned. From __peter__ at web.de Sun Mar 27 13:39:30 2016 From: __peter__ at web.de (Peter Otten) Date: Sun, 27 Mar 2016 19:39:30 +0200 Subject: Help with python script for NMR References: <89a6c69e-5f60-47d7-99db-4004966fc7c5@googlegroups.com> <5f7ff60d-0297-4bee-b3e4-3af0ca757dfe@googlegroups.com> Message-ID: mohamadmaaz5 at gmail.com wrote: > On Sunday, March 27, 2016 at 4:50:01 PM UTC+2, Joel Goldstick wrote: >> On Sun, Mar 27, 2016 at 10:38 AM, wrote: >> >> > Hello there, >> > I found a python script in a scientific article that enables a simple >> > calculation on an NMR spectrum. >> > I have no experience in programming and i would appreciate it if i can >> > communicate with someone who can write this script and send it to me by >> > mail in py format. It's a short script but i keep making alot of >> > mistaken and it fails every time. >> > Anyone's interested in helping me ? >> > Thanks >> > -- >> > https://mail.python.org/mailman/listinfo/python-list >> > >> >> copy the code here. You will get help, but people don't generally write >> programs for others here >> >> -- >> Joel Goldstick >> http://joelgoldstick.com/ >> http://cc-baseballstats.info/ > > this is the script. the thing is that i have zero experience in writing > and i cant find the error. all i need is to embed this script to perfome a > relatively simple calculation on a spectra. hope anyone can help. thanks > > #! /usr /bin/envpython > #encoding:utf- 8 > i m p o r tnmrtec . nmrNotebook . c o n t r o l l e r . C o n t r o l l e > r as Cont i m p o r tnmrtec . u t i l as u t i l > i m p o r tnmrtec . nmrNotebook . model . common .nmrCommon as nmrcom > c l a s sBarycentre : If you want to turn Annex B of www.theses.fr/2014STRAJ015.pdf into runnable Python please note """ Created by Marie?Aude Coutouly , Justine Vieville, Matthieu ... ...Tanty and Marc?Andre Delsuc on 2010?11?04 Copyright ( c ) 2010 NMRTEC and IGBMC. All rights Reserved . """" If you didn't already contact the author(s) you should try that first -- perhaps they can provide a copy of the original script. From mail.python.org at marco.sulla.e4ward.com Sun Mar 27 14:01:27 2016 From: mail.python.org at marco.sulla.e4ward.com (Marco S.) Date: Sun, 27 Mar 2016 20:01:27 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > The point you might have missed is that treating lists as if they were > mappings violates at least one critical property of mappings: that the > relationship between keys and values are stable. This is true for immutable maps, but for mutable ones, you can simply do map[key] = new_value You can easily create a new class that extend dict and add to it a method that emulated the insert method of lists. It will definitively not break any contract, if your contract is "sequences are maps with ordered integer keys that starts from zero and have no gaps". Mark Lawrence wrote: > I cannot see this happening unless you provide a patch on the bug > tracker. However I suspect you can get the same thing by subclassing > dict. Why don't you try it and let us know how you get on? The problem with a vdict is that I should also create by zero a new interface (ABC), since MutableMapping have an incompatible contract. And to be much more useful I should code it inc C, and my C skills are not so magnificent. Furthermore I would try to create a new sequence interface that inherit from the vdict interface. More briefly, I need much free time. But I suppose I can start with something quick and dirty. From mohamadmaaz5 at gmail.com Sun Mar 27 14:58:29 2016 From: mohamadmaaz5 at gmail.com (mohamadmaaz5 at gmail.com) Date: Sun, 27 Mar 2016 11:58:29 -0700 (PDT) Subject: Help with python script for NMR In-Reply-To: References: <89a6c69e-5f60-47d7-99db-4004966fc7c5@googlegroups.com> <5f7ff60d-0297-4bee-b3e4-3af0ca757dfe@googlegroups.com> Message-ID: <5a9af45e-c8f7-42f1-add5-0f795e7e102a@googlegroups.com> On Sunday, March 27, 2016 at 7:40:06 PM UTC+2, Peter Otten wrote: > mohamadmaaz5 at gmail.com wrote: > > > On Sunday, March 27, 2016 at 4:50:01 PM UTC+2, Joel Goldstick wrote: > >> On Sun, Mar 27, 2016 at 10:38 AM, wrote: > >> > >> > Hello there, > >> > I found a python script in a scientific article that enables a simple > >> > calculation on an NMR spectrum. > >> > I have no experience in programming and i would appreciate it if i can > >> > communicate with someone who can write this script and send it to me by > >> > mail in py format. It's a short script but i keep making alot of > >> > mistaken and it fails every time. > >> > Anyone's interested in helping me ? > >> > Thanks > >> > -- > >> > https://mail.python.org/mailman/listinfo/python-list > >> > > >> > >> copy the code here. You will get help, but people don't generally write > >> programs for others here > >> > >> -- > >> Joel Goldstick > >> http://joelgoldstick.com/ > >> http://cc-baseballstats.info/ > > > > this is the script. the thing is that i have zero experience in writing > > and i cant find the error. all i need is to embed this script to perfome a > > relatively simple calculation on a spectra. hope anyone can help. thanks > > > > #! /usr /bin/envpython > > #encoding:utf- 8 > > i m p o r tnmrtec . nmrNotebook . c o n t r o l l e r . C o n t r o l l e > > r as Cont i m p o r tnmrtec . u t i l as u t i l > > i m p o r tnmrtec . nmrNotebook . model . common .nmrCommon as nmrcom > > c l a s sBarycentre : > > If you want to turn Annex B of www.theses.fr/2014STRAJ015.pdf into runnable > Python please note > > """ > Created by Marie-Aude Coutouly , Justine Vieville, Matthieu ... > ...Tanty and Marc-Andre Delsuc on 2010-11-04 > Copyright ( c ) 2010 NMRTEC and IGBMC. All rights Reserved . > """" > > If you didn't already contact the author(s) you should try that first -- > perhaps they can provide a copy of the original script. already sent a request and waiting, thank you From breamoreboy at yahoo.co.uk Sun Mar 27 15:24:18 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 27 Mar 2016 20:24:18 +0100 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: Message-ID: On 27/03/2016 19:01, Marco S. via Python-list wrote: > > Mark Lawrence wrote: > >> I cannot see this happening unless you provide a patch on the bug >> tracker. However I suspect you can get the same thing by subclassing >> dict. Why don't you try it and let us know how you get on? > > The problem with a vdict is that I should also create by zero a new > interface (ABC), since MutableMapping have an incompatible contract. > And to be much more useful I should code it inc C, and my C skills are > not so magnificent. Furthermore I would try to create a new sequence > interface that inherit from the vdict interface. More briefly, I need > much free time. But I suppose I can start with something quick and > dirty. > Why do you need a new interace if all you're trying to do is create a vdict class that has "iter(d) == iter(d.values()), and should also have a count() method, like sequence types"? I don't understand why you think you need C skills. E.g. SortedContainers https://pypi.python.org/pypi/sortedcontainers "is an Apache2 licensed containers library, written in pure-Python, and fast as C-extensions." I think your quick and dirty might well turn into something useful for your application. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From rriehle at itu.edu Sun Mar 27 15:38:16 2016 From: rriehle at itu.edu (Richard Riehle) Date: Sun, 27 Mar 2016 12:38:16 -0700 (PDT) Subject: List of Functions Message-ID: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> Several months ago, I posted a question regarding how to create a list of functions. I quickly solved the problem on my own, but I am just now getting around to sharing my solution. It was actually quite simple, and also quite useful for the problem I had at hand. Below is an example of one way to do this. There are actually some other solutions. This solution is based on the fact that Python functions are first-class objects, and therefore enable one to emulate functional programming. Consider that we might need a list of buttons, each of which can behave differently based on a parameter list. First, we define three button functions with a parameter. Then, we create a list of those functions. The tricky part is how we formulate the actual function call. I demonstrate this in the last two lines of the code below. I realize that this seems trivial to many experience Pythonistas. But it might prove useful for those who are relative newcomers to the language. In any case, I hope someone can find it helpful. >>> def button1(number): print ('button1 = ', number) ## define the buttons >>> def button2(number): print ('button2 = ', number) >>> def button3(number): print ('button3 = ', number) >>> buttonList = [button1, button2, button3] ## create the list >>> >>> buttonList [1] (25) ## using positional association button2 = 25 >>>buttonList [0] (number = 78) ## using named association button1 = 78 From ben.usenet at bsb.me.uk Sun Mar 27 16:06:01 2016 From: ben.usenet at bsb.me.uk (Ben Bacarisse) Date: Sun, 27 Mar 2016 21:06:01 +0100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87twjs5tz2.fsf@nightsong.com> <56f78e74$0$1616$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87zitj1yae.fsf@bsb.me.uk> Steven D'Aprano writes: > On Sun, 27 Mar 2016 05:13 pm, Paul Rubin wrote: > >> Steven D'Aprano writes: >>> For example, would you consider that this isolated C code is >>> "meaningless"? >>> int i = n + 1; >> >> It's meaningful as long as n is in a certain range of values so there's >> no overflow. >> >>> But according to the standard, it's "meaningless", since it might >>> overflow, and signed int overflow is Undefined Behaviour. >> >> No it's not meaningless if it "might" overflow, it's meaningless if it >> -does- overflow, > > No! That's exactly wrong! > > Paul, thank you for inadvertently proving the point I am trying to get > across. People, even experienced C coders, simply don't understand what the > C standard says and what C compilers can and will do. > > If the C compiler cannot prove that n is strictly less than MAXINT (or is > that spelled INT_MAX?), (the latter) > the *entire program* (or at least the bits reachable from this line, > in both directions) is Undefined, and the compiler has no obligations > at all. If I understand you correctly, you are claiming that in this program #include int main(int argc, char **argv) { int n = argc > 1 ? atoi(argv[1]) : 0; int i = n + 1; // not needed but used because it's the line in question printf("Hello world\n"); } everything after "int i = n + 1;" is undefined because the compiler can't prove that n is strictly less than INT_MAX. (In fact atoi exhibits undefined behaviour in some cases which the compiler can't prove don't apply here either, so the trouble could happen even earlier.) Given that the only observable behaviour is the printf call, would the fact that the program is undefined by that point mean that a compiler could generate code equivalent to #include int main(void) { puts("You loose!\n"); } and still be conforming according to the language standard? (Obviously this is a rather mild option given that anything is permitted.) That *seems* to be what you are saying, but it's not backed up by what the C people I know say. In particular > But don't believe me. What do I know about C, I don't even know whether to > spell the biggest int MAXINT or INT_MAX or MAX_INT. Instead, believe these > guys: > > http://blog.regehr.org/archives/213 > http://blog.regehr.org/archives/226 > http://blog.regehr.org/archives/232 > > http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html > http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html > http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_21.html don't seem to be saying that. Whilst I've not yet read them all, they seem be unexceptional explanations of UB in C (by which I mean they accord with what I understand it to be!) and I don't see how they confirm what I think you are saying. -- Ben. From bc at freeuk.com Sun Mar 27 16:18:58 2016 From: bc at freeuk.com (BartC) Date: Sun, 27 Mar 2016 21:18:58 +0100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <38a7607d-cbd5-4f70-bfd2-49b2bb3ecc1e@googlegroups.com> References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <38a7607d-cbd5-4f70-bfd2-49b2bb3ecc1e@googlegroups.com> Message-ID: On 27/03/2016 18:19, Ned Batchelder wrote: > On Sunday, March 27, 2016 at 12:58:23 PM UTC-4, BartC wrote: >> There would be a list of expression terms that can also form independent >> statements. Not knowing Python, the list would comprise function calls >> (ie. the function call is top node in the AST of the expression), and >> docstrings. > > It's a little frustrating to discuss language design when you claim not to > know Python. Perhaps you could devote some off-list time to learning it? :) Since the language is presumably available to anyone including non-experts, why shouldn't someone who is only going to use a subset, have an opinion on a troublesome part of the language? >>> One of Guido's principles in designing Python was to keep it simple, For a simple language, there appear to be quite a few esoteric uses being thought up for that feature! -- Bartc From python.list at tim.thechases.com Sun Mar 27 16:32:36 2016 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 27 Mar 2016 15:32:36 -0500 Subject: How to make Python interpreter a little more strict? In-Reply-To: <56f7536b$0$22140$c3e8da3$5496439d@news.astraweb.com> References: <20160325150608.21c3827a@fujitsu> <56f7536b$0$22140$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20160327153236.6c70fb76@bigbox.christie.dr> On 2016-03-27 14:28, Steven D'Aprano wrote: > > So intrigued by this question I tried the following > > def fnc( n ): > > print "fnc called with parameter '%d'" % n > > return n > > > > for i in range(0,5): > > if i%2 == 0: > > fnc > > next > > print i > > > > and got the same result as the OP > > In this case, the two lines "fnc" and "next" simply look up the > function names, but without actually calling them. They're not > quite "no-ops", since they can fail and raise NameError if the name > doesn't exist, but otherwise they might as well be no-ops. Which is actually useful. I've got some 2.4 code that reads try: any except NameError: def any(...): ... (with a similar block for all() ) I don't want to call any() or all(), I simply want to test whether they exist. -tkc From bc at freeuk.com Sun Mar 27 16:49:20 2016 From: bc at freeuk.com (BartC) Date: Sun, 27 Mar 2016 21:49:20 +0100 Subject: How to make Python interpreter a little more strict? In-Reply-To: References: <20160325150608.21c3827a@fujitsu> <56f7536b$0$22140$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 27/03/2016 21:32, Tim Chase wrote: > On 2016-03-27 14:28, Steven D'Aprano wrote: >> In this case, the two lines "fnc" and "next" simply look up the >> function names, but without actually calling them. They're not >> quite "no-ops", since they can fail and raise NameError if the name >> doesn't exist, but otherwise they might as well be no-ops. > > Which is actually useful. I've got some 2.4 code that reads > > try: > any > except NameError: > def any(...): > ... > > (with a similar block for all() ) > > I don't want to call any() or all(), I simply want to test whether > they exist. But would it have been much of an imposition to have typed: try: test = any except NameError: def any(...): ... ? (Or any of the half dozen ways there must be to test the existence of a name.) -- Bartc From rosuav at gmail.com Sun Mar 27 16:59:32 2016 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 28 Mar 2016 07:59:32 +1100 Subject: How to make Python interpreter a little more strict? In-Reply-To: References: <20160325150608.21c3827a@fujitsu> <56f7536b$0$22140$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Mar 28, 2016 at 7:49 AM, BartC wrote: > On 27/03/2016 21:32, Tim Chase wrote: >> >> On 2016-03-27 14:28, Steven D'Aprano wrote: > > >>> In this case, the two lines "fnc" and "next" simply look up the >>> function names, but without actually calling them. They're not >>> quite "no-ops", since they can fail and raise NameError if the name >>> doesn't exist, but otherwise they might as well be no-ops. >> >> >> Which is actually useful. I've got some 2.4 code that reads >> >> try: >> any >> except NameError: >> def any(...): >> ... >> >> (with a similar block for all() ) >> >> I don't want to call any() or all(), I simply want to test whether >> they exist. > > > But would it have been much of an imposition to have typed: > > try: > test = any > except NameError: > def any(...): > ... > > ? (Or any of the half dozen ways there must be to test the existence of a > name.) It shifts the uselessness to "why did you assign to that name?". While that's not too bad (and nothing like as bad as a dummy function call), it's generally reserved for the places where Python syntax mandates an assignment: for _ in range(4): next(iter) # discard the headers If you're building a linter, I would expect "name assigned to and never used" to be its own warning; but also, the try/except block hints that this isn't useless. Generally, "dummy expressions" like this are going to explicitly catch at least one exception that can be raised only in that expression (ie a really small try block). That pretty much counts as your language-level marker for conscious dummy expression usage. ChrisA From oscar.j.benjamin at gmail.com Sun Mar 27 17:16:40 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 27 Mar 2016 22:16:40 +0100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <87zitj1yae.fsf@bsb.me.uk> References: <56ef9787$0$1516$c3e8da3$5496439d@news.astraweb.com> <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87twjs5tz2.fsf@nightsong.com> <56f78e74$0$1616$c3e8da3$5496439d@news.astraweb.com> <87zitj1yae.fsf@bsb.me.uk> Message-ID: On 27 Mar 2016 23:11, "Ben Bacarisse" wrote: > > Steven D'Aprano writes: > > > On Sun, 27 Mar 2016 05:13 pm, Paul Rubin wrote: > > > >> Steven D'Aprano writes: > >>> For example, would you consider that this isolated C code is > >>> "meaningless"? > >>> int i = n + 1; > >> > >> It's meaningful as long as n is in a certain range of values so there's > >> no overflow. > >> > >>> But according to the standard, it's "meaningless", since it might > >>> overflow, and signed int overflow is Undefined Behaviour. > >> > >> No it's not meaningless if it "might" overflow, it's meaningless if it > >> -does- overflow, > > > > No! That's exactly wrong! > > > > Paul, thank you for inadvertently proving the point I am trying to get > > across. People, even experienced C coders, simply don't understand what the > > C standard says and what C compilers can and will do. > > > > If the C compiler cannot prove that n is strictly less than MAXINT (or is > > that spelled INT_MAX?), > > (the latter) > > > the *entire program* (or at least the bits reachable from this line, > > in both directions) is Undefined, and the compiler has no obligations > > at all. > > If I understand you correctly, you are claiming that in this program > > #include > > int main(int argc, char **argv) > { > int n = argc > 1 ? atoi(argv[1]) : 0; > int i = n + 1; // not needed but used because it's the line in question > printf("Hello world\n"); > } > > everything after "int i = n + 1;" is undefined because the compiler > can't prove that n is strictly less than INT_MAX. Although Steve is incorrect to say that everything is undefined just because the compiler can't prove that n != INT_MAX one thing that he is right about is that undefined behaviour applies to the whole program. So if the n+1 does lead to undefined behaviour (i.e. if n == INT_MAX) then the behaviour is also undefined *before* that line. If we change the line to INT_MAX+1 then a compiler is free to do whatever it likes with the *entire* program. In practice what this means is that an optimising compiler can see n+1 and then optimise using the assumption that n!=INT_MAX (since there are *zero* constraints on the behaviour of the *entire* program if that assumption is broken). This optimisation could for example remove an if(n==INT_MAX) block as dead code even if the check occurs *before* the line that involves n+1 which can be surprising. Of course if the check is used to conditionally execute n+1 then the assumption cannot be applied by the optimiser so it's still entirely possible to avoid this particular undefined behaviour. -- Oscar From ned at nedbatchelder.com Sun Mar 27 17:55:52 2016 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sun, 27 Mar 2016 14:55:52 -0700 (PDT) Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <38a7607d-cbd5-4f70-bfd2-49b2bb3ecc1e@googlegroups.com> Message-ID: <7461be36-370e-4ccb-8fea-433f03097ca9@googlegroups.com> On Sunday, March 27, 2016 at 4:19:12 PM UTC-4, BartC wrote: > On 27/03/2016 18:19, Ned Batchelder wrote: > > On Sunday, March 27, 2016 at 12:58:23 PM UTC-4, BartC wrote: > > >> There would be a list of expression terms that can also form independent > >> statements. Not knowing Python, the list would comprise function calls > >> (ie. the function call is top node in the AST of the expression), and > >> docstrings. > > > > It's a little frustrating to discuss language design when you claim not to > > know Python. Perhaps you could devote some off-list time to learning it? :) > > Since the language is presumably available to anyone including > non-experts, why shouldn't someone who is only going to use a subset, > have an opinion on a troublesome part of the language? It will be a partly-informed opinion. If you are OK with that, I guess I will have to be also. > >>> One of Guido's principles in designing Python was to keep it simple, > > For a simple language, there appear to be quite a few esoteric uses > being thought up for that feature! Yes, it's impressive the things a simple design can accomplish. In the end, I'm not sure what the goal of this discussion is. We've discussed something you don't like about Python. We've explained as best we can why the language is the way it is. You still think it's a deficiency. What now? --Ned. From bc at freeuk.com Sun Mar 27 18:11:06 2016 From: bc at freeuk.com (BartC) Date: Sun, 27 Mar 2016 23:11:06 +0100 Subject: Undefined behaviour in C [was Re: The Cost of Dynamism] In-Reply-To: <7461be36-370e-4ccb-8fea-433f03097ca9@googlegroups.com> References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <38a7607d-cbd5-4f70-bfd2-49b2bb3ecc1e@googlegroups.com> <7461be36-370e-4ccb-8fea-433f03097ca9@googlegroups.com> Message-ID: On 27/03/2016 22:55, Ned Batchelder wrote: > On Sunday, March 27, 2016 at 4:19:12 PM UTC-4, BartC wrote: >> On 27/03/2016 18:19, Ned Batchelder wrote: >>> On Sunday, March 27, 2016 at 12:58:23 PM UTC-4, BartC wrote: >> >>>> There would be a list of expression terms that can also form independent >>>> statements. Not knowing Python, the list would comprise function calls >>>> (ie. the function call is top node in the AST of the expression), and >>>> docstrings. >>> >>> It's a little frustrating to discuss language design when you claim not to >>> know Python. Perhaps you could devote some off-list time to learning it? :) >> >> Since the language is presumably available to anyone including >> non-experts, why shouldn't someone who is only going to use a subset, >> have an opinion on a troublesome part of the language? > > It will be a partly-informed opinion. If you are OK with that, I guess > I will have to be also. > >>>>> One of Guido's principles in designing Python was to keep it simple, >> >> For a simple language, there appear to be quite a few esoteric uses >> being thought up for that feature! > > Yes, it's impressive the things a simple design can accomplish. > > In the end, I'm not sure what the goal of this discussion is. We've > discussed something you don't like about Python. We've explained as best > we can why the language is the way it is. You still think it's a > deficiency. What now? Stalemate I guess. Actually I'm not that bothered by this, but as someone else brought it up, I just wondered why Python was doing the same as C in allowing arbitrary expressions to be evaluated for no apparent reason. Now I know. -- Bartc From python at lucidity.plus.com Sun Mar 27 19:10:01 2016 From: python at lucidity.plus.com (Erik) Date: Mon, 28 Mar 2016 00:10:01 +0100 Subject: List of Functions In-Reply-To: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> Message-ID: <56F86849.4030109@lucidity.plus.com> Hi Richard, On 27/03/16 20:38, Richard Riehle wrote: > I realize that this seems trivial to many experience Pythonistas. But it might prove useful for those who are relative newcomers Thanks for sharing your solution (people finding the original question because it happens to match their own may then find this follow-up). However, please also read PEP8 - https://www.python.org/dev/peps/pep-0008/ >>>> def button1(number): > print ('button1 = ', number) ## define the buttons >>>> def button2(number): > print ('button2 = ', number) >>>> def button3(number): > print ('button3 = ', number) >>>> buttonList = [button1, button2, button3] ## create the list >>>> >>>> buttonList [1] (25) ## using positional association > button2 = 25 >>>> buttonList [0] (number = 78) ## using named association > button1 = 78 > The whitespace before the [] and () is what I'm referring you to PEP8 about. Of course, you can do what you want - this is just a friendly nudge ;) That extra whitespace does make it a bit harder to grok if you're used to reading "typical" Python code. BR, E. From nobody at nowhere.invalid Sun Mar 27 19:26:30 2016 From: nobody at nowhere.invalid (Nobody) Date: Mon, 28 Mar 2016 00:26:30 +0100 Subject: How to make Python interpreter a little more strict? References: <20160325150608.21c3827a@fujitsu> Message-ID: On Sat, 26 Mar 2016 23:30:30 +0000, John Pote wrote: > So I have sympathy with the OP, I would expect the compiler to pick this > up Why? The code is valid, the compiler knows how to generate the appropriate bytecode for it. The compiler isn't "lint". Reporting code which is actually invalid is fairly straightforward. When the parser attempts to match the next token against a parse rule and finds that nothing matches (e.g. the "fnc next" example), it just needs to raise a SyntaxError. The point at which the exception needs to be raised naturally exists in the code. But to identify code which is perfectly valid yet is "probably" a mistake first requires someone to identify such cases, then someone needs to start adding the appropriate tests to the compiler to distinguish such code from the rest. > It would be all to easy to write a series of lines just calling > functions and forget the () on one of them. Not fun programming. It's > also a good reminder that the meaning of a keyword in language A is not > necessarily the same in language B (ie 'next', Python) "next" isn't a keyword, it's a built-in function. It's perfectly valid to re-use that name for your own variables or functions. > So on this last point is this behaviour of Python defined somewhere in > the docs? What behaviour? Evaluating a name? From hongyi.zhao at gmail.com Sun Mar 27 19:40:31 2016 From: hongyi.zhao at gmail.com (Hongyi Zhao) Date: Sun, 27 Mar 2016 23:40:31 +0000 (UTC) Subject: Calling the source command from subprocess.popen to update the os.environ. References: Message-ID: On Sun, 27 Mar 2016 13:24:05 +0000, Hongyi Zhao wrote: > # replace env > os.environ.clear() I find another method which can solve this issue, ie., changing the above code into the follows: # ref : http://unix.stackexchange.com/questions/178522/unsetting- environment-variable-with-an-empty-name if "" in os.environ.data: del os.environ.data[""] os.environ.clear() Regards -- .: Hongyi Zhao [ hongyi.zhao AT gmail.com ] Free as in Freedom :. From ben.usenet at bsb.me.uk Sun Mar 27 20:19:14 2016 From: ben.usenet at bsb.me.uk (Ben Bacarisse) Date: Mon, 28 Mar 2016 01:19:14 +0100 Subject: List of Functions References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> Message-ID: <87bn5z1mkd.fsf@bsb.me.uk> Richard Riehle writes: > Several months ago, I posted a question regarding how to create a list > of functions. > I realize that this seems trivial to many experience Pythonistas. But > it might prove useful for those who are relative newcomers to the > language. In any case, I hope someone can find it helpful. > >>>> def button1(number): > print ('button1 = ', number) ## define the buttons >>>> def button2(number): > print ('button2 = ', number) >>>> def button3(number): > print ('button3 = ', number) >>>> buttonList = [button1, button2, button3] ## create the list >>>> >>>> buttonList [1] (25) ## using positional association > button2 = 25 >>>>buttonList [0] (number = 78) ## using named association > button1 = 78 Anywhere you see a pattern there is the opportunity to make a function that captures the pattern. You could choose to have a button-function making function like this: def makeButton(n): return lambda number: print('button%d = %d' % (n, number)) It's shame that anonymous functions (for that's what's being returned here -- a function with no name) were born of a subject that used arbitrary Greek letters for things. We seem stuck with the mysterious but meaningless "lambda" for a very simple and useful idea. So maybe it's better to do it with a named local function instead: def makeButton(n): def button(number): print('button%d = %d' % (n, number)) return button; And now you can use code to make the list since the button number is now data. buttonList = [makeButton(i) for i in range(1, 3)] -- Ben. From steve at pearwood.info Sun Mar 27 20:20:54 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Mar 2016 11:20:54 +1100 Subject: help with program References: <1392737302.749065.1459024715818.JavaMail.yahoo.ref@mail.yahoo.com> <1392737302.749065.1459024715818.JavaMail.yahoo@mail.yahoo.com> Message-ID: <56f878e8$0$1593$c3e8da3$5496439d@news.astraweb.com> On Mon, 28 Mar 2016 01:18 am, Bob Gailer wrote: > The problem with putting input at the end of a program is: if the program > raises an exception you won't see it. True. But the solution to that is simple: don't make mistakes when programming :-) If you have a better solution, please speak up. I don't know Windows very well and I'm not sure why the console is disappearing in the first place. -- Steven From steve at pearwood.info Sun Mar 27 20:54:16 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Mar 2016 11:54:16 +1100 Subject: Statements as expressions [was Re: Undefined behaviour in C] References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> Message-ID: <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> On Mon, 28 Mar 2016 03:58 am, BartC wrote: >> One of Guido's principles in designing Python was to keep it simple, >> even where that might mean people could make errors with it. This part >> of the language is no different: any expression can be a statement. > > Yeah, but even simpler would be that any statement can also be an > expression! He didn't go that far though. People say that, but I don't believe it. What does it mean to say that any statement could also be an expression? If this statement is an expression: if condition: print(1) print(2) else: print(3) print(4) what value should it return? Justify your choice. What should be the return value of this statement? while True: x += 1 if condition: break I don't think that "every statement is an expression" is conceptually simpler at all. I think it is more difficult to understand. Nearly all human languages make a distinction between things and actions: * expressions return a value, which makes them a thing (noun); * statements do something, which makes them an action (verb). It's easy to understand the concept of an expression where the result is dropped. "Hand me that hammer" and then you just drop the hammer on the floor. It's harder to understand the concept of functions (doing words, verbs) as values. "First class functions" take a bit of mental effort to understand, but the payoff it worth it. But it is even harder to understand what it might mean for a while loop to be a value, and the benefit of doing so seems significantly less than compelling. Maybe it is easier for non-English speakers with quite different linguistic models, but the benefit of adding statements as expressions seems to me to be well less than the extra difficulty it would produce. -- Steven From steve at pearwood.info Sun Mar 27 21:05:46 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Mar 2016 12:05:46 +1100 Subject: Suggestion: make sequence and map interfaces more similar References: Message-ID: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> On Mon, 28 Mar 2016 05:01 am, Marco S. wrote: > Steven D'Aprano wrote: > >> The point you might have missed is that treating lists as if they were >> mappings violates at least one critical property of mappings: that the >> relationship between keys and values are stable. > > > This is true for immutable maps, but for mutable ones, you can simply do No, it is true for mutable maps too. When you add a new key:value to a dict, the other key:value pairs don't change. That is the whole point of a mapping! Of course you can deliberately change the value by re-assignment: map[key] = new_value but that's not what I'm talking about. When you add a NEW key, the OTHER keys DON'T change. That is ABSOLUTELY CRITICAL to a mapping. Anything which lacks that property is not a mapping. The relationship between the index of a value and the value in a sequence is not stable. Inserting a new value can change the "key"(actually index) of some or all of the existing values. The whole point of sequences is that the position of values is NOT stable: they are intended to move around. You can sort them, reverse them, delete them, insert new values, and the others will move around to make room. If you think of the index as a key, this is completely the opposite behaviour of mappings. In a mapping, the key:value is stable, and must not change unless you explicitly change it. In a sequence, the index:value relationship is unstable, and can easily change without notice, due to many different operations: insertion deletion popping a value sorting shuffling reversal of the sequence and probably more. -- Steven From steve at pearwood.info Sun Mar 27 21:24:16 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Mar 2016 12:24:16 +1100 Subject: Useless expressions [was Re: Undefined behaviour in C] References: <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> Message-ID: <56f887c1$0$1598$c3e8da3$5496439d@news.astraweb.com> On Sun, 27 Mar 2016 10:31 pm, BartC wrote: > On 27/03/2016 07:34, Paul Rubin wrote: >> BartC writes: >>> But my suggestion was to have required a keyword in front of >>> such expressions. >> >> Should there be a keyword in front of a line containing "sqrt(x)" ? >> What about "launch(missiles)" ? > > They both look like function calls. Function calls are *very* commonly > used as standalone expressions. > > You /could/ stipulate that they be written: > > call launch(missiles) # like Fortran iirc > > but that wouldn't be popular and is unnecessary. > >> The compiler can't tell which of those expressions has a side effect. >> The first might be buggy code but the second is idiomatic. > > Whether there are side-effects is not quite as important as picking up > things that are likely to be errors: > > f() # Probably OK > g() # Probably OK > f()+g() # Probably not OK You don't and can't know what's "probably not" okay unless you know what type of object both f and g return. Don't think about floats and ints and strings. Think of complex objects with operator overloading. You're probably thinking of `x + y`. Instead, think of things like: graph + node database + table in a procedural style instead of a functional style. With operator overloading, we have the ability to write domain-specific little languages. It's not the compiler's job to cast value judgements on what is good or likely style, it must accept anything legal. If you want something to make value judgements about style, or get warnings about what looks like legal code but might be an error, then you should use a linter like PyChecker, Pylint, Jedi or similar. That's not the compiler's job. > Maybe there is some legitimate, obscure reason for writing the latter, > but stick some indicator in front to tell the language (and whoever > happens to be reading the code) that this is what you intend. In your language, you can make operator overloading illegal if you like, or discourage it by requiring special syntax, but in Python it is a first-class (pun not intended) programming style of equal standing to arithmetic, strings, method calls and modules. -- Steven From steve at pearwood.info Sun Mar 27 21:24:56 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Mar 2016 12:24:56 +1100 Subject: How to make Python interpreter a little more strict? References: <20160325150608.21c3827a@fujitsu> <56f7536b$0$22140$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56f887e8$0$1598$c3e8da3$5496439d@news.astraweb.com> On Mon, 28 Mar 2016 07:49 am, BartC wrote: > On 27/03/2016 21:32, Tim Chase wrote: >> On 2016-03-27 14:28, Steven D'Aprano wrote: > >>> In this case, the two lines "fnc" and "next" simply look up the >>> function names, but without actually calling them. They're not >>> quite "no-ops", since they can fail and raise NameError if the name >>> doesn't exist, but otherwise they might as well be no-ops. >> >> Which is actually useful. I've got some 2.4 code that reads >> >> try: >> any >> except NameError: >> def any(...): >> ... >> >> (with a similar block for all() ) >> >> I don't want to call any() or all(), I simply want to test whether >> they exist. > > But would it have been much of an imposition to have typed: > > try: > test = any > except NameError: > def any(...): > ... > > ? (Or any of the half dozen ways there must be to test the existence of > a name.) No, not much of an imposition. But then you might have your linter (if you bother with one) complaining that you define "test" but never use it. But regardless of whether it is an imposition or not, that's not how we do it. It's a stylistic choice, that's all. We've explained the reasons for it, but it ultimately comes down to a matter of taste. -- Steven From steve at pearwood.info Sun Mar 27 21:26:16 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Mar 2016 12:26:16 +1100 Subject: Useless expressions [was Re: Undefined behaviour in C] References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> Message-ID: <56f88839$0$1598$c3e8da3$5496439d@news.astraweb.com> On Mon, 28 Mar 2016 03:39 am, Terry Reedy wrote: > On 3/27/2016 11:48 AM, Ned Batchelder wrote: >> On Sunday, March 27, 2016 at 10:43:49 AM UTC-4, BartC wrote: > >>> whether fn has an explicit return or not, and not allowing: >>> >>> fn # and other kinds of expression >>> >>> unless some keyword is used. >> >> Python *could* have made it an error to have a useless expression as a >> statement. > > In interactive mode, which is an essential part of Python, expression > statements print the value of the expression. Thus no expression is > useless. > > So Bart is proposing I don't think Bart is intending this as an actual proposal to change Python so much as just a hypothetical to discuss. > to either disable an extremely useful feature or > split Python into two slightly different dialects. I think both are bad > ideas. I don't think that's quite fair. The interactive interpreter is already slightly different from non-interactive use, in that bare expressions print the result, while in non-interactive use they just get garbage collected. It wouldn't be that different to change "print versus ignore" into "print versus raise error". I think it is a bit extreme to call that two different dialects. If so, then the current interactive interpreter is also a different dialect. But that's not what makes this a bad idea. Consider something like file.write. In Python 2, writing to a file behaves like a procedure, and you write: with open(filename) as file: file.write("something") In Python 3, the write method has changed to return the number of characters or bytes actually written. But if you don't need that information, you aren't *forced* to collect it and ignore it. You can just ignore it: with open(filename) as file: file.write("something") is still perfectly legal. But Bart's suggestion would make that an error. No, Bart's suggestion is perfectly reasonable for a linter, but not for Python. Other languages may choose to be more restrictive. Pascal, for example, requires you to declare subroutines as functions or procedures depending on whether or not they return a value, and that's got much to recommend it too. But Python made different choices. -- Steven From rosuav at gmail.com Sun Mar 27 21:38:19 2016 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 28 Mar 2016 12:38:19 +1100 Subject: Useless expressions [was Re: Undefined behaviour in C] In-Reply-To: <56f887c1$0$1598$c3e8da3$5496439d@news.astraweb.com> References: <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <56f887c1$0$1598$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Mar 28, 2016 at 12:24 PM, Steven D'Aprano wrote: >> >> f() # Probably OK >> g() # Probably OK >> f()+g() # Probably not OK > > You don't and can't know what's "probably not" okay unless you know what > type of object both f and g return. > > Don't think about floats and ints and strings. Think of complex objects with > operator overloading. You're probably thinking of `x + y`. Instead, think > of things like: > > graph + node > database + table > > in a procedural style instead of a functional style. With operator > overloading, we have the ability to write domain-specific little languages. I would still look askance at code that adds two things and drops the result, though. The compiler can't discard it, but if a linter complains, I'd support that. A DSL that requires you to do this is, imo, poorly designed. It'll make every subsequent maintainer wonder if the code is buggy or not. But it's still... > ... not the compiler's job to cast value judgements on what is good or > likely style, it must accept anything legal. If you want something to make > value judgements about style, or get warnings about what looks like legal > code but might be an error, then you should use a linter like PyChecker, > Pylint, Jedi or similar. That's not the compiler's job. Exactly. ChrisA From no.email at nospam.invalid Sun Mar 27 21:40:23 2016 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 27 Mar 2016 18:40:23 -0700 Subject: Statements as expressions [was Re: Undefined behaviour in C] References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87h9fr5qig.fsf@nightsong.com> Steven D'Aprano writes: > if condition: > print(1) > print(2) > else: > print(3) > print(4) > what value should it return? Justify your choice. It could whatever value that the last call to print() returns. Lisp has worked like that since the 1950's. > What should be the return value of this statement? > > while True: > x += 1 > if condition: break It could return None, or break(val) could return val. > I don't think that "every statement is an expression" is conceptually > simpler at all. I think it is more difficult to understand. It hasn't been a problem in Lisp or its descendants, Erlang, Haskell, etc. I don't know about Ruby or Javascript. > But it is even harder to understand what it might mean for a while > loop to be a value, and the benefit of doing so seems significantly > less than compelling. It means that you get to use an incredibly simple and beautiful evaluation model. Have you ever used Lisp or Scheme? Give it a try sometime. Excellent free book: https://mitpress.mit.edu/sicp/full-text/book/book.html From steve at pearwood.info Sun Mar 27 21:45:02 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Mar 2016 12:45:02 +1100 Subject: Useless expressions [was Re: Undefined behaviour in C] References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> Message-ID: <56f88c9f$0$1605$c3e8da3$5496439d@news.astraweb.com> On Mon, 28 Mar 2016 01:43 am, BartC wrote: [... talk about function and procedures ...] > Well, that could be done in Python (not so usefully because you can't > take account of such info until a call is attempted), but that's not > what I'm talking about, which is simply allowing: > > fn(...) > > whether fn has an explicit return or not, and not allowing: > > fn # and other kinds of expression > > unless some keyword is used. (I've no idea what that might be; all the > best ones are taken. But I've already said a keyword can be emulated via > a dummy function call.) I think that the only suggestion that might, *just barely*, work in Python is forbidding the evaluation of a single name as a syntax error. Any other expression would have to still be allowed. Advantage: - catches various errors, such as forgetting to call procedure-like functions: main # oops, meant main() or mistyping a keyword: for x in sequence: if condition: next # oops, meant continue Disadvantages: - makes it less convenient to use the `try: name except NameError` idiom. - won't do anything about errors like this: x = y # oops, meant to call y() a = b # this one is okay though - it treats a single name as a special case of arbitrary expressions. What's so special about the single name case that we should guard against this: name but not this? name.validate The Zen of Python has something to say about special cases. import this Now, I happen to think that using "name.validate" for the side-effects of the attribute look-up is a terrible idea. But it's legal code, and the compiler shouldn't make value judgements about good or bad code. You want value judgements, use a linter. -- Steven From python.list at tim.thechases.com Sun Mar 27 22:59:11 2016 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 27 Mar 2016 21:59:11 -0500 Subject: Useless expressions [was Re: Undefined behaviour in C] In-Reply-To: References: <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <56f887c1$0$1598$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20160327215911.755881f5@bigbox.christie.dr> On 2016-03-28 12:38, Chris Angelico wrote: > I would still look askance at code that adds two things and drops > the result, though. The compiler can't discard it, but if a linter > complains, I'd support that. A DSL that requires you to do this is, > imo, poorly designed. Is it only the "*add* two things" or are you decrying any generic operator that gets evaluated and then drops the result? Steven recently opened a thread ["Bash-like pipes in Python"] where this exact sort of thing would be done: get_values() | filter("smith") | sort("income") | send_to_printer() Several different solutions were posited with varying degrees of conciseness-vs-pythonicity-vs-pipe'ness. That said, I'm in the "let the compiler accept valid syntax; leave it to the linter" camp. -tkc From rosuav at gmail.com Sun Mar 27 23:29:41 2016 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 28 Mar 2016 14:29:41 +1100 Subject: Useless expressions [was Re: Undefined behaviour in C] In-Reply-To: <20160327215911.755881f5@bigbox.christie.dr> References: <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <56f887c1$0$1598$c3e8da3$5496439d@news.astraweb.com> <20160327215911.755881f5@bigbox.christie.dr> Message-ID: On Mon, Mar 28, 2016 at 1:59 PM, Tim Chase wrote: > On 2016-03-28 12:38, Chris Angelico wrote: >> I would still look askance at code that adds two things and drops >> the result, though. The compiler can't discard it, but if a linter >> complains, I'd support that. A DSL that requires you to do this is, >> imo, poorly designed. > > Is it only the "*add* two things" or are you decrying any generic > operator that gets evaluated and then drops the result? > > Steven recently opened a thread ["Bash-like pipes in Python"] where > this exact sort of thing would be done: > > get_values() | filter("smith") | sort("income") | send_to_printer() > > Several different solutions were posited with varying degrees of > conciseness-vs-pythonicity-vs-pipe'ness. I was talking about any operator that, for built-in types, does no mutation and has no effect aside from its return value. So yes, the use of the pipe is a perfect counter-example - or rather, proof that my concern is a code smell rather than fundamentally bad. C++ started it with the iostream << and >> overloads; personally, I think that's more cute than useful, but there are times when it can be extremely useful. So I revise my stance: A DSL that requires you to do this *may be* poorly designed, and needs a very solid justification. > That said, I'm in the "let the compiler accept valid syntax; leave it > to the linter" camp. Yeah definitely. ChrisA From nulla.epistola at web.de Mon Mar 28 03:48:49 2016 From: nulla.epistola at web.de (Sibylle Koczian) Date: Mon, 28 Mar 2016 09:48:49 +0200 Subject: help with program In-Reply-To: <56f878e8$0$1593$c3e8da3$5496439d@news.astraweb.com> References: <1392737302.749065.1459024715818.JavaMail.yahoo.ref@mail.yahoo.com> <1392737302.749065.1459024715818.JavaMail.yahoo@mail.yahoo.com> <56f878e8$0$1593$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56F8E1E1.9030201@web.de> Am 28.03.2016 um 02:20 schrieb Steven D'Aprano: > On Mon, 28 Mar 2016 01:18 am, Bob Gailer wrote: > >> The problem with putting input at the end of a program is: if the program >> raises an exception you won't see it. > > True. But the solution to that is simple: don't make mistakes when > programming :-) > > If you have a better solution, please speak up. I don't know Windows very > well and I'm not sure why the console is disappearing in the first place. > Because it was opened only by starting the program, and so it closes when the program ends. Wouldn't the same thing happen on Linux, if a console application were started from the file manager? I would always start a console application from an open command prompt, in case of exceptions. And if my Python GUI application doesn't appear on the screen I do the same, to see the traceback. From nulla.epistola at web.de Mon Mar 28 03:48:49 2016 From: nulla.epistola at web.de (Sibylle Koczian) Date: Mon, 28 Mar 2016 09:48:49 +0200 Subject: help with program In-Reply-To: <56f878e8$0$1593$c3e8da3$5496439d@news.astraweb.com> References: <1392737302.749065.1459024715818.JavaMail.yahoo.ref@mail.yahoo.com> <1392737302.749065.1459024715818.JavaMail.yahoo@mail.yahoo.com> <56f878e8$0$1593$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56F8E1E1.9030201@web.de> Am 28.03.2016 um 02:20 schrieb Steven D'Aprano: > On Mon, 28 Mar 2016 01:18 am, Bob Gailer wrote: > >> The problem with putting input at the end of a program is: if the program >> raises an exception you won't see it. > > True. But the solution to that is simple: don't make mistakes when > programming :-) > > If you have a better solution, please speak up. I don't know Windows very > well and I'm not sure why the console is disappearing in the first place. > Because it was opened only by starting the program, and so it closes when the program ends. Wouldn't the same thing happen on Linux, if a console application were started from the file manager? I would always start a console application from an open command prompt, in case of exceptions. And if my Python GUI application doesn't appear on the screen I do the same, to see the traceback. From jussi.piitulainen at helsinki.fi Mon Mar 28 03:51:00 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Mon, 28 Mar 2016 10:51:00 +0300 Subject: List of Functions References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> Message-ID: Ben Bacarisse writes: > It's shame that anonymous functions (for that's what's being returned > here -- a function with no name) were born of a subject that used > arbitrary Greek letters for things. We seem stuck with the mysterious > but meaningless "lambda" for a very simple and useful idea. Well said. Python should have called it "fun". I have heard that the use of lambda for this purpose was originally not an arbitrary choice but a typographical accident. A misinterpreted caret or something. I also seem to remember that I've seen some discussion on whether the story is true or not, but I forget which way it went. From hongyi.zhao at gmail.com Mon Mar 28 04:07:49 2016 From: hongyi.zhao at gmail.com (Hongyi Zhao) Date: Mon, 28 Mar 2016 08:07:49 +0000 (UTC) Subject: Using python heredoc to substitute the external file read by python script. Message-ID: Hi all, See the following python codes: import os from subprocess import check_output # POSIX: name shall not contain '=', value doesn't contain '\0' output = check_output("source /home/werner/env-intel-toolchains.sh; env -0", shell=True, executable="/bin/bash") In the above codes, I use the file /home/werner/env-intel-toolchains.sh for subprocess.check_output to use for its operation. If I want to use python heredoc to substitute this external file for the above codes. Is this possible? Regards -- .: Hongyi Zhao [ hongyi.zhao AT gmail.com ] Free as in Freedom :. From katewinslet626 at gmail.com Mon Mar 28 04:10:10 2016 From: katewinslet626 at gmail.com (Shiva Upreti) Date: Mon, 28 Mar 2016 01:10:10 -0700 (PDT) Subject: Pyaudio and sockets Message-ID: <2aa228df-4ee4-4515-a013-cf2d65502dd0@googlegroups.com> I am trying to send audio using sockets to a different PC, but audio is not clear on the other end and I cant understand why. Here is the code: import socket import pyaudio import wave import sys import pickle import time HOST="" PORT=1061 s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 RECORD_SECONDS = 3 def record(sock): def callback_record(in_data, frame_count, time_info, status): #print len(in_data) sock.sendall(in_data) return (in_data, pyaudio.paContinue) p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=False, stream_callback=callback_record) stream.start_stream() return stream def play(sock): def callback_play(in_data, frame_count, time_info, status): #msg=recv_all(sock) in_data=sock.recv(5000) return (in_data, pyaudio.paContinue) p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=False, output=True, stream_callback=callback_play) stream.start_stream() return stream def recv_all(sock): data=sock.recv(5000) return data if sys.argv[1] == 'server': s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((HOST, PORT)) s.listen(10) while(True): print "Listening at:", s.getsockname() sc, addr=s.accept() print "Connection established with:", addr while True: stream_record=record(sc) #stream_play=play(sc) while stream_record.is_active(): #time.sleep(0.0) pass #stream_record.stop_stream() #stream_record.close() #stream_play.stop_stream() #stream_play.close() elif sys.argv[1]=='client': s.connect((HOST, PORT)) while True: stream_play=play(s) #time.sleep(5) #stream_record=record(s) while stream_play.is_active(): #time.sleep(0.0) pass #stream_record.stop_stream() #stream_record.close() #stream_play.stop_stream() #stream_play.close() To run it as server enter this command: python audio_chat2.py server To run it as client enter this command: python audio_chat2.py client I also tried running them on same PC, still voice was not clear. From marko at pacujo.net Mon Mar 28 04:58:54 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Mon, 28 Mar 2016 11:58:54 +0300 Subject: List of Functions References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> Message-ID: <87mvpjx9kh.fsf@elektro.pacujo.net> Jussi Piitulainen : > Ben Bacarisse writes: >> It's shame that anonymous functions (for that's what's being returned >> here -- a function with no name) were born of a subject that used >> arbitrary Greek letters for things. We seem stuck with the mysterious >> but meaningless "lambda" for a very simple and useful idea. > > Well said. > > Python should have called it "fun". > > I have heard that the use of lambda for this purpose was originally > not an arbitrary choice but a typographical accident. A misinterpreted > caret or something. I also seem to remember that I've seen some > discussion on whether the story is true or not, but I forget which way > it went. I don't know the etymology of things, but way back when I learned combinatory logic, the capital letter ? was used as the name of the abstraction algorithm. Combinatory logic was able to express any formula without variables, which apparently were somewhat of a sore spot for logicians in the early 20th century. So you took your formula with variables and ran it through the ? algorithm to get an equivalent combinator expression that didn't have any variables. I always thought the ? calculus arose from the abstraction algorithm. Once the logicians had "tamed" variables with ?, they no longer felt the need to avoid them. You could set aside the clumsy combinators and incorporate the lambda in the language itself. ... As for Python, I don't feel a great need for anonymous functions. However, I keep running into a need for anonymous classes, or, rather, classless objects. Not a biggie. I just create a one-off inner class and instantiate it, but I do appreciate Java's syntactic innovation. Marko From breamoreboy at yahoo.co.uk Mon Mar 28 05:36:44 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 28 Mar 2016 10:36:44 +0100 Subject: Problem With Embedded Icon and Python 3.4 In-Reply-To: References: Message-ID: On 26/03/2016 02:37, Wildman via Python-list wrote: > On Sat, 26 Mar 2016 01:42:37 +0000, Mark Lawrence wrote: > >> On 25/03/2016 05:10, Wildman via Python-list wrote: >>> I have a program that I have been trying to rewrite so it will >>> run on Python 2.7 and 3.4. >> >> This http://pythonhosted.org/six/ might come in handy in future. >> >> As I'm also climbing the tkinter cliff at the moment I've found anything >> on stackoverflow from Bryan Oakley to be very helpful. In particular, >> his answer here >> http://stackoverflow.com/questions/17466561/best-way-to-structure-a-tkinter-application >> really helped me get a grip on things. >> >> A lot of the examples here http://pyinmyeye.blogspot.co.uk/ were also >> useful. >> >> HTH. > > Thanks for the links. Good stuff. Bookmarked. > One I forgot http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From ben+python at benfinney.id.au Mon Mar 28 06:29:48 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 28 Mar 2016 21:29:48 +1100 Subject: Using python heredoc to substitute the external file read by python script. References: Message-ID: <85egauc2ub.fsf@benfinney.id.au> Hongyi Zhao writes: > If I want to use python heredoc to substitute this external file for > the above codes. Is this possible? What do you mean by ?Python heredoc?? What Python feature are you referring to? -- \ ?Anyone who puts a small gloss on [a] fundamental technology, | `\ calls it proprietary, and then tries to keep others from | _o__) building on it, is a thief.? ?Tim O'Reilly, 2000-01-25 | Ben Finney From bc at freeuk.com Mon Mar 28 07:11:25 2016 From: bc at freeuk.com (BartC) Date: Mon, 28 Mar 2016 12:11:25 +0100 Subject: Statements as expressions [was Re: Undefined behaviour in C] In-Reply-To: <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 28/03/2016 01:54, Steven D'Aprano wrote: > On Mon, 28 Mar 2016 03:58 am, BartC wrote: > >>> One of Guido's principles in designing Python was to keep it simple, >>> even where that might mean people could make errors with it. This part >>> of the language is no different: any expression can be a statement. >> >> Yeah, but even simpler would be that any statement can also be an >> expression! He didn't go that far though. > > People say that, but I don't believe it. Well, some languages work like that. I think Lisp does. And so does the more 'normal'-looking Algol-68. What does it mean to say that any > statement could also be an expression? If this statement is an expression: > > > if condition: > print(1) > print(2) > else: > print(3) > print(4) > > > what value should it return? Justify your choice. Each branch of the 'if-else' returns the value of the last statement/expression in each block. The if-statement as a whole returns one or the other. Here, it might be the return value of print(); probably None. > What should be the return value of this statement? > > while True: > x += 1 > if condition: break Many statements such as loops just returned 'void' in A68. The interesting statements were if, case-switch and block (where the value is that of the last statement/expression). To make the best use of this, you really need a more free-format syntax than Python, and blocks need closure. A68 used the funny-looking 'fi' to close an if-statement, and 'od' for a loop: while c:=psource[n]; n+:=1; c!=etx do ... od if c then a else b fi := 0 # also written (c|a|b):=0 return case n in: 10,20,30 out: 90 esac > I don't think that "every statement is an expression" is conceptually > simpler at all. I think it is more difficult to understand. Nearly all > human languages make a distinction between things and actions: > > * expressions return a value, which makes them a thing (noun); > > * statements do something, which makes them an action (verb). Yet Python does allow any expression as a statement. Not even the potentially useful block statement, where you do x, y and z and then have a normal expression as its value. And Python allows a for-loop inside a lisp-comprehension. Python also has an if-else statement in the form of a conditional expression (which I won't show as I can never remember the syntax). > It's easy to understand the concept of an expression where the result is > dropped. "Hand me that hammer" and then you just drop the hammer on the > floor. > > It's harder to understand the concept of functions (doing words, verbs) as > values. Huh? Functions do things then return results. Yet Python also allows procedure calls with no explicit return statement, to act as though they return a value: def p(): pass print (p()) It returns None, just like A68 uses 'void'. So Python picks and chooses what it wants from the more general and conceptually simpler model of a language where expressions and statements are interchangeable. Python then is a little more complex because you have to consider what is allowed, and what isn't. >It's being a bit, what's the word "First class functions" take a bit of mental effort to understand, > but the payoff it worth it. > > But it is even harder to understand what it might mean for a while loop to > be a value, and the benefit of doing so seems significantly less than > compelling. Maybe it is easier for non-English speakers with quite > different linguistic models, but the benefit of adding statements as > expressions seems to me to be well less than the extra difficulty it would > produce. (I've created several languages based on the Algol-68 model. With more recent ones I've dropped that model, so that statements and expressions are different, and that is strictly enforced. This makes implementation simpler, and detects lots more errors. The few statements that /were/ also useful as expressions, have separate, simplified, value-returning versions.) -- Bartc From larudwer at freenet.de Mon Mar 28 07:36:56 2016 From: larudwer at freenet.de (larudwer) Date: Mon, 28 Mar 2016 13:36:56 +0200 Subject: repeat items in a list References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> <29bb9c16-eef4-4c00-9e41-ce8419405c29@googlegroups.com> Message-ID: Am 27.03.2016 um 13:13 schrieb Antonio Caminero Garcia: > On Sunday, March 27, 2016 at 11:52:22 AM UTC+2, larudwer wrote: >> how about >> >> >>>> sorted(["a", "b"]*3) >> ['a', 'a', 'a', 'b', 'b', 'b'] > > that's cooler, less efficient though and do not maintain the original order. > In case such order was important, you should proceed as follows: > > If the elements are unique, this would work: > > sorted(sequence*nrep, key=sequence.index) > > Otherwise you'd need a more complex key function (maybe a method of a class with > a static variable that tracks the number of times that such method is called and > with a "dynamic index functionality" that acts accordingly (i-th nrep-group of value v)) > and imo it does not worth it. > in case you want to mainain order: >>>> ["a","b"]*3 ['a', 'b', 'a', 'b', 'a', 'b'] is completely suffincient. From hongyi.zhao at gmail.com Mon Mar 28 08:01:56 2016 From: hongyi.zhao at gmail.com (Hongyi Zhao) Date: Mon, 28 Mar 2016 12:01:56 +0000 (UTC) Subject: Using python heredoc to substitute the external file read by python script. References: Message-ID: On Mon, 28 Mar 2016 21:29:48 +1100, Ben Finney wrote: >> If I want to use python heredoc to substitute this external file for >> the above codes. Is this possible? > > What do you mean by ?Python heredoc?? What Python feature are you > referring to? I find the following methods currently: import subprocess subprocess.Popen( """ cat < new.txt Hello World! EOF""", shell=True) subprocess.Popen( """ cat < References: <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <56f887c1$0$1598$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 28/03/2016 02:24, Steven D'Aprano wrote: > On Sun, 27 Mar 2016 10:31 pm, BartC wrote: >> Whether there are side-effects is not quite as important as picking up >> things that are likely to be errors: >> >> f() # Probably OK >> g() # Probably OK >> f()+g() # Probably not OK > > You don't and can't know what's "probably not" okay unless you know what > type of object both f and g return. > > Don't think about floats and ints and strings. Think of complex objects with > operator overloading. You're probably thinking of `x + y`. Instead, think > of things like: > > graph + node > database + table There's theory, and there's practice. Most types of statements start with a keyword. The ones that don't need a keyword are assignments (including augmented assignment), and standalone expressions (I'm sure someone will correct me if I'm wrong). And of standalone expressions, the vast majority that I can see are function calls (that is, an expression, of any complexity, ending with (...)). So no matter how many potentially useful counter-examples you can dig up, non-function-call expressions are still going to be highly unusual. And suspect. That's why it's not going to be much loss to disallow them /in that form/. (There are also docstrings, but until yesterday I didn't even know they were also expressions. Wikipedia says this: "Python docstrings appear as a string literal (not an expression) as the first statement following the definition of functions..." so their status is a little unclear. Whatever it is, they don't lead to the same head-scratching when they appear as arbitrary expressions that are not function calls.) > in a procedural style instead of a functional style. With operator > overloading, we have the ability to write domain-specific little languages. Sure. But give the reader a warning! -- Bartc From dan at tombstonezero.net Mon Mar 28 08:39:20 2016 From: dan at tombstonezero.net (Dan Sommers) Date: Mon, 28 Mar 2016 12:39:20 -0000 (UTC) Subject: List of Functions References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> <87mvpjx9kh.fsf@elektro.pacujo.net> Message-ID: On Mon, 28 Mar 2016 11:58:54 +0300, Marko Rauhamaa wrote: > As for Python, I don't feel a great need for anonymous functions. > However, I keep running into a need for anonymous classes, or, rather, > classless objects. Not a biggie. I just create a one-off inner class > and instantiate it, but I do appreciate Java's syntactic innovation. And I always curse Java for having to create an inner class and a method when all I need is a simple function. :-) I think it's Steven D'Aprano who keeps pointing out that you can always name your tiny helper functions instead of using lambda: def some_complex_function(): def f(x) = x + 2 some_library_that_wants_a_callback(f) some_library_that_wants_a_callback(lambda x: x + 2) Both calls to some_library_that_wants_a_callback run the same. From ben.usenet at bsb.me.uk Mon Mar 28 08:55:50 2016 From: ben.usenet at bsb.me.uk (Ben Bacarisse) Date: Mon, 28 Mar 2016 13:55:50 +0100 Subject: Statements as expressions [was Re: Undefined behaviour in C] References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87twjqzrqh.fsf@bsb.me.uk> BartC writes: > On 28/03/2016 01:54, Steven D'Aprano wrote: >> What should be the return value of this statement? >> >> while True: >> x += 1 >> if condition: break > > Many statements such as loops just returned 'void' in A68. The > interesting statements were if, case-switch and block (where the value > is that of the last statement/expression). An alternative would be for a loop to return the last value of its controlling expression. This is usually false for a whole loop but would be true is the loop was exited using break. In a for loop, the value would be the last value of its control variable. This would again permit you to tell a break from a normal for loop finishing. This way you can make the loop variable local and still use its final value outside the loop. Both would render some flag variables and some auxiliary variables redundant though I've not seen a language that does it. Maybe in practice it does not work out so well, but it looked useful when I sketch it out a while back. -- Ben. From marko at pacujo.net Mon Mar 28 09:29:21 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Mon, 28 Mar 2016 16:29:21 +0300 Subject: Useless expressions [was Re: Undefined behaviour in C] References: <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <56f887c1$0$1598$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87y492n32m.fsf@elektro.pacujo.net> BartC : > So no matter how many potentially useful counter-examples you can dig > up, non-function-call expressions are still going to be highly > unusual. And suspect. > > That's why it's not going to be much loss to disallow them /in that > form/. Note that operators are front ends for dunder methods, which can have side effects. I'm not aware of such an example in Python, but C++ notoriously uses operator overloading in its common I/O idioms: cout << "Hello world!" << endl; It turns out that I am currently creating something exciting in Python that "abuses" operators similarly, although without side effects -- I hope to be able to present my results here soonish. So I would be careful not to throw the baby away with the bathwater. There was a time when recursion was viewed with great suspicion, and nested if/else constructs were considered playing with fire. You are clearly getting similar allergic reactions from Python's elegant degrees of freedom. And all the while Java, C# and even C++ are painfully trying to get what Python has had since the beginning. Marko From marko at pacujo.net Mon Mar 28 09:40:44 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Mon, 28 Mar 2016 16:40:44 +0300 Subject: List of Functions References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> <87mvpjx9kh.fsf@elektro.pacujo.net> Message-ID: <87twjqn2jn.fsf@elektro.pacujo.net> Dan Sommers : > On Mon, 28 Mar 2016 11:58:54 +0300, Marko Rauhamaa wrote: > >> As for Python, I don't feel a great need for anonymous functions. >> However, I keep running into a need for anonymous classes, or, >> rather, classless objects. Not a biggie. I just create a one-off >> inner class and instantiate it, but I do appreciate Java's syntactic >> innovation. > > And I always curse Java for having to create an inner class and a > method when all I need is a simple function. :-) > > I think it's Steven D'Aprano who keeps pointing out that you can > always name your tiny helper functions instead of using lambda: > > def some_complex_function(): > def f(x) = x + 2 > some_library_that_wants_a_callback(f) > some_library_that_wants_a_callback(lambda x: x + 2) > > Both calls to some_library_that_wants_a_callback run the same. Yes, but I've come to realize that I quite often need more than a function: I need an object with behavior. The solution is to use a "helper" class. Marko From random832 at fastmail.com Mon Mar 28 10:04:42 2016 From: random832 at fastmail.com (Random832) Date: Mon, 28 Mar 2016 10:04:42 -0400 Subject: repeat items in a list In-Reply-To: References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> <29bb9c16-eef4-4c00-9e41-ce8419405c29@googlegroups.com> Message-ID: <1459173882.380114.561434386.096F166A@webmail.messagingengine.com> On Mon, Mar 28, 2016, at 07:36, larudwer wrote: > in case you want to mainain order: > > >>>> ["a","b"]*3 > ['a', 'b', 'a', 'b', 'a', 'b'] > > is completely suffincient. I think you've completely missed the point of what order he's talking about. How do you turn ['a', 'c', 'b'] into ['a', 'a', 'a', 'c', 'c', 'c', 'b', 'b', 'b']? From best_lay at yahoo.com Mon Mar 28 10:31:48 2016 From: best_lay at yahoo.com (Wildman) Date: Mon, 28 Mar 2016 09:31:48 -0500 Subject: Problem With Embedded Icon and Python 3.4 References: Message-ID: On Mon, 28 Mar 2016 10:36:44 +0100, Mark Lawrence wrote: > On 26/03/2016 02:37, Wildman via Python-list wrote: >> On Sat, 26 Mar 2016 01:42:37 +0000, Mark Lawrence wrote: >> >>> On 25/03/2016 05:10, Wildman via Python-list wrote: >>>> I have a program that I have been trying to rewrite so it will >>>> run on Python 2.7 and 3.4. >>> >>> This http://pythonhosted.org/six/ might come in handy in future. >>> >>> As I'm also climbing the tkinter cliff at the moment I've found anything >>> on stackoverflow from Bryan Oakley to be very helpful. In particular, >>> his answer here >>> http://stackoverflow.com/questions/17466561/best-way-to-structure-a-tkinter-application >>> really helped me get a grip on things. >>> >>> A lot of the examples here http://pyinmyeye.blogspot.co.uk/ were also >>> useful. >>> >>> HTH. >> >> Thanks for the links. Good stuff. Bookmarked. >> > > One I forgot http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html I had already found that one and have it bookmarked. Thanks tho. -- GNU/Linux user #557453 The cow died so I don't need your bull! From nomail at com.invalid Mon Mar 28 11:29:03 2016 From: nomail at com.invalid (ast) Date: Mon, 28 Mar 2016 17:29:03 +0200 Subject: Path when reading an external file Message-ID: <56f94dc3$0$3337$426a34cc@news.free.fr> Hello In a program "code.py" I read an external file "foo.txt" supposed to be located in the same directory that "code.py" python/src/code.py python/src/foo.txt In "code.py": f = open('foo.txt', 'r') But if I run "python code.py" in an other dir than src/ say in python/, it will not work because file "foo.txt" will be searched in dir python/ and not in dir python/src/ I think it is possible to build an absolute path for "foo.txt" using __file__ so that the program works wherever you launch "python code.py" Is it the correct way to handle this problem ? thx From nomail at com.invalid Mon Mar 28 11:34:43 2016 From: nomail at com.invalid (ast) Date: Mon, 28 Mar 2016 17:34:43 +0200 Subject: newbie question In-Reply-To: References: <56f3c3eb$0$4546$426a74cc@news.free.fr> <56F3CB1E.2000606@mail.de> Message-ID: <56f94f18$0$3314$426a34cc@news.free.fr> "Matt Wheeler" a ?crit dans le message de news:mailman.92.1458825746.2244.python-list at python.org... > On Thu, 24 Mar 2016 11:10 Sven R. Kunze, wrote: > >> On 24.03.2016 11:57, Matt Wheeler wrote: >> >>>> import ast >> >>>> s = "(1, 2, 3, 4)" >> >>>> t = ast.literal_eval(s) >> >>>> t >> > (1, 2, 3, 4) >> >> I suppose that's the better solution in terms of safety. >> > > It has the added advantage that the enquirer gets to import a module that > shares their name ;) I had a look at that "ast" module doc, but I must admit that I didn't understood a lot of things. From martin at linux-ip.net Mon Mar 28 11:40:07 2016 From: martin at linux-ip.net (Martin A. Brown) Date: Mon, 28 Mar 2016 08:40:07 -0700 Subject: Path when reading an external file In-Reply-To: <56f94dc3$0$3337$426a34cc@news.free.fr> References: <56f94dc3$0$3337$426a34cc@news.free.fr> Message-ID: Greetings, > In a program "code.py" I read an external file "foo.txt" supposed > to be located in the same directory that "code.py" > > python/src/code.py > python/src/foo.txt > > In "code.py": f = open('foo.txt', 'r') > > But if I run "python code.py" in an other dir than src/ say in > python/, it will not work because file "foo.txt" will be searched > in dir python/ and not in dir python/src/ > > I think it is possible to build an absolute path for "foo.txt" > using __file__ so that the program works wherever you launch > "python code.py" > > Is it the correct way to handle this problem ? Ayup, I would say so. My suggested technique: here = os.path.dirname(os.path.abspath(__file__)) foo = os.path.join(here, 'foo.txt') with open(foo, 'r') as f: pass Good luck, -Martin -- Martin A. Brown http://linux-ip.net/ From nomail at com.invalid Mon Mar 28 11:48:33 2016 From: nomail at com.invalid (ast) Date: Mon, 28 Mar 2016 17:48:33 +0200 Subject: Path when reading an external file In-Reply-To: References: <56f94dc3$0$3337$426a34cc@news.free.fr> Message-ID: <56f95256$0$27815$426a34cc@news.free.fr> "Martin A. Brown" a ?crit dans le message de news:mailman.108.1459179618.28225.python-list at python.org... > > Greetings, > >> In a program "code.py" I read an external file "foo.txt" supposed >> to be located in the same directory that "code.py" >> >> python/src/code.py >> python/src/foo.txt >> >> In "code.py": f = open('foo.txt', 'r') >> >> But if I run "python code.py" in an other dir than src/ say in >> python/, it will not work because file "foo.txt" will be searched >> in dir python/ and not in dir python/src/ >> >> I think it is possible to build an absolute path for "foo.txt" >> using __file__ so that the program works wherever you launch >> "python code.py" >> >> Is it the correct way to handle this problem ? > > Ayup, I would say so. My suggested technique: > > here = os.path.dirname(os.path.abspath(__file__)) > foo = os.path.join(here, 'foo.txt') > with open(foo, 'r') as f: > pass > > Good luck, > > -Martin > > -- > Martin A. Brown > http://linux-ip.net/ Ok, this is what I intended to do Thanks for your answer From rgaddi at highlandtechnology.invalid Mon Mar 28 13:30:53 2016 From: rgaddi at highlandtechnology.invalid (Rob Gaddi) Date: Mon, 28 Mar 2016 17:30:53 -0000 (UTC) Subject: repeat items in a list References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> Message-ID: beliavsky at aol.com wrote: > On Saturday, March 26, 2016 at 7:24:10 PM UTC-4, Erik wrote: >> >> Or, if you want to "import operator" first, you can use 'operator.add' >> instead of the lambda (but you _did_ ask for a one-liner ;)). >> >> Out of interest, why the fascination with one-liners? > > Thanks for your reply. Sometimes when I program in Python I think I am not using the full capabilities of the language, so I want to know if there are > more concise ways of doing things. Concise is only worth so much. PEP20 tells us "Explicit is better than implicit", "Simple is better than complex" and "If the implementation is hard to explain, it's a bad idea". Python is a beautifully expressive language. Your goal should not be to write the minimum number of lines of code to accomplish the task. Your goal should be to write the code such that your grandmother can understand it. That way, when you screw it up, you'll be able to easily figure out where and how you did so. Or failing that, you can get grangran to show you. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From no.email at nospam.invalid Mon Mar 28 14:27:31 2016 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 28 Mar 2016 11:27:31 -0700 Subject: Statements as expressions [was Re: Undefined behaviour in C] References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> Message-ID: <878u125ugc.fsf@nightsong.com> BartC writes: > With more recent ones I've dropped that model, so that statements and > expressions are different, and that is strictly enforced. This makes > implementation simpler, and detects lots more errors. You should try Haskell, where there are only expressions, but the ones that perform actions can be separated from the other ones through the type system, so using one in the wrong place raises a compile time type error. From ben+python at benfinney.id.au Mon Mar 28 14:59:38 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 29 Mar 2016 05:59:38 +1100 Subject: Using python heredoc to substitute the external file read by python script. References: Message-ID: <85a8libf8l.fsf@benfinney.id.au> I don't understand what you're trying to do. But I think you have fixed your problem: Hongyi Zhao writes: > It seems the above code will do the job for me. If I understand correctly this sentence, you now have a satisfactory solution. Good! -- \ ?A man must consider what a rich realm he abdicates when he | `\ becomes a conformist.? ?Ralph Waldo Emerson | _o__) | Ben Finney From tjreedy at udel.edu Mon Mar 28 15:34:59 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 Mar 2016 15:34:59 -0400 Subject: Useless expressions [was Re: Undefined behaviour in C] In-Reply-To: <56f88839$0$1598$c3e8da3$5496439d@news.astraweb.com> References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f88839$0$1598$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 3/27/2016 9:26 PM, Steven D'Aprano wrote: > On Mon, 28 Mar 2016 03:39 am, Terry Reedy wrote: >> So Bart is proposing whether 'actually' or 'hypothetically' > I don't think Bart is intending this as an actual proposal to change Python > so much as just a hypothetical to discuss. I don't remember Bart saying anything of the sort. I'll let him clarify hit meaning. >> to either disable an extremely useful feature or >> split Python into two slightly different dialects. I think both are bad >> ideas. > > I don't think that's quite fair. I don't think your strained nitpicking of my statement is quite fair. It is definitely faulty. > The interactive interpreter is already > slightly different from non-interactive use, Yes, the extra behavior of interactive mode is specified in the Reference in the section on Expression statements. https://docs.python.org/3/reference/simple_stmts.html#expression-statements But as far as I can remember, both run the *SAME PYTHON LANGUAGE*. Dialects are a property of languages, not of interpreter modes. > in that bare expressions print the result, Expressions evaluate to objects. Having the interpreter also display the object is at most an added semantic. It is not a syntax difference and in that sense is not a *language* difference*. > while in non-interactive use they just get garbage collected. Garbage collection is not relevant to this proposal or discussion. AFAIK, Objects become eligible for garbage collection at the same time in either mode. > It wouldn't be that different to change "print versus ignore" into "print > versus raise error". Are you serious? Having the *same code* execute in one mode and raise in another, and thereby abort execution of all following code, is quite different. It makes the set of legal statements different and that is the basic definition of a language. It suite fair to call the different sets of legal statements 'slightly different dialects'. > I think it is a bit extreme to call that two different > dialects. Your nitpicking is what is extreme. > If so, then the current interactive interpreter is also a > different dialect. To repeat, the current interactive interpreter runs the same sequence of statements, which is to say, the same language. It just outputs extra information about what is going on. CPython debug builds display even more extra information (about references). >>> 0 0 [44187 refs] >>> a=0 [44189 refs] >>> 0 0 [44189 refs] This in itself does not mean that the debug interactive interpreter is yet a third dialect of Python. -- Terry Jan Reedy From zljubisicmob at gmail.com Mon Mar 28 15:55:37 2016 From: zljubisicmob at gmail.com (zljubisicmob at gmail.com) Date: Mon, 28 Mar 2016 12:55:37 -0700 (PDT) Subject: Sending gmail with no clear password Message-ID: Hi, I have a python3 script that runs 24/7 on linux (raspberry pi) server. It would be very nice for the script to be able to send an email message about certain statuses. As the linux server is headless, I don't have an option to key in the password while starting the script. Furthermore, from time to time I restart the server remotely, so password should be somewhere in the system but kept more secure than hardcoded in the python script. I understand that I can send email by using let's say procedure from the https://rajivpandit.wordpress.com/2013/09/19/how-to-send-email-by-python/ On the link above there are two approaches. One with no need for any authentication or password, but that approach doesn't work. It is written for python 2 but that is what I need. What are my options? Regards. From antoon.pardon at rece.vub.ac.be Mon Mar 28 16:26:48 2016 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Mon, 28 Mar 2016 22:26:48 +0200 Subject: Why lambda in loop requires default? In-Reply-To: <56F73B60.9020603@gmail.com> References: <56F73B60.9020603@gmail.com> Message-ID: <56F99388.1080604@rece.vub.ac.be> Op 27-03-16 om 03:46 schreef gvim: > Given that Python, like Ruby, is an object-oriented language why doesn't this: It has nothing to do with being object-oriented but by how scopes are used > def m(): > a = [] > for i in range(3): a.append(lambda: i) > return a Python doesn't create a new scope for the suite of the for loop. If you want an intermediate scope, you have to provide it your self. Like the following. def m(): a = [] for i in range(3): a.append((lambda i: (lambda : i))(i)) return a > b = m() > for n in range(3): print(b[n]()) # => 2 2 2 > > ... work the same as this in Ruby: > > def m > a = [] > (0..2).each {|i| a << ->(){i}} > a > end I don't know ruby but I guess the block creates a new scope and thus running the block is like calling an anonymous function. So the i in each run of the block is a new instantiation of the variable instead of being the same variable. -- Antoon Pardon From python at lucidity.plus.com Mon Mar 28 16:41:53 2016 From: python at lucidity.plus.com (Erik) Date: Mon, 28 Mar 2016 21:41:53 +0100 Subject: Sending gmail with no clear password In-Reply-To: References: Message-ID: <56F99711.70309@lucidity.plus.com> Hi. It's hard to understand what your question is. On 28/03/16 20:55, zljubisicmob at gmail.com wrote: > I have a python3 script that runs 24/7 on linux (raspberry pi) > server. It would be very nice for the script to be able to send an > email message about certain statuses. Reading between the lines, am I correct in stating that: 1) You preferably want to send an email with no authentication at all. 2) If authentication is /required/ by the server you are contacting then you don't want the password to be stored in plain text. 3) The link you pasted does what you want (with no authentication), but it doesn't work in Python 3. > What are my options? If I have understood you correctly, then the obvious thing is to convert the code in the link so that it works in Python 3. If you can't do that and you need to use authentication, then there's only so much you can do to protect your password if you don't want to type it in. Why can't the password be stored in plain text? Who are you trying to secure it from? I suspect that the answer is that you can /obscure/ or /obfuscate/ the password (i.e., make it difficult to determine - encrypt it using some unique key that's obtained from the server's H/W somehow), but it would be very hard to actually /secure/ it from anyone with access to your Rpi. If your script can determine the password in plain text automatically (without some sort of external input), then so can anyone who has logged into the device with the appropriate permissions - if only by copying the script and making it display the password rather than send it to the server. E. From nickle at gmail.com Mon Mar 28 16:49:02 2016 From: nickle at gmail.com (Nick) Date: Mon, 28 Mar 2016 13:49:02 -0700 (PDT) Subject: Meta Data Message-ID: Django has the idea of specifying models using typed Fields. The same exists within SQLAlchemy Are there any tutorials on setting up a similar system. ie. Declare classes and fields, query the meta data. Fields restricted to certain types. N. From davidgshi at yahoo.co.uk Mon Mar 28 17:06:16 2016 From: davidgshi at yahoo.co.uk (David Shi) Date: Mon, 28 Mar 2016 21:06:16 +0000 (UTC) Subject: Which are best, well-tested ways to create REST services, with Json, in Python? References: <496157280.2274927.1459199176427.JavaMail.yahoo.ref@mail.yahoo.com> Message-ID: <496157280.2274927.1459199176427.JavaMail.yahoo@mail.yahoo.com> Has anyone done a recent reviews of creating REST services, in Python? Regards. David From jenswaelkens at gmail.com Mon Mar 28 17:10:28 2016 From: jenswaelkens at gmail.com (jenswaelkens at gmail.com) Date: Mon, 28 Mar 2016 14:10:28 -0700 (PDT) Subject: [newbie] tkFileDialog does not show title Message-ID: <968ddc19-1944-4ec8-975b-ec88e4391361@googlegroups.com> I'm using the tkFileDialog-module in Python 2.7, it works fine except for one thing: when I add a title, the title isn't shown. e.g. I have this line of code: inputfilename=tkFileDialog.askopenfilename(defaultextension=".dat", filetypes=(("data file", "*.dat"),("All Files", "*.*") ),title='Select input file') this works fine i.e. the file selector menu opens but I expected that the text 'Select input file' would be displayed too. Can anyone here explain me how I can achieve this? kind regards, Jens From rosuav at gmail.com Mon Mar 28 17:25:49 2016 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 29 Mar 2016 08:25:49 +1100 Subject: repeat items in a list In-Reply-To: References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> Message-ID: On Tue, Mar 29, 2016 at 4:30 AM, Rob Gaddi wrote: > beliavsky at aol.com wrote: > >> On Saturday, March 26, 2016 at 7:24:10 PM UTC-4, Erik wrote: >>> >>> Or, if you want to "import operator" first, you can use 'operator.add' >>> instead of the lambda (but you _did_ ask for a one-liner ;)). >>> >>> Out of interest, why the fascination with one-liners? >> >> Thanks for your reply. Sometimes when I program in Python I think I am not using the full capabilities of the language, so I want to know if there are >> more concise ways of doing things. > > Concise is only worth so much. PEP20 tells us "Explicit is better than > implicit", "Simple is better than complex" and "If the implementation is > hard to explain, it's a bad idea". > > Python is a beautifully expressive language. Your goal should not be to > write the minimum number of lines of code to accomplish the task. > Your goal should be to write the code such that your grandmother can > understand it. That way, when you screw it up, you'll be able to easily > figure out where and how you did so. Or failing that, you can get > grangran to show you. Just out of interest, did you (generic you) happen to notice Mark's suggestion? It's a one-liner that nicely expresses the intention and accomplishes the goal: yy = [aa for aa in xx for _ in range(nrep)] It quietly went through without fanfare, but I would say this is the perfect solution to the original problem. ChrisA From rosuav at gmail.com Mon Mar 28 17:40:04 2016 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 29 Mar 2016 08:40:04 +1100 Subject: List of Functions In-Reply-To: <87twjqn2jn.fsf@elektro.pacujo.net> References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> <87mvpjx9kh.fsf@elektro.pacujo.net> <87twjqn2jn.fsf@elektro.pacujo.net> Message-ID: On Tue, Mar 29, 2016 at 12:40 AM, Marko Rauhamaa wrote: > Dan Sommers : > >> On Mon, 28 Mar 2016 11:58:54 +0300, Marko Rauhamaa wrote: >> >>> As for Python, I don't feel a great need for anonymous functions. >>> However, I keep running into a need for anonymous classes, or, >>> rather, classless objects. Not a biggie. I just create a one-off >>> inner class and instantiate it, but I do appreciate Java's syntactic >>> innovation. >> >> And I always curse Java for having to create an inner class and a >> method when all I need is a simple function. :-) >> >> I think it's Steven D'Aprano who keeps pointing out that you can >> always name your tiny helper functions instead of using lambda: >> >> def some_complex_function(): >> def f(x) = x + 2 >> some_library_that_wants_a_callback(f) >> some_library_that_wants_a_callback(lambda x: x + 2) >> >> Both calls to some_library_that_wants_a_callback run the same. > > Yes, but I've come to realize that I quite often need more than a > function: I need an object with behavior. The solution is to use a > "helper" class. Can you give an example of code that would benefit from a "lambda-class" construct? Since all functions more complicated than "return this expression" need statement syntax in Python, you'd be pretty restricted in what you can do, so I'm thinking that maybe a SimpleNamespace might suffice: from types import SimpleNamespace obj = SimpleNamespace( add2=lambda x: x+2, squared=lambda x: x*x, ) But if "behaviour" involves mutable state, it'd be fiddly to squish that into lambda functions, so a lambda class would be impractical too. What you could perhaps do is this: def one_off(cls): return cls() @one_off class obj: def func1(self): ... def func2(self): ... obj.func1() obj.func2() It's a statement, with all the costs and benefits thereof, but you don't have to have "obj = obj()" at the end. ChrisA From joel.goldstick at gmail.com Mon Mar 28 17:42:19 2016 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 28 Mar 2016 17:42:19 -0400 Subject: Meta Data In-Reply-To: References: Message-ID: There is information in Pro Django Models chapter that may be what you want. Pro Django, Apress, Marty Alchin On Mon, Mar 28, 2016 at 4:49 PM, Nick wrote: > Django has the idea of specifying models using typed Fields. > The same exists within SQLAlchemy > > Are there any tutorials on setting up a similar system. > > ie. Declare classes and fields, query the meta data. Fields restricted to > certain types. > > N. > -- > https://mail.python.org/mailman/listinfo/python-list > -- Joel Goldstick http://joelgoldstick.com/ http://cc-baseballstats.info/ From nickle at gmail.com Mon Mar 28 18:06:15 2016 From: nickle at gmail.com (Nick) Date: Mon, 28 Mar 2016 15:06:15 -0700 (PDT) Subject: Meta Data In-Reply-To: References: Message-ID: Thanks Joel, A quick look on Amazon shows it is probably relevant. N. From python at lucidity.plus.com Mon Mar 28 18:14:07 2016 From: python at lucidity.plus.com (Erik) Date: Mon, 28 Mar 2016 23:14:07 +0100 Subject: repeat items in a list In-Reply-To: References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> Message-ID: <56F9ACAF.5050602@lucidity.plus.com> On 28/03/16 22:25, Chris Angelico wrote: > Just out of interest, did you (generic you) happen to notice Mark's > suggestion? It's a one-liner that nicely expresses the intention and > accomplishes the goal: > > yy = [aa for aa in xx for _ in range(nrep)] > > It quietly went through without fanfare, but I would say this is the > perfect solution to the original problem. I noticed it (and I timed it - it was ~30% faster than my version (because mine was creating short transient list objects), but it takes a _LOT_ - millions - of iterations of the example case (nrep = 3, xx = two-element-list) to even make it measurable on my PC). It would have probably been even quicker if he'd cached the range() object. I'm not convinced it's particularly intuitive, though. That trailing "for _ in range(nrep)" looks at first glance like an error - some code that's generating a value that is not referenced anywhere else. It makes perfect sense when one analyses it, but it's not the most immediately grokkable construct. Hmmm. It's almost as if in this instance I'd prefer something like: yy = [for aa in xx for _ in range(nrep): aa] But I know we can't go /there/ ;) E. From best_lay at yahoo.com Mon Mar 28 18:14:36 2016 From: best_lay at yahoo.com (Wildman) Date: Mon, 28 Mar 2016 17:14:36 -0500 Subject: [newbie] tkFileDialog does not show title References: <968ddc19-1944-4ec8-975b-ec88e4391361@googlegroups.com> Message-ID: On Mon, 28 Mar 2016 14:10:28 -0700, jenswaelkens wrote: > I'm using the tkFileDialog-module in Python 2.7, it works fine except for one thing: when I add a title, the title isn't shown. > > e.g. I have this line of code: > inputfilename=tkFileDialog.askopenfilename(defaultextension=".dat", filetypes=(("data file", "*.dat"),("All Files", "*.*") ),title='Select input file') > > this works fine i.e. the file selector menu opens but I expected that the text > 'Select input file' would be displayed too. Can anyone here explain me how I can achieve this? > > kind regards, > Jens I copied and pasted your code into a test script and it worked perfectly as it is. Sorry but I don't have clue as where to look for the problem. Does text show elsewhere in your program such as the main window titlebar, labels or buttons? I'm thinking maybe something to do with font or foreground color. I'm just guessing here... -- GNU/Linux user #557453 May the Source be with you. From sinayg at gmail.com Mon Mar 28 18:18:17 2016 From: sinayg at gmail.com (Sinay Goldberg) Date: Tue, 29 Mar 2016 01:18:17 +0300 Subject: error installing scipy on python 3.5, win 10 64 bit Message-ID: <56F9ADA9.6000105@gmail.com> Please help From pkpearson at nowhere.invalid Mon Mar 28 18:29:14 2016 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 28 Mar 2016 22:29:14 GMT Subject: [newbie] tkFileDialog does not show title References: <968ddc19-1944-4ec8-975b-ec88e4391361@googlegroups.com> Message-ID: On Mon, 28 Mar 2016 14:10:28 -0700 (PDT), jenswaelkens at gmail.com wrote: > I'm using the tkFileDialog-module in Python 2.7, it works fine except > for one thing: when I add a title, the title isn't shown. > > e.g. I have this line of code: > inputfilename=tkFileDialog.askopenfilename(defaultextension=".dat", > filetypes=(("data file", "*.dat"),("All Files", "*.*") ), > title='Select input file') > > this works fine i.e. the file selector menu opens but I expected that > the text 'Select input file' would be displayed too. Can anyone here > explain me how I can achieve this? On my system (Linux, Python 2.7.3), "Select input file" appears as the title of the choose-a-file popup window -- that is, it appears on the window's title bar, along with the maximize, minimize, and close buttons. Is that not what you wanted? -- To email me, substitute nowhere->runbox, invalid->com. From steve at pearwood.info Mon Mar 28 18:52:48 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Mar 2016 09:52:48 +1100 Subject: List of Functions References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> <87mvpjx9kh.fsf@elektro.pacujo.net> <87twjqn2jn.fsf@elektro.pacujo.net> Message-ID: <56f9b5c2$0$1606$c3e8da3$5496439d@news.astraweb.com> On Tue, 29 Mar 2016 08:40 am, Chris Angelico wrote: > On Tue, Mar 29, 2016 at 12:40 AM, Marko Rauhamaa wrote: >> Dan Sommers : >> >>> On Mon, 28 Mar 2016 11:58:54 +0300, Marko Rauhamaa wrote: >>> >>>> As for Python, I don't feel a great need for anonymous functions. >>>> However, I keep running into a need for anonymous classes, or, >>>> rather, classless objects. Not a biggie. I just create a one-off >>>> inner class and instantiate it, but I do appreciate Java's syntactic >>>> innovation. "Classless object" is an oxymoron in Python since all values without exception have a class. Can you explain what you mean? Also, for the benefit of those who aren't Java coders, what do you mean by "Java's syntactic innovation"? >>> And I always curse Java for having to create an inner class and a >>> method when all I need is a simple function. :-) >>> >>> I think it's Steven D'Aprano who keeps pointing out that you can >>> always name your tiny helper functions instead of using lambda: >>> >>> def some_complex_function(): >>> def f(x) = x + 2 >>> some_library_that_wants_a_callback(f) >>> some_library_that_wants_a_callback(lambda x: x + 2) >>> >>> Both calls to some_library_that_wants_a_callback run the same. >> >> Yes, but I've come to realize that I quite often need more than a >> function: I need an object with behavior. The solution is to use a >> "helper" class. > > Can you give an example of code that would benefit from a > "lambda-class" construct? That would be called "type" :-) type(name, bases, namespace) returns a new class: py> C = type("MyClass", (object,), {'foo': 1}) py> C py> C.foo 1 -- Steven From walters.justin01 at gmail.com Mon Mar 28 19:11:40 2016 From: walters.justin01 at gmail.com (justin walters) Date: Mon, 28 Mar 2016 16:11:40 -0700 Subject: Which are best, well-tested ways to create REST services, with Json, in Python? In-Reply-To: <496157280.2274927.1459199176427.JavaMail.yahoo@mail.yahoo.com> References: <496157280.2274927.1459199176427.JavaMail.yahoo.ref@mail.yahoo.com> <496157280.2274927.1459199176427.JavaMail.yahoo@mail.yahoo.com> Message-ID: On Mon, Mar 28, 2016 at 2:06 PM, David Shi via Python-list < python-list at python.org> wrote: > Has anyone done a recent reviews of creating REST services, in Python? > Regards. > David > -- > https://mail.python.org/mailman/listinfo/python-list > There are a ton of different ways to do this. Can you provide some details about the application? From rosuav at gmail.com Mon Mar 28 19:40:18 2016 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 29 Mar 2016 10:40:18 +1100 Subject: List of Functions In-Reply-To: <56f9b5c2$0$1606$c3e8da3$5496439d@news.astraweb.com> References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> <87mvpjx9kh.fsf@elektro.pacujo.net> <87twjqn2jn.fsf@elektro.pacujo.net> <56f9b5c2$0$1606$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Mar 29, 2016 at 9:52 AM, Steven D'Aprano wrote: > That would be called "type" :-) > > type(name, bases, namespace) returns a new class: > > > py> C = type("MyClass", (object,), {'foo': 1}) > py> C > > py> C.foo > 1 Yeah, but to do that in a single expression, you need to have all the functions in the dictionary, so it's no improvement over SimpleNamespace. The functions get attached to the class, not the instance, which means they need 'self' - but without assignment, you wouldn't be able to make much use of self anyway. Hence the call for an example. ChrisA From steve at pearwood.info Mon Mar 28 19:40:50 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Mar 2016 10:40:50 +1100 Subject: List of Functions References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> Message-ID: <56f9c104$0$1604$c3e8da3$5496439d@news.astraweb.com> On Mon, 28 Mar 2016 06:51 pm, Jussi Piitulainen wrote: > Ben Bacarisse writes: > >> It's shame that anonymous functions (for that's what's being returned >> here -- a function with no name) were born of a subject that used >> arbitrary Greek letters for things. We seem stuck with the mysterious >> but meaningless "lambda" for a very simple and useful idea. I'm not sure that "lambda" is any more mysterious or meaningless than other terms used in computing. What's a closure? A trampoline? A future? Mapping? Thread? Greenlet? Mantissa? Not to mention terms from mathematics that people simply memorise, like "sin", "cos", "power". Not to mention "Monad". I don't think *anyone* knows what a Monad is ;-) > Well said. > > Python should have called it "fun". As in the 80s pop hit by Cyndia Lauper, "Girls Just Wanna Have Anonymous Functions"? > I have heard that the use of lambda for this purpose was originally not > an arbitrary choice but a typographical accident. A misinterpreted caret > or something. I also seem to remember that I've seen some discussion on > whether the story is true or not, but I forget which way it went. I don't know whether or not it is true, but I've heard the same thing. Quote: (Note: it may seem perverse to use lambda to introduce a procedure/function. The notation goes back to Alonzo Church, who in the 1930's started with a "hat" symbol; he wrote the square function as "? . y ? y". But frustrated typographers moved the hat to the left of the parameter and changed it to a capital lambda: "?y . y ? y"; from there the capital lambda was changed to lowercase, and now we see "?y . y ? y" in math books and (lambda (y) (* y y)) in Lisp. If it were up to me, I'd use fun or maybe ^. ) http://norvig.com/lispy2.html -- Steven From random832 at fastmail.com Mon Mar 28 19:50:18 2016 From: random832 at fastmail.com (Random832) Date: Mon, 28 Mar 2016 19:50:18 -0400 Subject: List of Functions In-Reply-To: <56f9c104$0$1604$c3e8da3$5496439d@news.astraweb.com> References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> <56f9c104$0$1604$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1459209018.3117163.561946234.4A5119C1@webmail.messagingengine.com> On Mon, Mar 28, 2016, at 19:40, Steven D'Aprano wrote: > Not to mention "Monad". I don't think *anyone* knows what a Monad is ;-) A monad is just a monoid in the category of endofunctors; what's the problem? Well, someone had to say it. From rosuav at gmail.com Mon Mar 28 19:54:59 2016 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 29 Mar 2016 10:54:59 +1100 Subject: List of Functions In-Reply-To: <1459209018.3117163.561946234.4A5119C1@webmail.messagingengine.com> References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> <56f9c104$0$1604$c3e8da3$5496439d@news.astraweb.com> <1459209018.3117163.561946234.4A5119C1@webmail.messagingengine.com> Message-ID: On Tue, Mar 29, 2016 at 10:50 AM, Random832 wrote: > On Mon, Mar 28, 2016, at 19:40, Steven D'Aprano wrote: >> Not to mention "Monad". I don't think *anyone* knows what a Monad is ;-) > > A monad is just a monoid in the category of endofunctors; what's the > problem? > > Well, someone had to say it. A monad is what you get in front of every Twitch stream. A polyad is what you get on dodgy torrent sites. Of course, only functional languages have them; nonfunctional languages use adblockers. ChrisA From steve at pearwood.info Mon Mar 28 20:44:41 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Mar 2016 11:44:41 +1100 Subject: Learning Python (or Haskell) makes you a worse programmer Message-ID: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> http://lukeplant.me.uk/blog/posts/why-learning-haskell-python-makes-you-a-worse-programmer/ -- Steven From walters.justin01 at gmail.com Mon Mar 28 21:35:07 2016 From: walters.justin01 at gmail.com (justin walters) Date: Mon, 28 Mar 2016 18:35:07 -0700 Subject: Which are best, well-tested ways to create REST services, with Json, in Python? In-Reply-To: <1788096198.2418319.1459210649427.JavaMail.yahoo@mail.yahoo.com> References: <1788096198.2418319.1459210649427.JavaMail.yahoo@mail.yahoo.com> Message-ID: On Mon, Mar 28, 2016 at 5:17 PM, David Shi wrote: > Hello, Justin, > > I am thinking of a fast, responsive, secure way of doing this. Python at > server-side. It provides REST services. Data exchange with the > web--page. Formatted XML or Json. > > Ideally, it uses the least code. > > Any excellent literature describes this? I like articles which give > insight into the nitty-gritty. > > Looking forward to hearing from you. > > Regards. > > Shao > > > > David, Please reply all on this list. My preferred method is to use Django with Django Rest Framework. Django is a very mature and robust framework with a ton of features. I use it in production for several projects and have very few issues. It includes middleware authentication and security features as well. You can find the Django documentation here: https://docs.djangoproject.com/en/1.9/. If you've never used Django before, I recommend going through the official tutorial. It is also advised to use Python 3.4+. Django rest framework is probably one of the best documented packages out there. You can find it's documentation here: http://www.django-rest-framework.org/. The official tutorial is very in-depth. I would recommend working through it as well. DRF includes a lot of functionality and multiple authentication and serialization methods. There are other options as well depending on the scale of your project you may choose to use something like flask: http://flask.pocoo.org/ with flask-restful and sqlalchemy. Like I said my personal recommendation is Django and DRF as it is easy to set up, there isn't much overhead, and it scales very well. Does that answer your question, or were you looking for more information? From rustompmody at gmail.com Mon Mar 28 22:23:45 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 28 Mar 2016 19:23:45 -0700 (PDT) Subject: List of Functions In-Reply-To: <56f9c104$0$1604$c3e8da3$5496439d@news.astraweb.com> References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> <56f9c104$0$1604$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tuesday, March 29, 2016 at 5:11:02 AM UTC+5:30, Steven D'Aprano wrote: > On Mon, 28 Mar 2016 06:51 pm, Jussi Piitulainen wrote: > > > Ben Bacarisse writes: > > > >> It's shame that anonymous functions (for that's what's being returned > >> here -- a function with no name) were born of a subject that used > >> arbitrary Greek letters for things. We seem stuck with the mysterious > >> but meaningless "lambda" for a very simple and useful idea. > > I'm not sure that "lambda" is any more mysterious or meaningless than other > terms used in computing. What's a closure? A trampoline? A future? Mapping? > Thread? Greenlet? Mantissa? Not to mention terms from mathematics that > people simply memorise, like "sin", "cos", "power". Its my conjecture/contention that people find ? hard because 98% of material presenting it is backward: "A ? is an 'anonymous function" How does "A constant is an anonymous variable" sound? From ben.usenet at bsb.me.uk Mon Mar 28 22:45:58 2016 From: ben.usenet at bsb.me.uk (Ben Bacarisse) Date: Tue, 29 Mar 2016 03:45:58 +0100 Subject: List of Functions References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> <56f9c104$0$1604$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87y492xaqh.fsf@bsb.me.uk> Steven D'Aprano writes: > On Mon, 28 Mar 2016 06:51 pm, Jussi Piitulainen wrote: > >> Ben Bacarisse writes: >> >>> It's shame that anonymous functions (for that's what's being returned >>> here -- a function with no name) were born of a subject that used >>> arbitrary Greek letters for things. We seem stuck with the mysterious >>> but meaningless "lambda" for a very simple and useful idea. > > I'm not sure that "lambda" is any more mysterious or meaningless than other > terms used in computing. What's a closure? A trampoline? A future? Mapping? > Thread? Greenlet? Mantissa? Not to mention terms from mathematics that > people simply memorise, like "sin", "cos", "power". Well lambda is more arbitrary than those that include helpful hints to the technical meaning in the plain English meaning. What's more, though they express important concepts they are not all part of Python's syntax. Lambda has no helpful meaning and yet has to appear in the program's text. Anyway, even it is were exactly like all the other examples, is that a reason to have more? I'd argue that we should have as few such words as possible, especially in the syntax. If functions were defined fun f(x): return x * x then an anonymous function could be written as a function definition but the name fun (x): return x * x I suppose you could do that even with "def" but it's a bit less mnemonic. There's probably a good reason why this was not done -- maybe it stops the grammar being LL(1)? And if lambda's arrived late, and a new keyword is needed to flag a function expression, then lambda is appealing to the designer since it's less likely to be in use as an identifier in existing code than many more meaningful keywords. -- Ben. From rosuav at gmail.com Mon Mar 28 23:33:13 2016 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 29 Mar 2016 14:33:13 +1100 Subject: List of Functions In-Reply-To: <87y492xaqh.fsf@bsb.me.uk> References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> <56f9c104$0$1604$c3e8da3$5496439d@news.astraweb.com> <87y492xaqh.fsf@bsb.me.uk> Message-ID: On Tue, Mar 29, 2016 at 1:45 PM, Ben Bacarisse wrote: > If functions were defined > > fun f(x): return x * x > > then an anonymous function could be written as a function definition but > the name > > fun (x): return x * x > > I suppose you could do that even with "def" but it's a bit less > mnemonic. > > There's probably a good reason why this was not done -- maybe it stops > the grammar being LL(1)? And if lambda's arrived late, and a new > keyword is needed to flag a function expression, then lambda is > appealing to the designer since it's less likely to be in use as an > identifier in existing code than many more meaningful keywords. Some languages are exactly like this. I'm not sure what the reason is for Python's difference, but one possibility is the mess that comes from having statements inside expressions when indentation is significant to statements (but free-form in expressions). ChrisA From ethan at stoneleaf.us Tue Mar 29 00:05:04 2016 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 28 Mar 2016 21:05:04 -0700 Subject: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56F9FEF0.3080405@stoneleaf.us> On 03/28/2016 05:44 PM, Steven D'Aprano wrote: > http://lukeplant.me.uk/blog/posts/why-learning-haskell-python-makes-you-a-worse-programmer/ Beautiful. And my deepest sympathies for the OP. -- ~Ethan~ From torriem at gmail.com Tue Mar 29 00:13:32 2016 From: torriem at gmail.com (Michael Torrie) Date: Mon, 28 Mar 2016 22:13:32 -0600 Subject: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56FA00EC.80909@gmail.com> On 03/28/2016 06:44 PM, Steven D'Aprano wrote: > http://lukeplant.me.uk/blog/posts/why-learning-haskell-python-makes-you-a-worse-programmer/ I have the same problem as the writer. Working in Python makes me really dislike working in any other language! From walters.justin01 at gmail.com Tue Mar 29 00:16:36 2016 From: walters.justin01 at gmail.com (justin walters) Date: Mon, 28 Mar 2016 21:16:36 -0700 Subject: Which are best, well-tested ways to create REST services, with Json, in Python? In-Reply-To: <1674435919.2379350.1459224742285.JavaMail.yahoo@mail.yahoo.com> References: <1674435919.2379350.1459224742285.JavaMail.yahoo@mail.yahoo.com> Message-ID: Hi David, once again, please reply all on this list. I sent you a couple of step by step guides. Pleas look at the links that I sent. On Mon, Mar 28, 2016 at 9:12 PM, David Shi wrote: > Hello, Justin, > > Is there any official step by step guide. > > Send me the download link and link to Official tutorial. > > Regards. > > David > > > On Tuesday, 29 March 2016, 2:35, justin walters < > walters.justin01 at gmail.com> wrote: > > > > > On Mon, Mar 28, 2016 at 5:17 PM, David Shi wrote: > > Hello, Justin, > > I am thinking of a fast, responsive, secure way of doing this. Python at > server-side. It provides REST services. Data exchange with the > web--page. Formatted XML or Json. > > Ideally, it uses the least code. > > Any excellent literature describes this? I like articles which give > insight into the nitty-gritty. > > Looking forward to hearing from you. > > Regards. > > Shao > > > > > > David, > > Please reply all on this list. > > My preferred method is to use Django with Django Rest Framework. Django is > a very mature and robust framework with a ton of features. I use it in > production for several projects and have very few issues. It includes > middleware authentication and security features as well. You can find the > Django documentation here: https://docs.djangoproject.com/en/1.9/. If > you've never used Django before, I recommend going through the official > tutorial. It is also advised to use Python 3.4+. > > Django rest framework is probably one of the best documented packages out > there. You can find it's documentation here: > http://www.django-rest-framework.org/. The official tutorial is very > in-depth. I would recommend working through it as well. DRF includes a lot > of functionality and multiple authentication and serialization methods. > > > There are other options as well depending on the scale of your project you > may choose to use something like flask: http://flask.pocoo.org/ with > flask-restful and sqlalchemy. > > Like I said my personal recommendation is Django and DRF as it is easy to > set up, there isn't much overhead, and it scales very well. > > Does that answer your question, or were you looking for more information? > > > > From marko at pacujo.net Tue Mar 29 00:45:40 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Tue, 29 Mar 2016 07:45:40 +0300 Subject: List of Functions References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> <87mvpjx9kh.fsf@elektro.pacujo.net> <87twjqn2jn.fsf@elektro.pacujo.net> Message-ID: <874mbpyjrf.fsf@elektro.pacujo.net> Chris Angelico : > On Tue, Mar 29, 2016 at 12:40 AM, Marko Rauhamaa wrote: >> Dan Sommers : >> >>> On Mon, 28 Mar 2016 11:58:54 +0300, Marko Rauhamaa wrote: >>> >>>> As for Python, I don't feel a great need for anonymous functions. >>>> However, I keep running into a need for anonymous classes, or, >>>> rather, classless objects. Not a biggie. I just create a one-off >>>> inner class and instantiate it, but I do appreciate Java's syntactic >>>> innovation. >>> >>> And I always curse Java for having to create an inner class and a >>> method when all I need is a simple function. :-) >>> >>> I think it's Steven D'Aprano who keeps pointing out that you can >>> always name your tiny helper functions instead of using lambda: >>> >>> def some_complex_function(): >>> def f(x) = x + 2 >>> some_library_that_wants_a_callback(f) >>> some_library_that_wants_a_callback(lambda x: x + 2) >>> >>> Both calls to some_library_that_wants_a_callback run the same. >> >> Yes, but I've come to realize that I quite often need more than a >> function: I need an object with behavior. The solution is to use a >> "helper" class. > > Can you give an example of code that would benefit from a > "lambda-class" construct? Here's a recent example: ======================================================================== def process(self, source): awk = self class Source(snake.FieldSource): def emit_fields(self): for fields in snake.get_fields( source, awk.encoding, awk.errors, awk.eol, awk.delim): if awk.selector is None or awk.selector(fields): yield [ fields[i] for i in awk.columns ] return Source(self.encoding, self.errors, self.eol, self.delim) ======================================================================== Here's another, older one: ======================================================================== def __init__(self, server, sock, domain, peer): super().__init__(server, sock) conn = self client_ip = peer[0] [...] class SPF_HELO(STATE): def terminate(self): conn.resume() conn.spf_query.cancel() conn.close() if conn.timer is not None: conn.timer.cancel() conn.timer = None conn.set_state(ZOMBIE) def handle_spf_verdict(self, verdict, reason, *capabilities): conn.resume() conn.log("verdict {} reason {}".format(verdict, reason)) # RFC 4408 ?2.5.5 calls for leniency for SoftFail #if verdict in [ SPFClient.FAIL, SPFClient.SOFT_FAIL ]: if verdict in [ SPFClient.FAIL ]: conn.respond(550, "SPF check failed: {}".format(reason)) conn.set_state(IDLE) return conn.respond(250, server.domain, *capabilities) conn.set_state(IDLE) ======================================================================== Marko From marko at pacujo.net Tue Mar 29 00:49:38 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Tue, 29 Mar 2016 07:49:38 +0300 Subject: List of Functions References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> <87mvpjx9kh.fsf@elektro.pacujo.net> <87twjqn2jn.fsf@elektro.pacujo.net> <56f9b5c2$0$1606$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87zithx50d.fsf@elektro.pacujo.net> Steven D'Aprano : > On Tue, 29 Mar 2016 08:40 am, Chris Angelico wrote: > >> On Tue, Mar 29, 2016 at 12:40 AM, Marko Rauhamaa wrote: >>> Dan Sommers : >>> >>>> On Mon, 28 Mar 2016 11:58:54 +0300, Marko Rauhamaa wrote: >>>>> As for Python, I don't feel a great need for anonymous functions. >>>>> However, I keep running into a need for anonymous classes, or, >>>>> rather, classless objects. Not a biggie. I just create a one-off >>>>> inner class and instantiate it, but I do appreciate Java's >>>>> syntactic innovation. > > "Classless object" is an oxymoron in Python since all values without > exception have a class. Can you explain what you mean? In class terms, I mean a closure class that has precisely one instance. Just like a closure function has precisely one instance. In object terms, I mean an object that implements an interface but whose class is not of essence. > Also, for the benefit of those who aren't Java coders, what do you mean > by "Java's syntactic innovation"? HelloWorld frenchGreeting = new HelloWorld() { String name = "tout le monde"; public void greet() { greetSomeone("tout le monde"); } public void greetSomeone(String someone) { name = someone; System.out.println("Salut " + name); } }; Marko From rosuav at gmail.com Tue Mar 29 01:00:06 2016 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 29 Mar 2016 16:00:06 +1100 Subject: List of Functions In-Reply-To: <874mbpyjrf.fsf@elektro.pacujo.net> References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> <87mvpjx9kh.fsf@elektro.pacujo.net> <87twjqn2jn.fsf@elektro.pacujo.net> <874mbpyjrf.fsf@elektro.pacujo.net> Message-ID: On Tue, Mar 29, 2016 at 3:45 PM, Marko Rauhamaa wrote: > Chris Angelico : > >> On Tue, Mar 29, 2016 at 12:40 AM, Marko Rauhamaa wrote: >>> Dan Sommers : >>> >>>> On Mon, 28 Mar 2016 11:58:54 +0300, Marko Rauhamaa wrote: >>>> >>>>> As for Python, I don't feel a great need for anonymous functions. >>>>> However, I keep running into a need for anonymous classes, or, >>>>> rather, classless objects. Not a biggie. I just create a one-off >>>>> inner class and instantiate it, but I do appreciate Java's syntactic >>>>> innovation. >>>> >>>> And I always curse Java for having to create an inner class and a >>>> method when all I need is a simple function. :-) >>>> >>>> I think it's Steven D'Aprano who keeps pointing out that you can >>>> always name your tiny helper functions instead of using lambda: >>>> >>>> def some_complex_function(): >>>> def f(x) = x + 2 >>>> some_library_that_wants_a_callback(f) >>>> some_library_that_wants_a_callback(lambda x: x + 2) >>>> >>>> Both calls to some_library_that_wants_a_callback run the same. >>> >>> Yes, but I've come to realize that I quite often need more than a >>> function: I need an object with behavior. The solution is to use a >>> "helper" class. >> >> Can you give an example of code that would benefit from a >> "lambda-class" construct? > > Here's a recent example: > > ======================================================================== > def process(self, source): > awk = self > class Source(snake.FieldSource): > def emit_fields(self): > for fields in snake.get_fields( > source, awk.encoding, awk.errors, > awk.eol, awk.delim): > if awk.selector is None or awk.selector(fields): > yield [ fields[i] for i in awk.columns ] > return Source(self.encoding, self.errors, self.eol, self.delim) > ======================================================================== > > Here's another, older one: > > ======================================================================== > def __init__(self, server, sock, domain, peer): > super().__init__(server, sock) > conn = self > client_ip = peer[0] > > [...] > > class SPF_HELO(STATE): > def terminate(self): > conn.resume() > conn.spf_query.cancel() > conn.close() > if conn.timer is not None: > conn.timer.cancel() > conn.timer = None > conn.set_state(ZOMBIE) > > def handle_spf_verdict(self, verdict, reason, *capabilities): > conn.resume() > conn.log("verdict {} reason {}".format(verdict, reason)) > # RFC 4408 ?2.5.5 calls for leniency for SoftFail > #if verdict in [ SPFClient.FAIL, SPFClient.SOFT_FAIL ]: > if verdict in [ SPFClient.FAIL ]: > conn.respond(550, "SPF check failed: {}".format(reason)) > conn.set_state(IDLE) > return > conn.respond(250, server.domain, *capabilities) > conn.set_state(IDLE) > ======================================================================== Since those functions have statements in them, there's not going to be any way to construct this class as an expression (short of stupid messing around with exec, which would be a bad idea). So the best you're likely to be able to do is a metaclass or decorator that short-hands the instantiation - or crafting your other code such that it takes the class, rather than an instance of the class. The latter is quite Pythonic, but generally not as well regarded in other languages, sometimes for obvious reasons like "classes aren't first class objects". :) ChrisA From sharad1087 at gmail.com Tue Mar 29 01:20:31 2016 From: sharad1087 at gmail.com (sharad1087 at gmail.com) Date: Mon, 28 Mar 2016 22:20:31 -0700 (PDT) Subject: Re-using TCL code from python over network Message-ID: <172d629d-3dc8-4e47-b163-05b4f32a027c@googlegroups.com> Hi We've a test automation framework written in TCL (including the automated test cases). We are evaluating shifting to Python and have a test framework in Python (including the automated test cases). Python provides a lot more 3rd party libraries that we'd like to make use of. We use a pretty old version of TCL (8.4.5, 32 bit). It's on FreeBSD and we've compiled it in-house. Compiling it to 64 bit or moving to a newer version is a massive task (since we've a lot of libraries - written in C and compiled as well as pure tcl). Also, we are evaluating having this Python infrastructure on Linux (CentOS). I've explored Python's Tkinter but it won't suit our case as it points to system installed TCL. I've also explored Python's subprocess (launch an interactive TCL shell remotely) and pexpect but none of them worked well for me to allow me to use TCL code interactively from Python. I'd like to gather any ideas/experience around this. If anyone has tried a similar stuff before and can share his/her experience, I'd appreciate it. Regards Sharad From rustompmody at gmail.com Tue Mar 29 02:21:04 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 28 Mar 2016 23:21:04 -0700 (PDT) Subject: List of Functions In-Reply-To: <87y492xaqh.fsf@bsb.me.uk> References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> <56f9c104$0$1604$c3e8da3$5496439d@news.astraweb.com> <87y492xaqh.fsf@bsb.me.uk> Message-ID: <10836e10-316a-492d-98ff-1928ac7eb8e6@googlegroups.com> On Tuesday, March 29, 2016 at 8:16:12 AM UTC+5:30, Ben Bacarisse wrote: > Steven D'Aprano writes: > > > On Mon, 28 Mar 2016 06:51 pm, Jussi Piitulainen wrote: > > > >> Ben Bacarisse writes: > >> > >>> It's shame that anonymous functions (for that's what's being returned > >>> here -- a function with no name) were born of a subject that used > >>> arbitrary Greek letters for things. We seem stuck with the mysterious > >>> but meaningless "lambda" for a very simple and useful idea. > > > > I'm not sure that "lambda" is any more mysterious or meaningless than other > > terms used in computing. What's a closure? A trampoline? A future? Mapping? > > Thread? Greenlet? Mantissa? Not to mention terms from mathematics that > > people simply memorise, like "sin", "cos", "power". > > Well lambda is more arbitrary than those that include helpful hints to > the technical meaning in the plain English meaning. What's more, though > they express important concepts they are not all part of Python's > syntax. Lambda has no helpful meaning and yet has to appear in the > program's text. I am guessing its a long time since you were introduced to computers. And you've forgotten what the jargon first felt like. As a student I remember my friends who were doing projects with me working at my place. And my mum made the strange remark: "You guys use all the words that I know. And you make them into sentences that have no meaning at all." Since you've 'forgotten' that jargonification stage, lets start with 'memory'. 'Memory' is a very old English word, eg. what I did right now -- remembering what my Mum told me some 35 years ago: Does it have anything to do with what memory means in computer-jargon? Dijkstra liked to point out that CS was backward in America compared to Europe because in Europe they used 'store' but Americans used anthropomorphism like memory Now given that store can mean -- among other things -- - room where I dump stuff - shop where I buy bread and eggs - etc why is Dijkstra's preferred use actually any better? Or his most famous request: When you make an error please call it an error. There is no 'mean little bug' crawling out when you were not looking. Shall we rename 'debugging programs' to 'error-correcting code(s)'? Likewise computer has always been a mathematician that computes and program is for things like radio-program, concert-program etc > > Anyway, even it is were exactly like all the other examples, is that a > reason to have more? I'd argue that we should have as few such words as > possible, especially in the syntax. Its a hard question Take an old word and give it a new related but different meaning vs Invent a nonsense word for a genuinely new concept My own finding is that repurposing old words to new concepts causes more confusion and misunderstanding than understanding and 'progress' A record of how sticking to sloppy terminology perpetuates sloppy understanding: http://blog.languager.org/2011/02/cs-education-is-fat-and-weak-2.html From auriocus at gmx.de Tue Mar 29 02:35:20 2016 From: auriocus at gmx.de (Christian Gollwitzer) Date: Tue, 29 Mar 2016 08:35:20 +0200 Subject: Re-using TCL code from python over network In-Reply-To: <172d629d-3dc8-4e47-b163-05b4f32a027c@googlegroups.com> References: <172d629d-3dc8-4e47-b163-05b4f32a027c@googlegroups.com> Message-ID: Am 29.03.16 um 07:20 schrieb sharad1087 at gmail.com: > We've a test automation framework written in TCL (including the > automated test cases). We are evaluating shifting to Python and have > a test framework in Python (including the automated test cases). > Python provides a lot more 3rd party libraries that we'd like to make > use of. > > We use a pretty old version of TCL (8.4.5, 32 bit). It's on FreeBSD > and we've compiled it in-house. Compiling it to 64 bit or moving to a > newer version is a massive task (since we've a lot of libraries - > written in C and compiled as well as pure tcl). Tcl's API (and ABI) is highly stable. I suspect that you could recompile most of the libraries, unless they depend on 3rd party code which is not portable. But of course it might be easier to call it from Python. > I've explored Python's Tkinter but it won't suit our case as it > points to system installed TCL. I've also explored Python's > subprocess (launch an interactive TCL shell remotely) and pexpect but > none of them worked well for me to allow me to use TCL code > interactively from Python. > > I'd like to gather any ideas/experience around this. If anyone has > tried a similar stuff before and can share his/her experience, I'd > appreciate it. You can set up a server in Tcl which will run arbitrary code from the network. The simplest possible server looks like this: http://wiki.tcl.tk/15539 A more complete package (which will correctly handle scripts which span multiple lines etc.) is the comm package in tcllib: https://core.tcl.tk/tcllib/doc/trunk/embedded/www/tcllib/files/modules/comm/comm.html Beware that this is of course a security hole, you should only do it in a network restricted by your firewall or by employing a safe interpreter on the Tcl side which is sufficiently restricted. https://www.tcl.tk/man/tcl8.4/TclCmd/interp.htm#M10 Probably the easiest way is using Tkinter from Python to send commands via the comm package to the remote site, i.e. tk.eval('package require comm') and then sending your commands by tk.eval('comm:comm send ...') The comm protocol is very simplistic http://docs.activestate.com/activetcl/8.4/tcllib/comm/comm_wire.html you could also reproduce it from Python in order to reduce this jumping through hoops. In the end it will always be a messy solution. As an interim solution it might work, but you should seriously consider recompiling the code as 64 bit, migrating all code to Python or watch out for the libraries you need in modern Tcl. Christian From jenswaelkens at gmail.com Tue Mar 29 02:47:15 2016 From: jenswaelkens at gmail.com (jenswaelkens at gmail.com) Date: Mon, 28 Mar 2016 23:47:15 -0700 (PDT) Subject: [newbie] tkFileDialog does not show title In-Reply-To: References: <968ddc19-1944-4ec8-975b-ec88e4391361@googlegroups.com> Message-ID: <8dbb835a-6ae7-43cc-a721-0df7a6338403@googlegroups.com> Op dinsdag 29 maart 2016 00:29:29 UTC+2 schreef Peter Pearson: > On Mon, 28 Mar 2016 14:10:28 -0700 (PDT), jenswaelkens at gmail.com wrote: > > I'm using the tkFileDialog-module in Python 2.7, it works fine except > > for one thing: when I add a title, the title isn't shown. > > > > e.g. I have this line of code: > > inputfilename=tkFileDialog.askopenfilename(defaultextension=".dat", > > filetypes=(("data file", "*.dat"),("All Files", "*.*") ), > > title='Select input file') > > > > this works fine i.e. the file selector menu opens but I expected that > > the text 'Select input file' would be displayed too. Can anyone here > > explain me how I can achieve this? > > On my system (Linux, Python 2.7.3), "Select input file" appears as > the title of the choose-a-file popup window -- that is, it appears on > the window's title bar, along with the maximize, minimize, and close > buttons. Is that not what you wanted? > > -- > To email me, substitute nowhere->runbox, invalid->com. Thanks Peter and Wildman for trying this out on your systems. Now I know at least the code is correct but the fact that nothing is displayed on my desktop has probably to do with some setting of the LXDE-desktop I'm using. I will investigate this further. kind regards, jens From marko at pacujo.net Tue Mar 29 02:50:22 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Tue, 29 Mar 2016 09:50:22 +0300 Subject: List of Functions References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> <56f9c104$0$1604$c3e8da3$5496439d@news.astraweb.com> <87y492xaqh.fsf@bsb.me.uk> <10836e10-316a-492d-98ff-1928ac7eb8e6@googlegroups.com> Message-ID: <87shz9wzf5.fsf@elektro.pacujo.net> Rustom Mody : > And my mum made the strange remark: "You guys use all the words that I > know. And you make them into sentences that have no meaning at all." That's what I think when I hear Estonian spoken. > My own finding is that repurposing old words to new concepts causes > more confusion and misunderstanding than understanding and 'progress' I disagree. I think it's absolutely great that we have "charm quarks" after centuries of "electrostatic equilibria". Finnish has a long tradition of translating fancy words into proper Finnish, and that has contributed to more informed democratic debate on, say, nuclear energy. We have: suunnikas for parallelogram puolisuunnikas for trapezoid suorakaide for rectangle suhde for ratio muuttuja for variable mahahaava for peptic ulcer syd?nkohtaus for myocardial infarction selk?ydin for spinal cord immuunikato for AIDS rattijuoppous for DUI ensiapu for CPR ydinvoima for nuclear power s?hk? for electricity happi for oxygen h?k? for carbon monoxide vetovoima for attraction kiihtyvyys for acceleration tietorakenne for data structure viite for reference etc etc Here's a funny, somewhat related story. I was wondering about the etymology of the word "glamour." I thought it must be some old borrowing from French. In reality, it was borrowed from Scots English, which borrowed it from English English. The original words was "grammar," which referred to what theology students studied in the university, ie, Latin. Only Latin carried the proper magic, charm. The Catholic priests did their hocuspocus ("hoc est corpus meum") in proper "grammar," or, in Scotland, "glamour." Would software developers be more glamorous if they used more impenetrable jargon? Marko From auriocus at gmx.de Tue Mar 29 02:52:42 2016 From: auriocus at gmx.de (Christian Gollwitzer) Date: Tue, 29 Mar 2016 08:52:42 +0200 Subject: List of Functions In-Reply-To: <10836e10-316a-492d-98ff-1928ac7eb8e6@googlegroups.com> References: <3c44f0f8-d701-463e-bf2c-f5871c51bddf@googlegroups.com> <87bn5z1mkd.fsf@bsb.me.uk> <56f9c104$0$1604$c3e8da3$5496439d@news.astraweb.com> <87y492xaqh.fsf@bsb.me.uk> <10836e10-316a-492d-98ff-1928ac7eb8e6@googlegroups.com> Message-ID: Am 29.03.16 um 08:21 schrieb Rustom Mody: > Dijkstra liked to point out that CS was backward in America compared to Europe > because in Europe they used 'store' but Americans used anthropomorphism like memory > > Now given that store can mean -- among other things -- > - room where I dump stuff > - shop where I buy bread and eggs > - etc > why is Dijkstra's preferred use actually any better? The Oxford dictionary lists "store" for "shop" as "chiefly North American" http://www.oxforddictionaries.com/definition/english/store Maybe Dijkstra was speaking from his native Dutch perspective? I don't know in Dutch, but at least in German we use "Speicher", which means "store room" - either a closet or room, typically under the roof, where you store things for later use, or a municipal facility to store, e.g. water in big amounts, or the big buildings at harbours used to store goods, but never a shop. A room where you store things for later use is a quite good description for computer memory, isn't it? Christian From steve+comp.lang.python at pearwood.info Tue Mar 29 03:12:31 2016 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 29 Mar 2016 18:12:31 +1100 Subject: Useless expressions [was Re: Undefined behaviour in C] References: <56f02196$0$1588$c3e8da3$5496439d@news.astraweb.com> <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <56f887c1$0$1598$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56fa2ae1$0$1502$c3e8da3$5496439d@news.astraweb.com> On Monday 28 March 2016 23:18, BartC wrote: > On 28/03/2016 02:24, Steven D'Aprano wrote: >> Don't think about floats and ints and strings. Think of complex objects >> with operator overloading. You're probably thinking of `x + y`. Instead, >> think of things like: >> >> graph + node >> database + table > > There's theory, and there's practice. [...] > So no matter how many potentially useful counter-examples you can dig > up, non-function-call expressions are still going to be highly unusual. > And suspect. Sure. If you want to call it a "code smell", no problem. It's not necessarily bad, but it's worth a second look. > That's why it's not going to be much loss to disallow them /in that form/. When you design your own language :-) feel free to design it that way. Python is designed differently. You don't have to agree with the decision, but that is the decision. The Python interpreter will accept any legal expression, and not try to guess which ones do and don't have side-effects, or which ones might be in error. Expressions include single names, so even they are allowed. If you want stricter rules, use a linter. > (There are also docstrings, but until yesterday I didn't even know they > were also expressions. Wikipedia says this: > > "Python docstrings appear as a string literal (not an expression) as the > first statement following the definition of functions..." > > so their status is a little unclear. I think what Wikipedia means is that you cannot use an expression that evaluates to a string as a docstring: py> def f(): ... "A string %s" % 23 ... py> f.__doc__ is None True It must be a string literal. -- Steve From ben+python at benfinney.id.au Tue Mar 29 03:35:34 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 29 Mar 2016 18:35:34 +1100 Subject: Useless expressions References: <56f42d9f$0$1618$c3e8da3$5496439d@news.astraweb.com> <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <56f887c1$0$1598$c3e8da3$5496439d@news.astraweb.com> <56fa2ae1$0$1502$c3e8da3$5496439d@news.astraweb.com> Message-ID: <851t6tbut5.fsf_-_@benfinney.id.au> Steven D'Aprano writes: > On Monday 28 March 2016 23:18, BartC wrote: > > > (There are also docstrings, but until yesterday I didn't even know > > they were also expressions. Wikipedia says this: > > > > "Python docstrings appear as a string literal (not an expression) as > > the first statement following the definition of functions..." > > > > so their status is a little unclear. Thanks for raising this, Bart. > I think what Wikipedia means is that you cannot use an expression that > evaluates to a string as a docstring I agree. I have edited that section of the article, hopefully it is now clearer: Python The common practice, of documenting a code object at the head of its definition, is captured by the addition of docstring syntax in the Python language. The docstring for a Python code object (a module, class, or function) is the first statement of that code object, immediately following the definition (the 'def' or 'class' statement). The statement must be a bare string literal, not any other kind of expression. The docstring for the code object is available on that code object's '__doc__' attribute. [?] -- \ ?True greatness is measured by how much freedom you give to | `\ others, not by how much you can coerce others to do what you | _o__) want.? ?Larry Wall | Ben Finney From kliateni at gmail.com Tue Mar 29 03:40:41 2016 From: kliateni at gmail.com (Karim) Date: Tue, 29 Mar 2016 09:40:41 +0200 Subject: Re-using TCL code from python over network In-Reply-To: <172d629d-3dc8-4e47-b163-05b4f32a027c@googlegroups.com> References: <172d629d-3dc8-4e47-b163-05b4f32a027c@googlegroups.com> Message-ID: <56FA3179.3080005@gmail.com> On 29/03/2016 07:20, sharad1087 at gmail.com wrote: > Hi > > We've a test automation framework written in TCL (including the automated test cases). We are evaluating shifting to Python and have a test framework in Python (including the automated test cases). Python provides a lot more 3rd party libraries that we'd like to make use of. > > We use a pretty old version of TCL (8.4.5, 32 bit). It's on FreeBSD and we've compiled it in-house. Compiling it to 64 bit or moving to a newer version is a massive task (since we've a lot of libraries - written in C and compiled as well as pure tcl). > > Also, we are evaluating having this Python infrastructure on Linux (CentOS). > > I've explored Python's Tkinter but it won't suit our case as it points to system installed TCL. I've also explored Python's subprocess (launch an interactive TCL shell remotely) and pexpect but none of them worked well for me to allow me to use TCL code interactively from Python. > > I'd like to gather any ideas/experience around this. If anyone has tried a similar stuff before and can share his/her experience, I'd appreciate it. > > Regards > Sharad You can find below a partial example where I launch a python process from a tcl program to get data from python which reads a database. You just have to get and compile tclpython (google is your best friend) which is a C interface bridging python and tcl and allow to launch at most 5 python interpreter processes if I remember correctly. I used it during 4 years but I now I migrated all the TCL code to python one indeed I don't need it anymore. But it is useful to do the transition. #!/usr/bin/env tclsh8.4 lappend auto_path $env(TCLPYTHON_PKG_PATH) package require tclpython 4.1 namespace eval ops { namespace export initPython namespace export exitPython ... namespace export getDeviceDescription .... } proc ops::initPython {} { # ---------------------------- # @goal: Create the interpreter process and import python needed modules. # @arg: # @return: # ---------------------------- variable interpreter set interpreter [python::interp new] $interpreter exec {from ops.tcl.pythontcl import to_string, to_list, to_dict, to_bool} .... $interpreter exec "opsdb = None" $interpreter exec "input_structure = dict()" } proc ops::exitPython {} { # ---------------------------- # @goal: Close the interpreter process. # @arg: # @return: # ---------------------------- variable interpreter python::interp delete $interpreter } proc ops::getDeviceDescription { libName deviceName } { # ---------------------------- # @goal: get # @arg: # @return: # ---------------------------- variable interpreter $interpreter exec "d_s = to_string(getDeviceDescription(opsdb, '$libName', '$deviceName'))" eval "set value [$interpreter eval {d_s}]" return $value } Karim From nickle at gmail.com Tue Mar 29 04:06:30 2016 From: nickle at gmail.com (Nick) Date: Tue, 29 Mar 2016 01:06:30 -0700 (PDT) Subject: Meta Data In-Reply-To: References: Message-ID: <47e86468-6179-46dd-bc4f-4de12dd77cf5@googlegroups.com> I did find a couple of patterns in Effective Python: 59 Specific Ways to Write Better Python (Effective Software Development). Registering classes and a field example. Thanks N. From steve+comp.lang.python at pearwood.info Tue Mar 29 04:26:14 2016 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 29 Mar 2016 19:26:14 +1100 Subject: Statements as expressions [was Re: Undefined behaviour in C] References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> <87h9fr5qig.fsf@nightsong.com> Message-ID: <56fa3c2a$0$1591$c3e8da3$5496439d@news.astraweb.com> On Monday 28 March 2016 12:40, Paul Rubin wrote: > Steven D'Aprano writes: >> if condition: >> print(1) >> print(2) >> else: >> print(3) >> print(4) >> what value should it return? Justify your choice. > > It could whatever value that the last call to print() returns. Lisp > has worked like that since the 1950's. "Lisp did it" isn't much of a justification. The point is that sticking a return value onto a conditional branch with two blocks is rather arbitrary. Why return the last value rather than the first? Why not return a list of all the values generated in the block? Or True/False depending on which branch was taken? Or for that matter, a random number? The point is that there's nothing intrinsically obvious or right about "return the value of the last statement in the block". >> What should be the return value of this statement? >> >> while True: >> x += 1 >> if condition: break > > It could return None, or break(val) could return val. Another arbitrary choice. It *could* return anything. But what *should* it return? An expression naturally and intrinsically should return the value the expression calculates. This is such a no-brainer that I feel stupid even writing it: "x+1" should return "x+1". It would be crazy to pick something else. But a statement is a statement because it doesn't have a return value. To give it one, we have to more-or-less arbitrarily force it to have one, but that doesn't make it terribly natural. del x Should it return None? The string 'x'? How about the value that x had just before it was deleted? True if that allowed the value to be garbage collected, False if it wasn't? Or the other way around? None of these suggests feel either useful or obviously right. >> I don't think that "every statement is an expression" is conceptually >> simpler at all. I think it is more difficult to understand. > > It hasn't been a problem in Lisp or its descendants, Erlang, Haskell, > etc. I don't know about Ruby or Javascript. Maybe, maybe not. But certain statements, at least, are definitely a problem in C/C++ : int war = false; if(war = true) { launchnuke(); } The way I see it, all expressions are meaningful as statements (although possibly not terribly useful if they don't have side-effects) but not all statements are meaningful as expressions. If other languages choose differently, well, that's their right to do so, but I don't agree with their choice. On the other hand, I am tempted by the thought of a language where all statements return 42. >> But it is even harder to understand what it might mean for a while >> loop to be a value, and the benefit of doing so seems significantly >> less than compelling. > > It means that you get to use an incredibly simple and beautiful > evaluation model. Have you ever used Lisp or Scheme? Give it a try > sometime. Excellent free book: > https://mitpress.mit.edu/sicp/full-text/book/book.html I've tried to get into Lisp a couple of times, and it doesn't speak to me. If you want my opinion, Forth has a more natural evaluation model. -- Steve From smith at a-team.it Tue Mar 29 04:29:21 2016 From: smith at a-team.it (Smith) Date: Tue, 29 Mar 2016 10:29:21 +0200 Subject: Help me Message-ID: https://github.com/githubdavide/ip-pubblico-send/blob/master/ip-pubblico.py From sharad1087 at gmail.com Tue Mar 29 04:29:26 2016 From: sharad1087 at gmail.com (Sharad Singla) Date: Tue, 29 Mar 2016 04:29:26 -0400 Subject: Re-using TCL code from python over network In-Reply-To: <56FA3179.3080005@gmail.com> References: <172d629d-3dc8-4e47-b163-05b4f32a027c@googlegroups.com> <56FA3179.3080005@gmail.com> Message-ID: Thanks. This is more of invoking python code from TCL. I am looking for the other way round. Curious, did you rewrite all your TCL code in python? Regards Sharad On Mar 29, 2016 1:10 PM, "Karim" wrote: > > > On 29/03/2016 07:20, sharad1087 at gmail.com wrote: > >> Hi >> >> We've a test automation framework written in TCL (including the automated >> test cases). We are evaluating shifting to Python and have a test framework >> in Python (including the automated test cases). Python provides a lot more >> 3rd party libraries that we'd like to make use of. >> >> We use a pretty old version of TCL (8.4.5, 32 bit). It's on FreeBSD and >> we've compiled it in-house. Compiling it to 64 bit or moving to a newer >> version is a massive task (since we've a lot of libraries - written in C >> and compiled as well as pure tcl). >> >> Also, we are evaluating having this Python infrastructure on Linux >> (CentOS). >> >> I've explored Python's Tkinter but it won't suit our case as it points to >> system installed TCL. I've also explored Python's subprocess (launch an >> interactive TCL shell remotely) and pexpect but none of them worked well >> for me to allow me to use TCL code interactively from Python. >> >> I'd like to gather any ideas/experience around this. If anyone has tried >> a similar stuff before and can share his/her experience, I'd appreciate it. >> >> Regards >> Sharad >> > > You can find below a partial example where I launch a python process from > a tcl program to get data from python > which reads a database. You just have to get and compile tclpython (google > is your best friend) which is a C interface > bridging python and tcl and allow to launch at most 5 python interpreter > processes if I remember correctly. I used it during 4 > years but I now I migrated all the TCL code to python one indeed I don't > need it anymore. But it is useful to do the transition. > > #!/usr/bin/env tclsh8.4 > > lappend auto_path $env(TCLPYTHON_PKG_PATH) > package require tclpython 4.1 > > namespace eval ops { > namespace export initPython > namespace export exitPython > ... > namespace export getDeviceDescription > > .... > } > > proc ops::initPython {} { > # ---------------------------- > # @goal: Create the interpreter process and import python needed modules. > # @arg: > # @return: > # ---------------------------- > variable interpreter > set interpreter [python::interp new] > $interpreter exec {from ops.tcl.pythontcl import to_string, > to_list, to_dict, to_bool} > .... > $interpreter exec "opsdb = None" > $interpreter exec "input_structure = dict()" > } > > proc ops::exitPython {} { > # ---------------------------- > # @goal: Close the interpreter process. > # @arg: > # @return: > # ---------------------------- > variable interpreter > python::interp delete $interpreter > } > > proc ops::getDeviceDescription { libName deviceName } { > # ---------------------------- > # @goal: get > # @arg: > # @return: > # ---------------------------- > variable interpreter > $interpreter exec "d_s = to_string(getDeviceDescription(opsdb, > '$libName', '$deviceName'))" > > eval "set value [$interpreter eval {d_s}]" > return $value > } > > Karim > > > From sharad1087 at gmail.com Tue Mar 29 04:37:34 2016 From: sharad1087 at gmail.com (sharad1087 at gmail.com) Date: Tue, 29 Mar 2016 01:37:34 -0700 (PDT) Subject: Re-using TCL code from python over network In-Reply-To: <172d629d-3dc8-4e47-b163-05b4f32a027c@googlegroups.com> References: <172d629d-3dc8-4e47-b163-05b4f32a027c@googlegroups.com> Message-ID: <6dd9aa00-1667-4d96-ae1e-953b8ddaca46@googlegroups.com> @Christian: Thanks! @Karim: Thanks. My requirement is to run tcl code from python. tclpython allows executing python code from tcl. "but I now I migrated all the TCL code to python one indeed" - did you re-write the TCL code in Python? From tonycamgar at gmail.com Tue Mar 29 04:43:50 2016 From: tonycamgar at gmail.com (Antonio Caminero Garcia) Date: Tue, 29 Mar 2016 01:43:50 -0700 (PDT) Subject: repeat items in a list In-Reply-To: References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> Message-ID: On Monday, March 28, 2016 at 11:26:08 PM UTC+2, Chris Angelico wrote: > On Tue, Mar 29, 2016 at 4:30 AM, Rob Gaddi > wrote: > > beliavsky at aol.com wrote: > > > >> On Saturday, March 26, 2016 at 7:24:10 PM UTC-4, Erik wrote: > >>> > >>> Or, if you want to "import operator" first, you can use 'operator.add' > >>> instead of the lambda (but you _did_ ask for a one-liner ;)). > >>> > >>> Out of interest, why the fascination with one-liners? > >> > >> Thanks for your reply. Sometimes when I program in Python I think I am not using the full capabilities of the language, so I want to know if there are > >> more concise ways of doing things. > > > > Concise is only worth so much. PEP20 tells us "Explicit is better than > > implicit", "Simple is better than complex" and "If the implementation is > > hard to explain, it's a bad idea". > > > > Python is a beautifully expressive language. Your goal should not be to > > write the minimum number of lines of code to accomplish the task. > > Your goal should be to write the code such that your grandmother can > > understand it. That way, when you screw it up, you'll be able to easily > > figure out where and how you did so. Or failing that, you can get > > grangran to show you. > > Just out of interest, did you (generic you) happen to notice Mark's > suggestion? It's a one-liner that nicely expresses the intention and > accomplishes the goal: > > yy = [aa for aa in xx for _ in range(nrep)] > > It quietly went through without fanfare, but I would say this is the > perfect solution to the original problem. > > ChrisA Of course that's definitely the most pythonic sol to this prob :)! Just wanted to point out the use of the operator "*" in lists. From no.email at nospam.invalid Tue Mar 29 04:54:24 2016 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 29 Mar 2016 01:54:24 -0700 Subject: Statements as expressions [was Re: Undefined behaviour in C] References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> <87h9fr5qig.fsf@nightsong.com> <56fa3c2a$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87r3et4qbj.fsf@nightsong.com> Steven D'Aprano writes: > The point is that there's nothing intrinsically obvious or right about > "return the value of the last statement in the block". Strictly speaking it returns the value of the block itself. The block is usually evaluated by PROG which returns the last value of the block, but you could also use PROG1 which uses the first value, or PROG2 which uses the second value. > I've tried to get into Lisp a couple of times, and it doesn't speak to me. > If you want my opinion, Forth has a more natural evaluation model. You might like Factor then, www.factorcode.org . From rosuav at gmail.com Tue Mar 29 05:09:39 2016 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 29 Mar 2016 20:09:39 +1100 Subject: Statements as expressions [was Re: Undefined behaviour in C] In-Reply-To: <56fa3c2a$0$1591$c3e8da3$5496439d@news.astraweb.com> References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> <87h9fr5qig.fsf@nightsong.com> <56fa3c2a$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Mar 29, 2016 at 7:26 PM, Steven D'Aprano wrote: > del x > > Should it return None? The string 'x'? How about the value that x had just > before it was deleted? True if that allowed the value to be garbage > collected, False if it wasn't? Or the other way around? None of these > suggests feel either useful or obviously right. Returning the value x had just before being deleted is certainly useful - consider the case where x is not a simple name but a subscripting, which makes this into a destructive lookup. Saying whether the object was garbage collected or not could also be useful, but feels very low level. But if Python were to make 'del' into an expression, the only semantics needed would be for simple names. For everything else, the value of 'del x[y]' or 'del x.y' would simply be 'whatever __delitem__/__delattr__ returns'. And even for simple names, the semantics could be defined by the enclosing scope's dictionary. It'd be like Python's operators; yes, you normally expect "x < y" to return a truthy or falsy value, and for most built-in types it'll return either True or False, but you can return anything at all - including a lazy evaluation object for a DSL. Someone could, for instance, make "del User[42]" return a Query object which, when executed, deletes the user with primary key 42. (Note: I am not advocating this. Just saying what would, IMO, be consistent with the rest of Python.) ChrisA From ben+python at benfinney.id.au Tue Mar 29 05:17:02 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 29 Mar 2016 20:17:02 +1100 Subject: Help me References: Message-ID: <85wpolabjl.fsf@benfinney.id.au> Smith writes: > [a URL] You'll get better help if you: * Summarise the problem briefly in the Subject field. * Actually say anything useful in the message body. -- \ ?My house is on the median strip of a highway. You don't really | `\ notice, except I have to leave the driveway doing 60 MPH.? | _o__) ?Steven Wright | Ben Finney From marko at pacujo.net Tue Mar 29 05:23:21 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Tue, 29 Mar 2016 12:23:21 +0300 Subject: Statements as expressions [was Re: Undefined behaviour in C] References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> <87h9fr5qig.fsf@nightsong.com> <56fa3c2a$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87egatmyd2.fsf@elektro.pacujo.net> Steven D'Aprano : > On Monday 28 March 2016 12:40, Paul Rubin wrote: > >> Steven D'Aprano writes: >>> if condition: >>> print(1) >>> print(2) >>> else: >>> print(3) >>> print(4) >>> what value should it return? Justify your choice. >> >> It could whatever value that the last call to print() returns. Lisp >> has worked like that since the 1950's. > > "Lisp did it" isn't much of a justification. Actually, it would be in my books. However, Scheme (a Lisp dialect) also has statements that don't return any particular value. The (if) happens to be an example. Thus, (set! x (if #f 3)) Assigns *some* value to x, but the language leaves it open what that value might be. Guile (a Scheme implementation) actually provides a distinct "unspecified" value, which it uses in cases where the language standard leaves the value unspecified. > The point is that there's nothing intrinsically obvious or right about > "return the value of the last statement in the block". No, but the semantics of a functional language become simpler when you can assume that every continuation operates on a value. Consequently, every function in Python returns a value as does every function in Perl and every command in bash. > I've tried to get into Lisp a couple of times, and it doesn't speak to > me. If you want my opinion, Forth has a more natural evaluation model. Forth, too, has nice, simple semantics. Forth has nothing but statements that operate on the stack and occasionally cause some side effects. Here's an example of how Python benefits from the functional model: decorators. You can use the same decorators both for proper functions and for procedures that ostensibly don't return a value. Python has defined "None" to be the default return value for procedures so it is legal to say, a = f() even if f doesn't return a value. Unfortunately, Python made a bit of a bad choice in the default return value. Now Python cannot perform effective tail recursion elimination. If Python had left the default unspecified, tail recursion elimination would be simple. Python's choice benefits the interactive console, which doesn't print out None values. Marko From srkunze at mail.de Tue Mar 29 05:37:46 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Tue, 29 Mar 2016 11:37:46 +0200 Subject: Which are best, well-tested ways to create REST services, with Json, in Python? In-Reply-To: <496157280.2274927.1459199176427.JavaMail.yahoo@mail.yahoo.com> References: <496157280.2274927.1459199176427.JavaMail.yahoo.ref@mail.yahoo.com> <496157280.2274927.1459199176427.JavaMail.yahoo@mail.yahoo.com> Message-ID: <56FA4CEA.3040809@mail.de> Not heard of any but I can recommend django-restframework. We've got good experience with that. On 28.03.2016 23:06, David Shi via Python-list wrote: > Has anyone done a recent reviews of creating REST services, in Python? > Regards. > David From __peter__ at web.de Tue Mar 29 05:39:35 2016 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Mar 2016 11:39:35 +0200 Subject: [OT] C# -- sharp or carp? was Re: Learning Python (or Haskell) makes you a worse programmer References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > http://lukeplant.me.uk/blog/posts/why-learning-haskell-python-makes-you-a-worse-programmer/ I was about to post that in a few years' time C# will acquire enough features to make code that follows the functional paradigm feasible in that language. Then I noted that this was the 10th anniversary repost ;) My question to those who know a bit of C#: what is the state-of-the-art equivalent to "\n".join(foo.description() for foo in mylist if foo.description() != "") From srkunze at mail.de Tue Mar 29 06:05:51 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Tue, 29 Mar 2016 12:05:51 +0200 Subject: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: <56FA00EC.80909@gmail.com> References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA00EC.80909@gmail.com> Message-ID: <56FA537F.9090506@mail.de> On 29.03.2016 06:13, Michael Torrie wrote: > On 03/28/2016 06:44 PM, Steven D'Aprano wrote: >> http://lukeplant.me.uk/blog/posts/why-learning-haskell-python-makes-you-a-worse-programmer/ > I have the same problem as the writer. Working in Python makes me > really dislike working in any other language! > Python = English :) From srkunze at mail.de Tue Mar 29 06:18:02 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Tue, 29 Mar 2016 12:18:02 +0200 Subject: [OT] C# -- sharp or carp? was Re: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56FA565A.9020800@mail.de> On 29.03.2016 11:39, Peter Otten wrote: > My question to those who know a bit of C#: what is the state-of-the-art > equivalent to > > "\n".join(foo.description() for foo in mylist > if foo.description() != "") > Using LINQ, I suppose: https://en.wikipedia.org/wiki/Language_Integrated_Query From srkunze at mail.de Tue Mar 29 06:23:39 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Tue, 29 Mar 2016 12:23:39 +0200 Subject: newbie question In-Reply-To: <56f94f18$0$3314$426a34cc@news.free.fr> References: <56f3c3eb$0$4546$426a74cc@news.free.fr> <56F3CB1E.2000606@mail.de> <56f94f18$0$3314$426a34cc@news.free.fr> Message-ID: <56FA57AB.30502@mail.de> On 28.03.2016 17:34, ast wrote: > > "Matt Wheeler" a ?crit dans le message de > news:mailman.92.1458825746.2244.python-list at python.org... >> On Thu, 24 Mar 2016 11:10 Sven R. Kunze, wrote: >> >>> On 24.03.2016 11:57, Matt Wheeler wrote: >>> >>>> import ast >>> >>>> s = "(1, 2, 3, 4)" >>> >>>> t = ast.literal_eval(s) >>> >>>> t >>> > (1, 2, 3, 4) >>> >>> I suppose that's the better solution in terms of safety. >>> >> >> It has the added advantage that the enquirer gets to import a module >> that >> shares their name ;) > > > I had a look at that "ast" module doc, but I must admit that > I didn't understood a lot of things. If there were a module "srkunze", I think, I would be equally surprised. ;) Best, Sven From kliateni at gmail.com Tue Mar 29 06:24:20 2016 From: kliateni at gmail.com (Karim) Date: Tue, 29 Mar 2016 12:24:20 +0200 Subject: Re-using TCL code from python over network In-Reply-To: References: <172d629d-3dc8-4e47-b163-05b4f32a027c@googlegroups.com> <56FA3179.3080005@gmail.com> Message-ID: <56FA57D4.3060802@gmail.com> On 29/03/2016 10:29, Sharad Singla wrote: > > Thanks. This is more of invoking python code from TCL. I am looking > for the other way round. > > Curious, did you rewrite all your TCL code in python? > > Regards > Sharad > > On Mar 29, 2016 1:10 PM, "Karim" > wrote: > > > > On 29/03/2016 07:20, sharad1087 at gmail.com > wrote: > > Hi > > We've a test automation framework written in TCL (including > the automated test cases). We are evaluating shifting to > Python and have a test framework in Python (including the > automated test cases). Python provides a lot more 3rd party > libraries that we'd like to make use of. > > We use a pretty old version of TCL (8.4.5, 32 bit). It's on > FreeBSD and we've compiled it in-house. Compiling it to 64 bit > or moving to a newer version is a massive task (since we've a > lot of libraries - written in C and compiled as well as pure tcl). > > Also, we are evaluating having this Python infrastructure on > Linux (CentOS). > > I've explored Python's Tkinter but it won't suit our case as > it points to system installed TCL. I've also explored Python's > subprocess (launch an interactive TCL shell remotely) and > pexpect but none of them worked well for me to allow me to use > TCL code interactively from Python. > > I'd like to gather any ideas/experience around this. If anyone > has tried a similar stuff before and can share his/her > experience, I'd appreciate it. > > Regards > Sharad > > > You can find below a partial example where I launch a python > process from a tcl program to get data from python > which reads a database. You just have to get and compile tclpython > (google is your best friend) which is a C interface > bridging python and tcl and allow to launch at most 5 python > interpreter processes if I remember correctly. I used it during 4 > years but I now I migrated all the TCL code to python one indeed I > don't need it anymore. But it is useful to do the transition. > > #!/usr/bin/env tclsh8.4 > > lappend auto_path $env(TCLPYTHON_PKG_PATH) > package require tclpython 4.1 > > namespace eval ops { > namespace export initPython > namespace export exitPython > ... > namespace export getDeviceDescription > > .... > } > > proc ops::initPython {} { > # ---------------------------- > # @goal: Create the interpreter process and import python needed > modules. > # @arg: > # @return: > # ---------------------------- > variable interpreter > set interpreter [python::interp new] > $interpreter exec {from ops.tcl.pythontcl import > to_string, to_list, to_dict, to_bool} > .... > $interpreter exec "opsdb = None" > $interpreter exec "input_structure = dict()" > } > > proc ops::exitPython {} { > # ---------------------------- > # @goal: Close the interpreter process. > # @arg: > # @return: > # ---------------------------- > variable interpreter > python::interp delete $interpreter > } > > proc ops::getDeviceDescription { libName deviceName } { > # ---------------------------- > # @goal: get > # @arg: > # @return: > # ---------------------------- > variable interpreter > $interpreter exec "d_s = to_string(getDeviceDescription(opsdb, > '$libName', '$deviceName'))" > > eval "set value [$interpreter eval {d_s}]" > return $value > } > > Karim > > Yes, part by part. In fact it was faster than expected thanks to python syntax. TCL coding is heavier than python equivalent. I say that by experience. My project involved 2 developers one pro TCL and myself pro Python. We found the best deal for both. Now I am alone. This is the reason everything is now python. But it was a good experience to learn TCL (weaknesses). Karim From srkunze at mail.de Tue Mar 29 06:26:56 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Tue, 29 Mar 2016 12:26:56 +0200 Subject: Threading is foobared? In-Reply-To: <56f74d00$0$1620$c3e8da3$5496439d@news.astraweb.com> References: <56f74d00$0$1620$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56FA5870.7060003@mail.de> On 27.03.2016 05:01, Steven D'Aprano wrote: > Am I the only one who has noticed that threading of posts here is severely > broken? It's always been the case that there have been a few posts here and > there that break threading, but now it seems to be much more common. I agree. Didn't we both already have a conversation about this? I thought it is my thunderbird messing things up. Best, Sven From auriocus at gmx.de Tue Mar 29 07:18:02 2016 From: auriocus at gmx.de (Christian Gollwitzer) Date: Tue, 29 Mar 2016 13:18:02 +0200 Subject: Re-using TCL code from python over network In-Reply-To: References: <172d629d-3dc8-4e47-b163-05b4f32a027c@googlegroups.com> Message-ID: Am 29.03.16 um 09:40 schrieb Karim: > You can find below a partial example where I launch a python process > from a tcl program to get data from python > which reads a database. You just have to get and compile tclpython > (google is your best friend) which is a C interface > bridging python and tcl and allow to launch at most 5 python interpreter > processes if I remember correctly. tclpython embeds a Python interpreter into Tcl as a module. Therefire, this will only work, if Tcl and Python use the same machine language (i.e. 32bit or 64bit) and run on the same machine. I understood from the OP, that he wants to run Tcl in 32 bit mode, and connect to it from Python running 64 bit on a different machine. Therefore, only a true networked solution will work. However if he can manage to get both into the same process, this will be a lot easier, as outlined by your solution. Christian From bc at freeuk.com Tue Mar 29 07:31:51 2016 From: bc at freeuk.com (BartC) Date: Tue, 29 Mar 2016 12:31:51 +0100 Subject: Statements as expressions [was Re: Undefined behaviour in C] In-Reply-To: <56fa3c2a$0$1591$c3e8da3$5496439d@news.astraweb.com> References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> <87h9fr5qig.fsf@nightsong.com> <56fa3c2a$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 29/03/2016 09:26, Steven D'Aprano wrote: > On Monday 28 March 2016 12:40, Paul Rubin wrote: > The point is that there's nothing intrinsically obvious or right about > "return the value of the last statement in the block". But that's exactly what happens inside a typical function: you have linear sequence of statements, then you a have return statement: at the end. It's a common pattern. >>> while True: >>> x += 1 >>> if condition: break >> >> It could return None, or break(val) could return val. > > Another arbitrary choice. It *could* return anything. But what *should* it > return? It's up to you. Write it like this (not valid Python): while True: x+=1; if c: break; y Now this is two statement, the loop, and 'y'. We now have a block, and because of the block rule, the value is y. > An expression naturally and intrinsically should return the value the > expression calculates. This is such a no-brainer that I feel stupid even > writing it: "x+1" should return "x+1". It would be crazy to pick something > else. (This is in contradiction to what you say elsewhere, where: graph + node may be procedural.) > But a statement is a statement because it doesn't have a return value. Isn't an expression technically a statement in Python? Therefore a statement could have a value. But take this example: if cond1: x=a1 elif cond2: x=a2 elif cond3: x=a3 else: x=a4 Clearly this would be better expressed as (not valid Python): x = if cond1: a1 elif cond2: a2 elif cond3: a3 else: a4 So some kinds of statements could conceivably yield a useful value. (And each a1, a2 here could be a block or other statement yielding a value.) > To > give it one, we have to more-or-less arbitrarily force it to have one, but > that doesn't make it terribly natural. > > del x > > Should it return None? The string 'x'? How about the value that x had just > before it was deleted? (Actually 'del is a rather odd language feature. And I can't figure out how it's implemented; how does it manage 'del x[i]'? Anyway that's another matter.) > True if that allowed the value to be garbage > collected, False if it wasn't? Or the other way around? None of these > suggests feel either useful or obviously right. It doesn't need to give a useful value. Its 'value' lies in being able to have it in a sequence or block: z = del x; y > The way I see it, all expressions are meaningful as statements (although > possibly not terribly useful if they don't have side-effects) but not all > statements are meaningful as expressions. Yes. But some are. To list a few statements that could return values (some are not part of Python): - If-elif-else - Switch and case select statements - Block - Increment - Subroutine call - Assignment The rest can still usefully appear in a block. Python has a version of if-else that appears in an expression, but it has function-call. But why stop there? Anyway this is all hypothetical, in case anyone thinks I'm pushing for a change in the language. I thought such a language was cool in the 1980s, but now will settle for a more conservative one even if it's not so elegant. -- bartc From rustompmody at gmail.com Tue Mar 29 09:28:30 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 29 Mar 2016 06:28:30 -0700 (PDT) Subject: DSL design (was DSLs in perl and python) In-Reply-To: <21d252f4-c6a8-4241-88e4-c5f492ebb835@googlegroups.com> References: <7f139f92-3957-40e5-be75-ad19b9401617@googlegroups.com> <21d252f4-c6a8-4241-88e4-c5f492ebb835@googlegroups.com> Message-ID: On Saturday, March 19, 2016 at 7:37:52 AM UTC+5:30, Rustom Mody wrote: > On Friday, March 18, 2016 at 6:52:53 PM UTC+5:30, Peter Otten wrote: > > Rustom Mody wrote: > > > > > On Friday, March 18, 2016 at 4:17:06 AM UTC+5:30, MRAB wrote: > > >> Stick an "x" on the end of the regex: /something/x or s/old/new/x. > > > > > > Thanks! > > > > > > Is there somewhere a regexp 'introspection' API/capability available? > > > > > > ie if the re looks like > > > rexp = r""" > > > # DSL (instantiation) for describing NYSE symbology > > > ^ > > > (?P [A-Z]*) # The base scrip > > > (?P [.+-])? # Series type char > > > (?P [A-Z])? # Series > > > (?P [#])? # issued char indicator > > > $ # Thats all (there should be!) > > > """ > > > > > > I would like to know that the named-groups are > > > {scrip, serchar, series, issued} > > > without doing match/search etc > > > > Is that a Perl or a Python question? If the latter: > > > > >>> r = re.compile(rexp, re.VERBOSE) > > >>> r.groupindex > > {'serchar': 2, 'issuedc': 4, 'scrip': 1, 'series': 3} > > Neat Thanks (and Jussi) Thanks once again to Peter and Jussi. With that groupindex pointer, this tiny dsl for re's is here https://github.com/rusimody/redsl [How BTW did you folks go about unearth that groupindex?? Dont see it in docs] Comments welcome. If people have comments on the python thats fine -- specifically if something does not work, is unclear etc. I am however more specifically interested in the DSL-design -- Can one clean/spruce that up? From rosuav at gmail.com Tue Mar 29 09:41:15 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 30 Mar 2016 00:41:15 +1100 Subject: DSL design (was DSLs in perl and python) In-Reply-To: References: <7f139f92-3957-40e5-be75-ad19b9401617@googlegroups.com> <21d252f4-c6a8-4241-88e4-c5f492ebb835@googlegroups.com> Message-ID: On Wed, Mar 30, 2016 at 12:28 AM, Rustom Mody wrote: > Thanks once again to Peter and Jussi. > With that groupindex pointer, this tiny dsl for re's is here > https://github.com/rusimody/redsl > [How BTW did you folks go about unearth that groupindex?? Dont see it in docs] Depending on your version: https://docs.python.org/2/library/re.html#re.RegexObject.groupindex https://docs.python.org/3/library/re.html#re.regex.groupindex You can find that by searching the docs for "?P", the syntax used in the RE itself. ChrisA From srkunze at mail.de Tue Mar 29 09:45:07 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Tue, 29 Mar 2016 15:45:07 +0200 Subject: Exclude every nth element from list? In-Reply-To: References: <94237154-22af-4e64-85ee-9b4cf334fa6f@googlegroups.com> Message-ID: <56FA86E3.5090408@mail.de> On 26.03.2016 18:06, Peter Otten wrote: > beliavsky--- via Python-list wrote: > >> I can use x[::n] to select every nth element of a list. Is there a >> one-liner to get a list that excludes every nth element? > del x[::n] > > ;) Actually quite nice. From jussi.piitulainen at helsinki.fi Tue Mar 29 09:45:20 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Tue, 29 Mar 2016 16:45:20 +0300 Subject: DSL design (was DSLs in perl and python) References: <7f139f92-3957-40e5-be75-ad19b9401617@googlegroups.com> <21d252f4-c6a8-4241-88e4-c5f492ebb835@googlegroups.com> Message-ID: Rustom Mody writes: > [How BTW did you folks go about unearth that groupindex?? Dont see it > in docs] The following reveal its existence: dir(re.compile("")) help(re.compile("")) But help only lists it as one of "data descriptors defined here" (in Python 3.4.3). I think I just guessed from its name that it might be relevant, and trying it out didn't immediately contradict the guess :) From __peter__ at web.de Tue Mar 29 09:51:40 2016 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Mar 2016 15:51:40 +0200 Subject: Finding methods, was Re: DSL design (was DSLs in perl and python) References: <7f139f92-3957-40e5-be75-ad19b9401617@googlegroups.com> <21d252f4-c6a8-4241-88e4-c5f492ebb835@googlegroups.com> Message-ID: Rustom Mody wrote: > [How BTW did you folks go about unearth that groupindex?? Dont see it in > [docs] While it's there https://docs.python.org/dev/library/re.html#re.regex.groupindex my personal search algorithm for this category of questions is mostly "I saw something like that before", then dir(some_obj) to find the candidates, then try the candidates in order of likelihood. If that fails use the source. While you learn things you weren't looking for the disadvantage of that approach is that you sometimes miss the "obvious, first hit given by the search engine" answer. From antoon.pardon at rece.vub.ac.be Tue Mar 29 10:08:49 2016 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Tue, 29 Mar 2016 16:08:49 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56FA8C71.4050306@rece.vub.ac.be> Op 28-03-16 om 03:05 schreef Steven D'Aprano: > On Mon, 28 Mar 2016 05:01 am, Marco S. wrote: > >> Steven D'Aprano wrote: >> >>> The point you might have missed is that treating lists as if they were >>> mappings violates at least one critical property of mappings: that the >>> relationship between keys and values are stable. >> >> This is true for immutable maps, but for mutable ones, you can simply do > No, it is true for mutable maps too. > > When you add a new key:value to a dict, the other key:value pairs don't > change. That is the whole point of a mapping! Of course you can > deliberately change the value by re-assignment: > > map[key] = new_value > > but that's not what I'm talking about. When you add a NEW key, the OTHER > keys DON'T change. That is ABSOLUTELY CRITICAL to a mapping. Anything which > lacks that property is not a mapping. I'm not sure I agree with that. > The relationship between the index of a value and the value in a sequence is > not stable. Inserting a new value can change the "key"(actually index) of > some or all of the existing values. Which is not simply adding a key. Inserting a new value is IMO more like doing an update. > The whole point of sequences is that > the position of values is NOT stable: they are intended to move around. I find that language too strong. The lists I use are generally stable. Does that mean I'm using lists in a way not intended. > You > can sort them, reverse them, delete them, insert new values, and the others > will move around to make room. If you think of the index as a key, this is > completely the opposite behaviour of mappings. Not really. IMO a mapping is just a surjective function and sometimes a list is a perfectly fine way to implement such a function. The point I think the OP tries to make is that sometimes you need to write a function that takes a surjective function as argument and produces some result, but you just don't care whether this function is implemented as a map or as a sequence. Suppose you want to know how many times each value occurs and want to map that. As it is you have to write something like the following. def count(l): counted = defaultdict(int) try: itr = l.values() except AttributeError: itr = iter(l) for v in itr: counted[v] += 1 return counted What would be the big problem if a values method would be available on a list which returned the iterator and if an items method would be like calling enumerate? From nathrcamargo1 at hotmail.com Tue Mar 29 10:11:44 2016 From: nathrcamargo1 at hotmail.com (natalia camargo) Date: Tue, 29 Mar 2016 11:11:44 -0300 Subject: =?utf-8?Q?Instala=C3=A7=C3=A3o?= Message-ID: N?o consigo instalar o python no meu Windows,gostaria de alguma ajuda ou esclarecimento Enviado do Email para Windows 10 From rosuav at gmail.com Tue Mar 29 10:31:32 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 30 Mar 2016 01:31:32 +1100 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56FA8C71.4050306@rece.vub.ac.be> References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> Message-ID: On Wed, Mar 30, 2016 at 1:08 AM, Antoon Pardon wrote: > Op 28-03-16 om 03:05 schreef Steven D'Aprano: >> When you add a new key:value to a dict, the other key:value pairs don't >> change. That is the whole point of a mapping! Of course you can >> deliberately change the value by re-assignment: >> >> map[key] = new_value >> >> but that's not what I'm talking about. When you add a NEW key, the OTHER >> keys DON'T change. That is ABSOLUTELY CRITICAL to a mapping. Anything which >> lacks that property is not a mapping. > > I'm not sure I agree with that. I am. The similarity between "mapping with integers as keys" and "sequence" is that both of them can be subscripted. And that's fine; Python lets you define __getitem__ in any way you like. OrderedDict is somewhere between "sequence with associated keys" and "mapping with inherent order", and there's no problem with that. But the definition of a sequence, and likewise the definition of a mapping, goes deeper than that. A sequence has *relative* stability; if one item is at a lower index than another, it will continue to be at a lower index, until you change one of those two items. Changes elsewhere in the sequence might bring them closer together or push them further apart, but one of them is still earlier in the sequence than the other. A mapping, on the other hand, has *absolute* stability. Any given key->value relationship is stable in and of itself. If you stuff a thing into a dict under a particular key, you expect to be able to get it back using that key, not some other. Sure, you can use a tuple to represent an immutable mapping between dense integers and values. And there are times when that's perfectly acceptable - here's two ways of depicting the month lengths in a non-leap year in the Gregorian calendar: mapping = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31} sequence = (None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) Both of them let you look up 6 and get back that June has 30 days. The sequence is forced to start from zero, but that's a small matter (and if you number your months 0-11 instead of 1-12, no difference at all). But the only operation these two data types truly share is subscripting. If you want to be able to iterate over these in calendar order, you don't switch out the dict for an OrderedDict - you use the tuple. If you want to be able to use month names instead of numbers, you don't mess around with the tuple - you use the dict. The whole idea of making sequences and mappings more similar is highly distasteful to me, and I've figured out why. It's the exact problem with the PHP array - it's not sure whether to act as a mapping or a sequence, and standard library functions can behave oddly in the presence of all-numeric keys that aren't intended to be a sequence. The two types are fundamentally different, and you almost never want to treat them identically - at best, you want to have one specific function that handles either type, and that's most cleanly handled inside that function, not by adding mapping-like features to sequences or vice versa. ChrisA From sharad1087 at gmail.com Tue Mar 29 11:02:32 2016 From: sharad1087 at gmail.com (sharad1087 at gmail.com) Date: Tue, 29 Mar 2016 08:02:32 -0700 (PDT) Subject: Re-using TCL code from python over network In-Reply-To: References: <172d629d-3dc8-4e47-b163-05b4f32a027c@googlegroups.com> Message-ID: <1caef003-c07e-4c5b-bc43-6337f67bae84@googlegroups.com> Thanks Christian. You are right. Our TCL is 32 bit and runs on FreeBSD. We are planning to use Python (64 bit) on CentOS. From srkunze at mail.de Tue Mar 29 11:41:34 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Tue, 29 Mar 2016 17:41:34 +0200 Subject: [OT] C# -- sharp or carp? was Re: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: <56FA565A.9020800@mail.de> References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA565A.9020800@mail.de> Message-ID: <56FAA22E.3040805@mail.de> On 29.03.2016 12:18, Sven R. Kunze wrote: > On 29.03.2016 11:39, Peter Otten wrote: >> My question to those who know a bit of C#: what is the state-of-the-art >> equivalent to >> >> "\n".join(foo.description() for foo in mylist >> if foo.description() != "") >> > > Using LINQ, I suppose: > https://en.wikipedia.org/wiki/Language_Integrated_Query Friend of mine told me something like this: String.Join("\n", mylist.Where(foo => !String.IsNullOrEmpty(foo.description)).Select(foo => foo.description)) [untested, but from what I know of quite correct] Best, Sven From davidgshi at yahoo.co.uk Tue Mar 29 11:49:38 2016 From: davidgshi at yahoo.co.uk (David Shi) Date: Tue, 29 Mar 2016 15:49:38 +0000 (UTC) Subject: Simple, fast responsive, secure way of creating REST services References: <1617463095.3176960.1459266578427.JavaMail.yahoo.ref@mail.yahoo.com> Message-ID: <1617463095.3176960.1459266578427.JavaMail.yahoo@mail.yahoo.com> Hello, Justin, What you said is very interesting and useful. I just wonder whether there are much simpler alternatives for fast, responsive, secure REST services.? Python at server-side.? It provides REST services.? Data exchange with the web--page.? Formatted XML or Json. Ideally, it uses the least code. Perhaps, some folks in this group have made great achievement for doing so, and would like to share with us. ? Or, any excellent literature describes this?? I like articles which give insight into the nitty-gritty. Looking forward to hearing from you. Regards. David From __peter__ at web.de Tue Mar 29 12:05:47 2016 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Mar 2016 18:05:47 +0200 Subject: [OT] C# -- sharp or carp? was Re: Learning Python (or Haskell) makes you a worse programmer References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA565A.9020800@mail.de> <56FAA22E.3040805@mail.de> Message-ID: Sven R. Kunze wrote: > On 29.03.2016 12:18, Sven R. Kunze wrote: >> On 29.03.2016 11:39, Peter Otten wrote: >>> My question to those who know a bit of C#: what is the state-of-the-art >>> equivalent to >>> >>> "\n".join(foo.description() for foo in mylist >>> if foo.description() != "") >>> >> >> Using LINQ, I suppose: >> https://en.wikipedia.org/wiki/Language_Integrated_Query > > Friend of mine told me something like this: > > String.Join("\n", mylist.Where(foo => > !String.IsNullOrEmpty(foo.description)).Select(foo => foo.description)) > > [untested, but from what I know of quite correct] Reformatting it a bit String.Join( "\n", mylist.Where( foo => !String.IsNullOrEmpty(foo.description) ).Select( foo => foo.description)) this looks like a variant of Python's str.join( "\n", map(lambda foo: foo.description, filter(lambda foo: foo.description, mylist))) Assuming it's type-safe and can perhaps reshuffle the where and select part into something optimised there is definitely progress. But still, Python's generator expressions are cool.. From srkunze at mail.de Tue Mar 29 12:11:36 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Tue, 29 Mar 2016 18:11:36 +0200 Subject: [OT] C# -- sharp or carp? was Re: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA565A.9020800@mail.de> <56FAA22E.3040805@mail.de> Message-ID: <56FAA938.4080702@mail.de> On 29.03.2016 18:05, Peter Otten wrote: > Reformatting it a bit > > String.Join( > "\n", > mylist.Where( > foo => !String.IsNullOrEmpty(foo.description) > ).Select( > foo => foo.description)) > > this looks like a variant of Python's > > str.join( > "\n", > map(lambda foo: foo.description, > filter(lambda foo: foo.description, mylist))) > > Assuming it's type-safe and can perhaps reshuffle the where and select part > into something optimised there is definitely progress. > > But still, Python's generator expressions are cool.. Haha, sure. But don't get stuck there. Learn something new from time to time; even a new language. Best, Sven From rgaddi at highlandtechnology.invalid Tue Mar 29 12:59:22 2016 From: rgaddi at highlandtechnology.invalid (Rob Gaddi) Date: Tue, 29 Mar 2016 16:59:22 -0000 (UTC) Subject: error installing scipy on python 3.5, win 10 64 bit References: Message-ID: Sinay Goldberg wrote: > Please help Alright, let's try making this an exercise for the student. You're asking a bunch of strangers on the Internet to take time out of their day to fix your problems. Is there, perhaps, any way that you could make their task easier so as to reduce the size of your ask? Some snippets of information that you may have that might narrow down the scope of "error" so that folks don't have to guess? Don't get me wrong, "Please help" is super informative. But maybe, just maybe, you may be able to increase your contribution to this conversation. Think long and hard on it. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From random832 at fastmail.com Tue Mar 29 13:22:09 2016 From: random832 at fastmail.com (Random832) Date: Tue, 29 Mar 2016 13:22:09 -0400 Subject: [stdlib-sig] Can imaplib be improved? In-Reply-To: <1458873222.2158998.559175002.3C7CEAF4@webmail.messagingengine.com> References: <1458873222.2158998.559175002.3C7CEAF4@webmail.messagingengine.com> Message-ID: <1459272129.1687004.562722474.0DAB6376@webmail.messagingengine.com> I'd posted this to stdlib-sig at python.org without realizing that that list is mostly dead. On Thu, Mar 24, 2016, at 22:33, Random832 wrote: > I assume that everyone who has ever used imaplib is familiar with how > painful its output format is to deal with. I am wondering if anyone else > has any ideas on ways it can be extended in a backward-compatible way to > provide options for better parsing, handling unilateral data from the > server, processing data as it comes in, etc. Anyone have any thoughts? From invalid at invalid.invalid Tue Mar 29 14:45:42 2016 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 29 Mar 2016 18:45:42 +0000 (UTC) Subject: [stdlib-sig] Can imaplib be improved? References: <1458873222.2158998.559175002.3C7CEAF4@webmail.messagingengine.com> Message-ID: On 2016-03-29, Random832 wrote: > I'd posted this to stdlib-sig at python.org without realizing that that > list is mostly dead. > > On Thu, Mar 24, 2016, at 22:33, Random832 wrote: >> I assume that everyone who has ever used imaplib is familiar with how >> painful its output format is to deal with. Yes. Been there, done that, still have bald patches where I tore my hair out. >> I am wondering if anyone else has any ideas on ways it can be >> extended in a backward-compatible way to provide options for better >> parsing, handling unilateral data from the server, processing data >> as it comes in, etc. I think giving up on backwards compatiblity and starting from scratch is the best idea. I like imaplib2 https://pypi.python.org/pypi/imaplib2 https://github.com/bcoe/imaplib2 https://sourceforge.net/projects/imaplib2/ imapclient is pretty nice to work with: https://pypi.python.org/pypi/IMAPClient https://bitbucket.org/mjs0/imapclient http://freshfoo.com/presentations/imapclient-intro/#/ Perhaps it (or something like it) could be added to the std library alongside the current imaplib. -- Grant Edwards grant.b.edwards Yow! I'm reporting for duty at as a modern person. I want gmail.com to do the Latin Hustle now! From random832 at fastmail.com Tue Mar 29 14:55:57 2016 From: random832 at fastmail.com (Random832) Date: Tue, 29 Mar 2016 14:55:57 -0400 Subject: [stdlib-sig] Can imaplib be improved? In-Reply-To: References: <1458873222.2158998.559175002.3C7CEAF4@webmail.messagingengine.com> Message-ID: <1459277757.1709688.562815482.38DBCD1C@webmail.messagingengine.com> On Tue, Mar 29, 2016, at 14:45, Grant Edwards wrote: > I think giving up on backwards compatiblity and starting from scratch > is the best idea. > > I like imaplib2 > > https://pypi.python.org/pypi/imaplib2 > https://github.com/bcoe/imaplib2 > https://sourceforge.net/projects/imaplib2/ > > imapclient is pretty nice to work with: > > https://pypi.python.org/pypi/IMAPClient > https://bitbucket.org/mjs0/imapclient > http://freshfoo.com/presentations/imapclient-intro/#/ > > Perhaps it (or something like it) could be added to the std library > alongside the current imaplib. I couldn't get imapclient to install; I got some kind of error (I can't remember, and can't reproduce now because it "thinks" it was successful) from pip installing some crypto dependency, and a runtime error not finding a SSLContext class. I haven't tried imaplib2 yet; by the time I discovered it my scripts were already mature enough that I just finished with what I had. From blacksqr at gmail.com Tue Mar 29 16:26:14 2016 From: blacksqr at gmail.com (blacksqr at gmail.com) Date: Tue, 29 Mar 2016 13:26:14 -0700 (PDT) Subject: Re-using TCL code from python over network In-Reply-To: References: <172d629d-3dc8-4e47-b163-05b4f32a027c@googlegroups.com> <56FA3179.3080005@gmail.com> Message-ID: <5948091b-2d32-4477-85a6-843a6f8cb3e7@googlegroups.com> On Tuesday, March 29, 2016 at 5:24:37 AM UTC-5, Karim wrote: > But it was a good experience to learn TCL (weaknesses). > > Karim I would be interested to know what you consider to be the top weaknesses of Tcl compared to Python which prompted your decision to switch. From nevinadias3 at gmail.com Tue Mar 29 17:00:57 2016 From: nevinadias3 at gmail.com (okdk) Date: Tue, 29 Mar 2016 14:00:57 -0700 (PDT) Subject: Help with python code Message-ID: This is my code import random import time pizzatype = [3.50,4.20,5.20,5.80,5.60] drinktype = [0.90,0.80,0.90] topping = [0.50,0.50,0.50,0.50] def Total_cost_cal (pt ,dt ,t): total = pt + dt + t return total print ("Welcome to Pizza Shed!") order = raw_input ("\n\nPLEASE PRESS ENTER TO ORDER." ) tablenum = input ("Enter table number from 1-25 \n ") while tablenum>25 or tablenum <=0: tablenum = input ("Enter the correct table number, there are only 25 tables ") #Pizza menu with prices print ("---------------------") print ("Let me help you with your order!") print ("---------------------") order = raw_input ("\n\nPLEASE PRESS ENTER TO SELECT YOUR PIZZA." ) print ("Menu") print ( "1 = cheese and tomato: 3.50, " "2 = ham and pineapple: 4.20, " "3 = vegetarian: 5.20, " "4 = meat feast: 5.80, " "5 = seafood: 5.60 " ) menu = input("Enter the type of pizza that you want to order from 1-5 \n") while menu>5 or menu <=0: menu = input ("Enter the right number ") pizza_cost = pizzatype[menu] print ("------------------") pizza_amount = input ("Enter the amount of Pizzas that you want to order ") while pizza_amount > 10 or pizza_amount <=0: pizza_amount = input ("Maximum amount is 10, Please enter again ") print ("--------------------") #base print ("Base") print ( "1 = thin and crispy," "2 = traditional" ) base = input ("Select a base from 1-2 \n") while base>2 or base<=0: base = input ("There are only 2 types, Please enter again ") print ("-------------------") #extra toppings print ("Extra Toppings") toppings = input ("Enter a number for your choice of extra topping \n Enter 1 for extra cheese \n Enter 2 for extra pepperoni \n Enter 3 for extra pineapple \n Enter 4 for extra peppers \n" ) while toppings >4 or toppings < 0: toppings = input ("There are only 4 types of extra toppings, Please try again " ) topping_cost = topping[toppings] print ("-------------------------") #drink print ("Drink") print ( "1 = Cola: 0.90, " "2 = Lemonande: 0.80, " "3 = Fizzy Orange: 0.90 " ) drink = input ("Enter a number for your choice of drinks " ) while drink>3 or drink<0: drink = input ("Choices start from 0 to 3 " ) drink_cost = drinktype[drink] drink_amount = input ("Enter the amount of drinks") while drink_amount >10 or drink_amount<0: drink_amount = input (" You can only have upto 10 drinks, Please try again") print ("--------------------------------") pizzatotal = pizza_cost*pizza_amount drinktotal = drink_cost*drink_amount total_cost = total_cost_cal(pizzatotal, drinktotal, topping_cost) print ("--------------------------------") print ("Calculating bill") print ("--------------------------------") print ("--------------------------------") print ("Thank You for ordering at Pizza Shed! ") Howeve, it doesnt seem to be working. It doesnt calculate the bill. I dont know what to do, as I'm less than average at this. it comes up as IndexError: list index out of range at line42 Please help From rgaddi at highlandtechnology.invalid Tue Mar 29 17:19:05 2016 From: rgaddi at highlandtechnology.invalid (Rob Gaddi) Date: Tue, 29 Mar 2016 21:19:05 -0000 (UTC) Subject: Help with python code References: Message-ID: okdk wrote: > This is my code > import random > import time > > pizzatype = [3.50,4.20,5.20,5.80,5.60] > drinktype = [0.90,0.80,0.90] > topping = [0.50,0.50,0.50,0.50] > > def Total_cost_cal (pt ,dt ,t): > total = pt + dt + t > return total > > print ("Welcome to Pizza Shed!") > > order = raw_input ("\n\nPLEASE PRESS ENTER TO ORDER." ) > > tablenum = input ("Enter table number from 1-25 \n ") > while tablenum>25 or tablenum <=0: > tablenum = input ("Enter the correct table number, there are only 25 tables ") > > #Pizza menu with prices > > print ("---------------------") > > print ("Let me help you with your order!") > > print ("---------------------") > > order = raw_input ("\n\nPLEASE PRESS ENTER TO SELECT YOUR PIZZA." ) > > print ("Menu") > > print ( > "1 = cheese and tomato: 3.50, " > "2 = ham and pineapple: 4.20, " > "3 = vegetarian: 5.20, " > "4 = meat feast: 5.80, " > "5 = seafood: 5.60 " ) > > menu = input("Enter the type of pizza that you want to order from 1-5 \n") > while menu>5 or menu <=0: > menu = input ("Enter the right number ") > pizza_cost = pizzatype[menu] > > print ("------------------") > > pizza_amount = input ("Enter the amount of Pizzas that you want to order ") > while pizza_amount > 10 or pizza_amount <=0: > pizza_amount = input ("Maximum amount is 10, Please enter again ") > > print ("--------------------") > > #base > > print ("Base") > > print ( > "1 = thin and crispy," > "2 = traditional" ) > > base = input ("Select a base from 1-2 \n") > while base>2 or base<=0: > base = input ("There are only 2 types, Please enter again ") > > print ("-------------------") > > #extra toppings > > print ("Extra Toppings") > > toppings = input ("Enter a number for your choice of extra topping \n Enter 1 for extra cheese \n Enter 2 for extra pepperoni \n Enter 3 for extra pineapple \n Enter 4 for extra peppers \n" ) > while toppings >4 or toppings < 0: > toppings = input ("There are only 4 types of extra toppings, Please try again " ) > topping_cost = topping[toppings] > > print ("-------------------------") > > #drink > > print ("Drink") > > print ( > "1 = Cola: 0.90, " > "2 = Lemonande: 0.80, " > "3 = Fizzy Orange: 0.90 " > ) > > drink = input ("Enter a number for your choice of drinks " ) > while drink>3 or drink<0: > drink = input ("Choices start from 0 to 3 " ) > drink_cost = drinktype[drink] > drink_amount = input ("Enter the amount of drinks") > while drink_amount >10 or drink_amount<0: > drink_amount = input (" You can only have upto 10 drinks, Please try again") > > > print ("--------------------------------") > > pizzatotal = pizza_cost*pizza_amount > drinktotal = drink_cost*drink_amount > > total_cost = total_cost_cal(pizzatotal, drinktotal, topping_cost) > > print ("--------------------------------") > print ("Calculating bill") > print ("--------------------------------") > print ("--------------------------------") > > print ("Thank You for ordering at Pizza Shed! ") > > > Howeve, it doesnt seem to be working. It doesnt calculate the bill. I dont know what to do, as I'm less than average at this. > it comes up as IndexError: list index out of range at line42 > > Please help Don't know which one is line 42; but I'd bet your problem is there. As a rough guess, it might be the line that says: pizza_cost = pizzatype[menu] You're bounding that to the range 1-5. A Python list of length 5 has indices 0-4. But the error message is telling you everything you need to know; you're trying to get a list index that's out of range in line 42. Find line 42, figure out what index you're asking it for, and you'll have your answer. If you don't have an editor that shows you line numbers then your editor is fundamentally terrible and you should not use it (I personally like Notepad++ for Windows or Geany for Linux). -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From bc at freeuk.com Tue Mar 29 17:19:56 2016 From: bc at freeuk.com (BartC) Date: Tue, 29 Mar 2016 22:19:56 +0100 Subject: Help with python code In-Reply-To: References: Message-ID: On 29/03/2016 22:00, okdk wrote: > pizzatype = [3.50,4.20,5.20,5.80,5.60] > drinktype = [0.90,0.80,0.90] > topping = [0.50,0.50,0.50,0.50] > total_cost = total_cost_cal(pizzatotal, drinktotal, topping_cost) > > print ("--------------------------------") > print ("Calculating bill") > print ("--------------------------------") > print ("--------------------------------") > > print ("Thank You for ordering at Pizza Shed! ") > > > Howeve, it doesnt seem to be working. It doesnt calculate the bill. I dont know what to do, as I'm less than average at this. > it comes up as IndexError: list index out of range at line42 Those lists you define are indexed from 0, not 1 as you seem to assume. (So you get an index error if choosing pizza type 5). You might try inserting a dummy 0 at the start (so the rest are indexed from 1), but better to change the logic. Also total_cost_cal() is not defined anywhere. (And the user interface is generally untidy with poor error checking, but this can be cleaned up later.) (I also found I was obliged to choose an extra topping. Suppose I don't want one? There is no option for that. Perhaps you can use option 0 for some of these, and that might help solve the indexing problem.) -- Bartc From vito.detullio at gmail.com Tue Mar 29 17:25:36 2016 From: vito.detullio at gmail.com (Vito De Tullio) Date: Tue, 29 Mar 2016 23:25:36 +0200 Subject: repeat items in a list References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> <29bb9c16-eef4-4c00-9e41-ce8419405c29@googlegroups.com> <1459173882.380114.561434386.096F166A@webmail.messagingengine.com> Message-ID: Random832 wrote: > How do you turn ['a', 'c', 'b'] into ['a', 'a', 'a', 'c', 'c', 'c', 'b', > 'b', 'b']? >>> sum([[e]*3 for e in ['a', 'c', 'b']], []) ['a', 'a', 'a', 'c', 'c', 'c', 'b', 'b', 'b'] -- By ZeD From nevinadias3 at gmail.com Tue Mar 29 17:32:47 2016 From: nevinadias3 at gmail.com (Yum Di) Date: Tue, 29 Mar 2016 14:32:47 -0700 (PDT) Subject: Help with python code In-Reply-To: References: Message-ID: import random import time pizzatype = [3.50,4.20,5.20,5.80,5.60] drinktype = [0.90,0.80,0.90] topping = [0.50,0.50,0.50,0.50] def Total_cost_cal (pt ,dt ,t): total = pt + dt + t return total print ("Welcome to Pizza Shed!") order = raw_input ("\n\nPLEASE PRESS ENTER TO ORDER." ) tablenum = input ("Enter table number from 1-25 \n ") while tablenum>25 or tablenum <=0: tablenum = input ("Enter the correct table number, there are only 25 tables ") #Pizza menu with prices print ("---------------------") print ("Let me help you with your order!") print ("---------------------") order = raw_input ("\n\nPLEASE PRESS ENTER TO SELECT YOUR PIZZA." ) print ("Menu") print ( "1 = cheese and tomato: 3.50, " "2 = ham and pineapple: 4.20, " "3 = vegetarian: 5.20, " "4 = meat feast: 5.80, " "5 = seafood: 5.60 " ) menu = input("Enter the type of pizza that you want to order from 1-5 \n") while menu>5 or menu <=1: menu = input ("Enter the right number ") pizza_cost = pizzatype[menu] print ("------------------") pizza_amount = input ("Enter the amount of Pizzas that you want to order ") while pizza_amount > 10 or pizza_amount <=0: pizza_amount = input ("Maximum amount is 10, Please enter again ") print ("--------------------") #base print ("Base") print ( "1 = thin and crispy," "2 = traditional" ) base = input ("Select a base from 1-2 \n") while base>2 or base<=1: base = input ("There are only 2 types, Please enter again ") if base_type == 1: print "You have chosen thin and crispy" elif base_type == 2: print ("You have chosen traditional") print ("-------------------") #extra toppings print ("Extra Toppings") toppings = input ("Enter a number for your choice of extra topping \n Enter 1 for extra cheese \n Enter 2 for extra pepperoni \n Enter 3 for extra pineapple \n Enter 4 for extra peppers \n" ) while toppings >4 or toppings < 0: toppings = input ("There are only 4 types of extra toppings, Please try again " ) topping_cost = topping[toppings] print ("-------------------------") #drink print ("Drink") print ( "1 = Cola: 0.90, " "2 = Lemonande: 0.80, " "3 = Fizzy Orange: 0.90 " ) drink = input ("Enter a number for your choice of drinks " ) while drink>3 or drink<0: drink = input ("Choices start from 0 to 3 " ) drink_cost = drinktype[drink] drink_amount = input ("Enter the amount of drinks") while drink_amount >10 or drink_amount<1: drink_amount = input (" You can only have upto 10 drinks, Please try again") print ("--------------------------------") pizzatotal = pizza_cost*pizza_amount drinktotal = drink_cost*drink_amount total_cost = total_cost_cal(pizzatotal, drinktotal, topping_cost) print ("--------------------------------") print ("Calculating bill") print ("--------------------------------") print ("--------------------------------") print ("Thank You for ordering at Pizza Shed! ") I still don't get it.. Sorry, I'm still quite new to this I've have made few minor changes, but it still doesn't work From vito.detullio at gmail.com Tue Mar 29 17:36:05 2016 From: vito.detullio at gmail.com (Vito De Tullio) Date: Tue, 29 Mar 2016 23:36:05 +0200 Subject: [OT] C# -- sharp or carp? was Re: Learning Python (or Haskell) makes you a worse programmer References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA565A.9020800@mail.de> <56FAA22E.3040805@mail.de> Message-ID: Sven R. Kunze wrote: >>> My question to those who know a bit of C#: what is the state-of-the-art >>> equivalent to >>> >>> "\n".join(foo.description() for foo in mylist >>> if foo.description() != "") > Friend of mine told me something like this: > > String.Join("\n", mylist.Where(foo => > !String.IsNullOrEmpty(foo.description)).Select(foo => foo.description)) I don't know if is "better" or not, but I find more readable using the "sql"-like syntax string.Join("\n", from foo in mylist where !string.IsNullOrEmpty(foo.description()) select foo.description()); which is relatively similar to the python's comprehension. -- By ZeD From rgaddi at highlandtechnology.invalid Tue Mar 29 17:37:49 2016 From: rgaddi at highlandtechnology.invalid (Rob Gaddi) Date: Tue, 29 Mar 2016 21:37:49 -0000 (UTC) Subject: Help with python code References: Message-ID: Yum Di wrote: > I still don't get it.. Sorry, I'm still quite new to this > I've have made few minor changes, but it still doesn't work Then try entering one line at a time of your program into the interactive interpreter. Copy and paste is fine, but use the interpreter to look at the actual values of variables that you're creating. Also, as a mailing list/Usenet etiquette note: You get to have one name you go by. Going around changing the name you're posting under in the middle of the thread is a guaranteed way to piss folks off. You didn't know. You now do. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From michael.selik at gmail.com Tue Mar 29 18:05:16 2016 From: michael.selik at gmail.com (Michael Selik) Date: Tue, 29 Mar 2016 22:05:16 +0000 Subject: repeat items in a list In-Reply-To: References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> <29bb9c16-eef4-4c00-9e41-ce8419405c29@googlegroups.com> <1459173882.380114.561434386.096F166A@webmail.messagingengine.com> Message-ID: I prefer itertools.chain.from_iterable to the sum trick. >>> from itertools import chain >>> lst = list('abc') >>> list(chain.from_iterable([s]*3 for s in lst)) ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'] On Tue, Mar 29, 2016 at 5:28 PM Vito De Tullio wrote: > Random832 wrote: > > > How do you turn ['a', 'c', 'b'] into ['a', 'a', 'a', 'c', 'c', 'c', 'b', > > 'b', 'b']? > > >>> sum([[e]*3 for e in ['a', 'c', 'b']], []) > ['a', 'a', 'a', 'c', 'c', 'c', 'b', 'b', 'b'] > > > -- > By ZeD > > -- > https://mail.python.org/mailman/listinfo/python-list > From mail.python.org at marco.sulla.e4ward.com Tue Mar 29 18:29:26 2016 From: mail.python.org at marco.sulla.e4ward.com (Marco Sulla) Date: Wed, 30 Mar 2016 00:29:26 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> Message-ID: On 29 March 2016 at 16:31, Chris Angelico wrote: > But the definition of a sequence, and likewise the definition of a > mapping, goes deeper than that. A sequence has *relative* stability; > if one item is at a lower index than another, it will continue to be > at a lower index, until you change one of those two items. Changes > elsewhere in the sequence might bring them closer together or push > them further apart, but one of them is still earlier in the sequence > than the other. A mapping, on the other hand, has *absolute* > stability. Any given key->value relationship is stable in and of > itself. If you stuff a thing into a dict under a particular key, you > expect to be able to get it back using that key, not some other. It's the same arguments of Steven D'Aprano. Let me counter these arguments with this example: >>> class StrangeDict(dict): ... def insert(self, k, v): ... if k in self: ... for key in [x for x in sorted(self.keys()) if x >= k]: ... v_next = self[key] ... self[key] = v ... v = v_next ... ... self[key+1] = v ... >>> a = StrangeDict({0:5, 1:7, 2: 14}) >>> a.insert(1, 5) >>> a {0: 5, 1: 5, 2: 7, 3: 14} Yes, it's a terrible class and lacks a lot of safety checks, but I don't think at all it violates the map contract. You can continue and add some constraint at __init__() about key types and their contiguity, some other methods and voila', you'll get a list-like class. Let me add that an items() and keys() for sequences will be also useful for day-by-day programming, since they will be a shortcut for enumerate(seq) and range(len(seq)) > The whole idea of making sequences and mappings more similar is highly > distasteful to me, and I've figured out why. It's the exact problem > with the PHP array - it's not sure whether to act as a mapping or a > sequence This is a good point. This is not true for mutable sequences (lists), since they will have a lot of methods (append, pop etc) that allows you to distinguish them, but immutable sequences like tuples will be not easily distinguishable using duck typing. I think the main problem is in __getitem__. __getitem__ can be used as slice method checking if its parameter is a slice. If the slice method was a separated method, this problem will not arise. On 27 March 2016 at 21:24, Mark Lawrence wrote: > Why do you need a new interace if all you're trying to do is create a > vdict class that has "iter(d) == iter(d.values()), and should also > have a count() method, like sequence types"? Since simply adding get(), items(), keys(), values() to existing sequence interface will likely break existing code, I would try also to write new sequence types, using a common interface with maps. This is my idea. From nevinadias3 at gmail.com Tue Mar 29 18:33:50 2016 From: nevinadias3 at gmail.com (Yum Di) Date: Tue, 29 Mar 2016 15:33:50 -0700 (PDT) Subject: Calculate Bill Message-ID: import random import time print ("Welcome to Pizza Shed!") order = raw_input ("\n\nPLEASE PRESS ENTER TO ORDER." ) tablenum = input ("Enter table number from 1-25 \n ") while tablenum>25 or tablenum <=0: tablenum = input ("Enter the correct table number, there are only 25 tables ") #Pizza menu with prices print ("---------------------") print ("Let me help you with your order!") print ("---------------------") order = raw_input ("\n\nPLEASE PRESS ENTER TO SELECT YOUR PIZZA." ) print ("Menu") print ( "1 = cheese and tomato: 3.50, " "2 = ham and pineapple: 4.20, " "3 = vegetarian: 5.20, " "4 = meat feast: 5.80, " "5 = seafood: 5.60 " ) pizza_choice = input("Enter the type of pizza that you want to order from 1-5 \n") while pizza_choice>5 or pizza_choice <=1: pizza_choice = input ("Enter the right number ") print ("------------------") pizza_amount = input ("Enter the amount of Pizzas that you want to order ") while pizza_amount > 10 or pizza_amount <=0: pizza_amount = input ("Maximum amount is 10, Please enter again ") print ("--------------------") #base print ("Base") print ( "1 = thin and crispy," "2 = traditional" ) base = input ("Select a base from 1-2 \n") while base>2 or base<=1: base = input ("There are only 2 types, Please enter again ") if base == 1: print "You have chosen thin and crispy" elif base == 2: print ("You have chosen traditional") print ("-------------------") #extra toppings print ("Extra Toppings") toppings = input ("Enter a number for your choice of extra topping \n Enter 1 for extra cheese \n Enter 2 for extra pepperoni \n Enter 3 for extra pineapple \n Enter 4 for extra peppers \n" ) while toppings >4 or toppings < 0: toppings = input ("There are only 4 types of extra toppings, Please try again " ) if toppings == 1: print "You have chosen extra cheese" elif toppings == 2: print ("You have chosen pepperoni") elif toppings == 3: print ("You have chosen pineapple") elif toppings == 4: print ("You have chosen peppers") print ("-------------------------") #drink print ("Drink") print ( "1 = Cola: 0.90, " "2 = Lemonande: 0.80, " "3 = Fizzy Orange: 0.90 " ) drink = input ("Enter a number for your choice of drinks " ) while drink>3 or drink<0: drink = input ("Choices start from 0 to 3 " ) drink_amount = input ("Enter the amount of drinks") while drink_amount >10 or drink_amount<1: drink_amount = input (" You can only have upto 10 drinks, Please try again") if drink == 1: print "You have chosen Cola" elif drink == 2: print ("You have chosen Lemonande") elif drink == 3: print ("You have chosen Fizzy Orange") print ("--------------------------------") print ("Calculating bill") print ("--------------------------------") print ("--------------------------------") print ("Thank You for ordering at Pizza Shed! ") Hey.. this code works. However, i need it to calculate the total cost. I dont know how to do that. Can someone help me.. thanks From davidgshi at yahoo.co.uk Tue Mar 29 18:45:08 2016 From: davidgshi at yahoo.co.uk (David Shi) Date: Tue, 29 Mar 2016 22:45:08 +0000 (UTC) Subject: IPython and Jupyter References: <447260475.3527219.1459291508756.JavaMail.yahoo.ref@mail.yahoo.com> Message-ID: <447260475.3527219.1459291508756.JavaMail.yahoo@mail.yahoo.com> Ipython-4.1.2 I thought that I installed Ipython. I typed in ipython notebook. But a WARNING came up, saying Subcommand 'ipython notebook is deprecated and will be removed in?future versions. Then Jupyter turned up. How can I make available both Ipython notebook and Jupyter?, so that I can switch between the twowhenever required. Regards. David From best_lay at yahoo.com Tue Mar 29 18:51:50 2016 From: best_lay at yahoo.com (Wildman) Date: Tue, 29 Mar 2016 17:51:50 -0500 Subject: Help with python code References: Message-ID: On Tue, 29 Mar 2016 21:19:05 +0000, Rob Gaddi wrote: >> menu = input("Enter the type of pizza that you want to order from 1-5 \n") >> while menu>5 or menu <=0: >> menu = input ("Enter the right number ") >> pizza_cost = pizzatype[menu] As it has already been pointed out, a Python list starts with an index of 0. Change the last line in the above code to this... pizza_cost = pizzatype[menu - 1] Anywhere else that your code references a list index you may need to make the same change. -- GNU/Linux user #557453 May the Source be with you. From esj at harvee.org Tue Mar 29 19:29:58 2016 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 29 Mar 2016 19:29:58 -0400 Subject: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: <56FA537F.9090506@mail.de> References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA00EC.80909@gmail.com> <56FA537F.9090506@mail.de> Message-ID: <56FB0FF6.3000305@harvee.org> On 3/29/2016 6:05 AM, Sven R. Kunze wrote: > > Python = English > As someone who writes English text and code using speech recognition, I can assure you that Python is not English. :-) From rosuav at gmail.com Tue Mar 29 19:34:23 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 30 Mar 2016 10:34:23 +1100 Subject: Calculate Bill In-Reply-To: References: Message-ID: On Wed, Mar 30, 2016 at 9:33 AM, Yum Di wrote: > Hey.. this code works. However, i need it to calculate the total cost. > I dont know how to do that. Can someone help me.. > thanks It does indeed appear to work. And thank you for posting your current code. However... > print ("Welcome to Pizza Shed!") > > order = raw_input ("\n\nPLEASE PRESS ENTER TO ORDER." ) > > tablenum = input ("Enter table number from 1-25 \n ") This should never be done. Do not do this. Your use of raw_input proves that you're using Python 2, and in Python 2, never ever ever use input(). There are two solutions: 1) Use raw_input everywhere 2) Use Python 3, and add parentheses to the few print() calls that don't have them. Either way, the correct fix also involves accepting *strings* from the keyboard, and then converting them. The problem with input() is that it automatically converts what the user types, according to the rules of source code; you almost never want this. For example, entering 08 will result in an error, but 08.50 is the same as 8.50. After that, you can start looking at the totals. But I'm not going to write the code for you; you can start writing code, and when you get stuck, come and ask for help. ChrisA From steve at pearwood.info Tue Mar 29 19:43:03 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 30 Mar 2016 10:43:03 +1100 Subject: Threading is foobared? References: <56f74d00$0$1620$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56fb1309$0$22141$c3e8da3$5496439d@news.astraweb.com> On Tue, 29 Mar 2016 09:26 pm, Sven R. Kunze wrote: > On 27.03.2016 05:01, Steven D'Aprano wrote: >> Am I the only one who has noticed that threading of posts here is >> severely broken? It's always been the case that there have been a few >> posts here and there that break threading, but now it seems to be much >> more common. > > I agree. Didn't we both already have a conversation about this? I > thought it is my thunderbird messing things up. I'm not using Thunderbird, so whatever the cause of the problem, it is not specific to Thunderbird. -- Steven From rgaddi at highlandtechnology.invalid Tue Mar 29 19:54:48 2016 From: rgaddi at highlandtechnology.invalid (Rob Gaddi) Date: Tue, 29 Mar 2016 23:54:48 -0000 (UTC) Subject: Threading is foobared? References: <56f74d00$0$1620$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Am I the only one who has noticed that threading of posts here is severely > broken? It's always been the case that there have been a few posts here and > there that break threading, but now it seems to be much more common. > > For instance, I see Jerry Martens' post "help with program". According to my > newsreader, KNode, there are no replies to that thread. But I see a reply > from Chris A. Chris' reply has a header line: > > In-Reply-To: <1392737302.749065.1459024715818.JavaMail.yahoo at mail.yahoo.com> > > but Jerry's original has: > > References: > <1392737302.749065.1459024715818.JavaMail.yahoo.ref at mail.yahoo.com> > > Notice the difference? Here the two values lined up: > > <1392737302.749065.1459024715818.JavaMail.yahoo.ref at mail.yahoo.com> > <1392737302.749065.1459024715818.JavaMail.yahoo at mail.yahoo.com> > Just read on Usenet instead of through the mailing list. That way you can accept broken threading as a given rather than wonder why it's happening in a particular case. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From steve at pearwood.info Tue Mar 29 20:05:51 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 30 Mar 2016 11:05:51 +1100 Subject: Statements as expressions [was Re: Undefined behaviour in C] References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> <87h9fr5qig.fsf@nightsong.com> <56fa3c2a$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56fb1861$0$1622$c3e8da3$5496439d@news.astraweb.com> On Tue, 29 Mar 2016 10:31 pm, BartC wrote: > On 29/03/2016 09:26, Steven D'Aprano wrote: >> On Monday 28 March 2016 12:40, Paul Rubin wrote: > > >> The point is that there's nothing intrinsically obvious or right about >> "return the value of the last statement in the block". > > But that's exactly what happens inside a typical function: you have > linear sequence of statements, then you a have return statement: at the > end. It's a common pattern. But return is an *explicit* exit. And not all languages work that way. {My Pascal syntax may be a bit rusty...} function demo(int x): int; begin demo := x + 1; {sets the return value} writeln('x has the value', x); writeln('returning now...'); end; [...] >> An expression naturally and intrinsically should return the value the >> expression calculates. This is such a no-brainer that I feel stupid even >> writing it: "x+1" should return "x+1". It would be crazy to pick >> something else. > > (This is in contradiction to what you say elsewhere, where: > > graph + node > > may be procedural.) Not at all. With operator overloading, the plus operator + ends up as a method call __add__ or __radd__. This method call can have side-effects, and it can return anything it likes, including None. That return value can be ignored, but it is still the return value of the expression: graph + node # returns None, use this expression for the side-effects only Just like print(a, b, c) returns None, and we use if for the side-effects. It's still an expression ("call the print function with these arguments"), it does something (prints) and then returns None. >> But a statement is a statement because it doesn't have a return value. > > Isn't an expression technically a statement in Python? I mean statements which are not legal expressions, like: del x import module from module import name for x in seq: block while condition: block try ... except ... else ... finally etc. I'm sorry that I wasn't pedantic enough to specify "statements (apart from expressions)" each time I contrasted statements and expressions. Can you possibly forgive me for my informal use of language? > Therefore a > statement could have a value. But take this example: > > if cond1: x=a1 > elif cond2: x=a2 > elif cond3: x=a3 > else: x=a4 > > Clearly this would be better expressed as (not valid Python): > > x = if cond1: a1 > elif cond2: a2 > elif cond3: a3 > else: a4 x = a1 if cond1 else a2 if cond2 else a3 if cond3 else a4 We can split it over multiple lines too: x = ( a1 if cond1 else a2 if cond2 else a3 if cond3 else a4 ) > (Actually 'del is a rather odd language feature. And I can't figure out > how it's implemented; how does it manage 'del x[i]'? Anyway that's > another matter.) del x[i] calls x.__delitem__(i) >> True if that allowed the value to be garbage >> collected, False if it wasn't? Or the other way around? None of these >> suggests feel either useful or obviously right. > > It doesn't need to give a useful value. Hence my suggestion that all statements (apart from expressions) return 42. > Its 'value' lies in being able to have it in a sequence or block: > > z = del x; y In a hypothetical Python where `del x` returns None, that would set z to None and then evaluate y, doing nothing with the result. -- Steven From steve at pearwood.info Tue Mar 29 20:50:45 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 30 Mar 2016 11:50:45 +1100 Subject: Calculate Bill References: Message-ID: <56fb22e8$0$1601$c3e8da3$5496439d@news.astraweb.com> On Wed, 30 Mar 2016 09:33 am, Yum Di wrote: [...] > print ("Thank You for ordering at Pizza Shed! ") > > Hey.. this code works. However, i need it to calculate the total cost. > I dont know how to do that. Can someone help me.. > thanks Think about how people calculate the bill at a real pizza restaurant. Every time you order something, they write it down in a list: seafood thin and crispy extra cheese pineapple Fizzy Orange The list goes to the cook, who prepares the order, then when you're ready to pay, it goes to somebody who works out the prices. In your case, you don't need to care about the cook. So you can record the prices of each item in a list: prices = [] # No items have been ordered. # Order 3 seafood pizzas: prices.append(5.60 * 3) and so on, for all the extra topics, drinks, deserts, anything else they order. Then, you calculate the total: sum(prices) -- Steven From tjreedy at udel.edu Tue Mar 29 20:55:08 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Mar 2016 20:55:08 -0400 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> Message-ID: On 3/29/2016 6:29 PM, Marco Sulla via Python-list wrote: > Let me add that an items() and keys() for sequences will be also > useful for day-by-day programming, since they will be a shortcut for > enumerate(seq) and range(len(seq)) To me they are useless and confusing duplications since enumerate()(seq) and range(len(seq)) are quite different from dict.items and dict.keys. They cannot be used interchangably. Dict.keys/values/items are re-iterable, set-like *dynamic views* of dicts. They are not iterators. They support binary set operations and inter-operate with sets. >>> {1:1, 2:2}.keys() ^ {1, 3} {2, 3} >>> {1, 3} ^ {1:1, 2:2}.keys() {2, 3} They not independent objects but are views of the contests of the dict. They are relatively easy to implement because dicts are key-hashed sets of pairs. At least in CPython, changing a dict disables view iterators. >>> d={1:1, 2:2} >>> di = iter(d) >>> next(di) 1 >>> d[3] = 3 >>> next(di) Traceback (most recent call last): File "", line 1, in next(di) RuntimeError: dictionary changed size during iteration Enumerates are iterators. Ranges are independent collections. Neither support binary set operations. Enumerates and range iterators are not disabled by sequence changes. > Since simply adding get(), items(), keys(), values() to existing > sequence interface will likely break existing code, I would try also > to write new sequence types, using a common interface with maps. seq.get is plausible, but the use cases are not clear. It is trivial to write, so it needs justification. A major use of dict.get is to supply an empty list for values that can be appended to. d.get(key, []).append(val) A similar use with lists could just as well be done with a dict. For the rest, try writing sequence view classes that actually mimic dict views and interoperate with sets and views. Find the dict view tests and adapt them to seq views. To use the same code with dicts and seqs, add functions that return a dict view or seq view depending on the class of the collections. def keys(ds): reture ds.keys() if isinstance(ds, dict) else SeqKeys(ds) You might search for 'python sequence view' first, and if there is nothing already on PyPI, add a seqview module there. -- Terry Jan Reedy From rosuav at gmail.com Tue Mar 29 20:56:33 2016 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 30 Mar 2016 11:56:33 +1100 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> Message-ID: On Wed, Mar 30, 2016 at 9:29 AM, Marco Sulla via Python-list wrote: > On 29 March 2016 at 16:31, Chris Angelico wrote: >> But the definition of a sequence, and likewise the definition of a >> mapping, goes deeper than that. A sequence has *relative* stability; >> if one item is at a lower index than another, it will continue to be >> at a lower index, until you change one of those two items. Changes >> elsewhere in the sequence might bring them closer together or push >> them further apart, but one of them is still earlier in the sequence >> than the other. A mapping, on the other hand, has *absolute* >> stability. Any given key->value relationship is stable in and of >> itself. If you stuff a thing into a dict under a particular key, you >> expect to be able to get it back using that key, not some other. > > It's the same arguments of Steven D'Aprano. Let me counter these > arguments with this example: > >>>> class StrangeDict(dict): > ... def insert(self, k, v): > ... if k in self: > ... for key in [x for x in sorted(self.keys()) if x >= k]: > ... v_next = self[key] > ... self[key] = v > ... v = v_next > ... > ... self[key+1] = v > ... >>>> a = StrangeDict({0:5, 1:7, 2: 14}) >>>> a.insert(1, 5) >>>> a > {0: 5, 1: 5, 2: 7, 3: 14} > > Yes, it's a terrible class and lacks a lot of safety checks, but I > don't think at all it violates the map contract. You can continue and > add some constraint at __init__() about key types and their > contiguity, some other methods and voila', you'll get a list-like > class. The map contract is this: x = StrangeDict() x[123] = 456 ... assert x[123] == 456 Your mapping does violate the map contract. ChrisA From rustompmody at gmail.com Tue Mar 29 23:14:02 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 29 Mar 2016 20:14:02 -0700 (PDT) Subject: Statements as expressions [was Re: Undefined behaviour in C] In-Reply-To: <878u125ugc.fsf@nightsong.com> References: <56f55e2e$0$1619$c3e8da3$5496439d@news.astraweb.com> <87wpoq1omm.fsf@elektro.pacujo.net> <56f5f81d$0$1585$c3e8da3$5496439d@news.astraweb.com> <87io0a6j1w.fsf@nightsong.com> <56f67ee3$0$1583$c3e8da3$5496439d@news.astraweb.com> <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> <878u125ugc.fsf@nightsong.com> Message-ID: <720bdbcc-862d-425d-abc0-2dacaaf8f7d9@googlegroups.com> On Tuesday, March 29, 2016 at 12:18:38 AM UTC+5:30, Paul Rubin wrote: > BartC writes: > > With more recent ones I've dropped that model, so that statements and > > expressions are different, and that is strictly enforced. This makes > > implementation simpler, and detects lots more errors. > > You should try Haskell, where there are only expressions, but the ones > that perform actions can be separated from the other ones through the > type system, so using one in the wrong place raises a compile time type > error. When I studied Pascal was mainstream and Lisp (and to smaller extent Prolog, APL) were hi-faluting. In retrospect, Pascal got something right that most everyone, both before and after got wrong, viz that we need values AND effects. Philosophically: Is programming about knowing or doing? Clearly any onesided answer is wrong. Both columns in the table here need equal weightage http://blog.languager.org/2016/01/primacy.html#expstat Pascal ? C ? Python is a slide down because Pascal had the clear distinction of procedure and function C conflated procedure into function with its 'void function' [Actually the first C had no void] Python only has None-return But a None returned to signify a real semantics eg dict.get not finding key And a None returned because asking for something is meaningless eg print in python3 are unfortunately undistinguishable although conceptually totally different Yeah Haskell's type system carries Pascal's procedure??function distinction in great and excruciating detail -- pure and monadic types. But IMHO monads for distinguishing values and effects is sledgehammer-for-cracking-an-egg From random832 at fastmail.com Tue Mar 29 23:34:26 2016 From: random832 at fastmail.com (Random832) Date: Tue, 29 Mar 2016 23:34:26 -0400 Subject: Threading is foobared? In-Reply-To: References: <56f74d00$0$1620$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1459308866.18182.563189330.386DC308@webmail.messagingengine.com> On Tue, Mar 29, 2016, at 19:54, Rob Gaddi wrote: > Just read on Usenet instead of through the mailing list. That way > you can accept broken threading as a given rather than wonder why it's > happening in a particular case. It's a given everywhere. Any thread that contains a sufficient number of replies from both users using usenet and users using the mailing list (gmane counts as the mailing list, since it _doesn't_ do the broken stuff) is going to be broken for everyone everywhere, though it will be broken in different places. For users reading by the mailing list, Usenet users' replies to Mailing List users will be broken (but their replies to each other will be fine). For users reading by Usenet, Mailing List users' replies to each other will be broken (though all replies made via Usenet or to Usenet users will be fine). From random832 at fastmail.com Tue Mar 29 23:38:37 2016 From: random832 at fastmail.com (Random832) Date: Tue, 29 Mar 2016 23:38:37 -0400 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> Message-ID: <1459309117.19250.563191890.0CB591D4@webmail.messagingengine.com> On Tue, Mar 29, 2016, at 20:56, Chris Angelico wrote: > The map contract is this: > > x = StrangeDict() > x[123] = 456 > ... > assert x[123] == 456 > > Your mapping does violate the map contract. So, you can put *anything* in that "..."? x = dict() x[123] = 456 x[123] = 789 assert x[123] == 456 dict violates the map contract. From steve+comp.lang.python at pearwood.info Wed Mar 30 01:43:23 2016 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 30 Mar 2016 16:43:23 +1100 Subject: Suggestion: make sequence and map interfaces more similar References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> Message-ID: <56fb677f$0$11121$c3e8da3@news.astraweb.com> On Wednesday 30 March 2016 14:38, Random832 wrote: > On Tue, Mar 29, 2016, at 20:56, Chris Angelico wrote: >> The map contract is this: >> >> x = StrangeDict() >> x[123] = 456 >> ... >> assert x[123] == 456 >> >> Your mapping does violate the map contract. > > So, you can put *anything* in that "..."? Yes, we're all very impressed that you spotted the trivial and obvious loophole that changing a key:value will change the key:value that you just changed *wink* but that doesn't really move the discussion anywhere. This is not an argument about dicts being mutable, because clearly they aren't. This is an argument about key:value pairs being stable. "Stable" doesn't mean "immutable". If you change the value associated with a key directly, then it will change. That's the whole point. But if you change *one* key, the relationship between *other* keys and their values shouldn't change. Given a surjection (many-to-one mapping) between keys and values in a mapping, we expect that changing the mapping of one key will not affect other keys. To be pedantic, by "change" I mean deleting the key (and, if necessary, value) or reassigning a new value to the key. To be even more pedantic, mutations to the value *do not count*. Specifically, insertions and deletions to the mapping never affect the existing keys. But, critically, insertions and deletions to a sequence do sometimes affect the index of existing items. So while we can say that there is a surjective function that maps the index of a sequence to an item, but that relationship fails to meet the requirements for it to be a mapping type like a dict. https://en.wikipedia.org/wiki/Bijection,_injection_and_surjection If somebody wants to insist that this is a kind of mapping, I can't disagree, but it isn't useful as a mapping type. -- Steven From steve+comp.lang.python at pearwood.info Wed Mar 30 01:57:25 2016 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 30 Mar 2016 16:57:25 +1100 Subject: Suggestion: make sequence and map interfaces more similar References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> Message-ID: <56fb6ac6$0$11116$c3e8da3@news.astraweb.com> On Wednesday 30 March 2016 16:43, Steven D'Aprano wrote: > This is not an argument about dicts being mutable, because clearly they > aren't. Er, I meant *immutable*. Dicts aren't immutable. -- Steve From breamoreboy at yahoo.co.uk Wed Mar 30 03:03:07 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 30 Mar 2016 08:03:07 +0100 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> Message-ID: On 29/03/2016 23:29, Marco Sulla via Python-list wrote: > > Let me add that an items() and keys() for sequences will be also > useful for day-by-day programming, since they will be a shortcut for > enumerate(seq) and range(len(seq)) > I cannot remember the last time I needed range(len(seq)) so I don't see how it can be "useful for day-by-day programming". There is usually a more Pythonic way of doing things. You need to get adjacent elements from a sequence? Use the pairwise recipe from https://docs.python.org/3/library/itertools.html. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From jussi.piitulainen at helsinki.fi Wed Mar 30 03:12:23 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Wed, 30 Mar 2016 10:12:23 +0300 Subject: Suggestion: make sequence and map interfaces more similar References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano writes: > Given a surjection (many-to-one mapping) No. And I doubt that Wikipedia says that. From smith at a-team.it Wed Mar 30 03:49:10 2016 From: smith at a-team.it (Smith) Date: Wed, 30 Mar 2016 09:49:10 +0200 Subject: Help me In-Reply-To: References: Message-ID: Il 29/03/2016 11:17, Ben Finney ha scritto: > Smith writes: > >> [a URL] > > You'll get better help if you: > > * Summarise the problem briefly in the Subject field. > > * Actually say anything useful in the message body. > thanks a lot From nevinadias3 at gmail.com Wed Mar 30 04:29:21 2016 From: nevinadias3 at gmail.com (Yum Di) Date: Wed, 30 Mar 2016 01:29:21 -0700 (PDT) Subject: HELP! With calculating Message-ID: <3b688675-4a0a-4722-9f09-c9be4541050e@googlegroups.com> import random import time print ("Welcome to Pizza Shed!") tablenum = input ("Enter table number from 1-25 \n ") while tablenum>25 or tablenum <=0: tablenum = input ("Enter the correct table number, there are only 25 tables ") #Pizza menu with prices print ("---------------------") print ("Let me help you with your order!") print ("---------------------") print ("Menu") print ( "1 = cheese and tomato: 3.50, " "2 = ham and pineapple: 4.20, " "3 = vegetarian: 5.20, " "4 = meat feast: 5.80, " "5 = seafood: 5.60 " ) pizza_choice = input("Enter the type of pizza that you want to order from 1-5 \n") while pizza_choice>5 or pizza_choice <=1: pizza_choice = input ("Enter the right number ") if pizza_choice == 1: print "You have chosen cheese and tomato. The cost for this is 3.50" elif pizza_choice == 2: print ("You have chosen ham and pineapple. The cost for this is 4.20") elif pizza_choice == 3: print ("You have chosen vegetarian. The cost for this is 5.20") elif pizza_choice == 4: print ("You have chosen meat feast. The cost for this is 5.80") elif pizza_choice == 5: print ("You have chosen sea food. The cost for this is 5.60") print ("------------------") pizza_amount = input ("Enter the amount of Pizzas that you want to order ") while pizza_amount > 10 or pizza_amount <=0: pizza_amount = input ("Maximum amount is 10, Please enter again ") print ("--------------------") #base print ("Base") print ( "1 = thin and crispy," "2 = traditional" ) base = input ("Select a base from 1-2 \n") while base>2 or base<=1: base = input ("There are only 2 types, Please enter again ") if base == 1: print "You have chosen thin and crispy" elif base == 2: print ("You have chosen traditional") print ("-------------------") #extra toppings print ("Extra Toppings") toppings = input ("Enter a number for your choice of extra topping \n Enter 1 for extra cheese \n Enter 2 for extra pepperoni \n Enter 3 for extra pineapple \n Enter 4 for extra peppers \n" ) while toppings >4 or toppings < 0: toppings = input ("There are only 4 types of extra toppings, Please try again " ) if toppings == 1: print ("You have chosen extra cheese. The cost for this is 0.50") elif toppings == 2: print ("You have chosen pepperoni. The cost for this is 0.50") elif toppings == 3: print ("You have chosen pineapple. The cost for this is 0.50") elif toppings == 4: print ("You have chosen peppers. The cost for this is 0.50") print ("-------------------------") #drink print ("Drink") print ( "1 = Cola: 0.90, " "2 = Lemonande: 0.80, " "3 = Fizzy Orange: 0.90 " ) drink = input ("Enter a number for your choice of drinks " ) while drink>3 or drink<0: drink = input ("Choices start from 0 to 3 " ) if drink == 1: print "You have chosen Cola. The cost for this is 0.90" elif drink == 2: print ("You have chosen Lemonande. The cost for this is 0.80") elif drink == 3: print ("You have chosen Fizzy Orange. The cost for this is 0.90") drink_amount = input ("Enter the amount of drinks") while drink_amount >10 or drink_amount<0: drink_amount = input (" You can only have upto 10 drinks, Please try again") print ("--------------------------------") print ("Calculating bill") print ("--------------------------------") print ("--------------------------------") print ("Thank You for ordering at Pizza Shed! ") Hey, this is my code.. I need to calculate the total cost, but I m not sure how to do that. I m still new at python. Can someone please help me From ben+python at benfinney.id.au Wed Mar 30 04:33:03 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 30 Mar 2016 19:33:03 +1100 Subject: Help me References: Message-ID: <85oa9w9xhc.fsf@benfinney.id.au> Smith writes: > Il 29/03/2016 11:17, Ben Finney ha scritto: > > You'll get better help if you: > > > > * Summarise the problem briefly in the Subject field. > > > > * Actually say anything useful in the message body. > > > thanks a lot You're welcome. Feel free to ask about the Python language here, following the advice above. -- \ ?Programs must be written for people to read, and only | `\ incidentally for machines to execute.? ?Abelson & Sussman, | _o__) _Structure and Interpretation of Computer Programs_ | Ben Finney From srkunze at mail.de Wed Mar 30 04:37:01 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Wed, 30 Mar 2016 10:37:01 +0200 Subject: Threading is foobared? In-Reply-To: <56fb1309$0$22141$c3e8da3$5496439d@news.astraweb.com> References: <56f74d00$0$1620$c3e8da3$5496439d@news.astraweb.com> <56fb1309$0$22141$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56FB902D.1090300@mail.de> On 30.03.2016 01:43, Steven D'Aprano wrote: > On Tue, 29 Mar 2016 09:26 pm, Sven R. Kunze wrote: > >> On 27.03.2016 05:01, Steven D'Aprano wrote: >>> Am I the only one who has noticed that threading of posts here is >>> severely broken? It's always been the case that there have been a few >>> posts here and there that break threading, but now it seems to be much >>> more common. >> I agree. Didn't we both already have a conversation about this? I >> thought it is my thunderbird messing things up. > I'm not using Thunderbird, so whatever the cause of the problem, it is not > specific to Thunderbird. > > > Haha, how nice. My thread view shows your reply as a sibling not a child to my mail. I assume you replied to my mail. How strange. Best, Sven From ben+python at benfinney.id.au Wed Mar 30 04:42:38 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 30 Mar 2016 19:42:38 +1100 Subject: HELP! With calculating References: <3b688675-4a0a-4722-9f09-c9be4541050e@googlegroups.com> Message-ID: <85k2kk9x1d.fsf@benfinney.id.au> Yum Di writes: > I m still new at python. > Can someone please help me Welcome to Python! Please join our dedicated beginner forum, ?python-tutor? . > Hey, this is my code.. That's a lot of code to dump all at once. If you have a specific request, please reduce the example to the very minimum needed to demonstrate the behaviour. See . -- \ ?The best in us does not require the worst in us: Our love of | `\ other human beings does not need to be nurtured by delusion.? | _o__) ?Sam Harris, at _Beyond Belief 2006_ | Ben Finney From antoon.pardon at rece.vub.ac.be Wed Mar 30 04:55:46 2016 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Wed, 30 Mar 2016 10:55:46 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56fb677f$0$11121$c3e8da3@news.astraweb.com> References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> Message-ID: <56FB9492.9030000@rece.vub.ac.be> Op 30-03-16 om 07:43 schreef Steven D'Aprano: > Yes, we're all very impressed that you spotted the trivial and obvious > loophole that changing a key:value will change the key:value that you just > changed *wink* but that doesn't really move the discussion anywhere. > > This is not an argument about dicts being mutable, because clearly they > aren't. This is an argument about key:value pairs being stable. "Stable" > doesn't mean "immutable". If you change the value associated with a key > directly, then it will change. That's the whole point. But if you change > *one* key, the relationship between *other* keys and their values shouldn't > change. > > Given a surjection (many-to-one mapping) between keys and values in a > mapping, we expect that changing the mapping of one key will not affect > other keys. To be pedantic, by "change" I mean deleting the key (and, if > necessary, value) or reassigning a new value to the key. To be even more > pedantic, mutations to the value *do not count*. I don't expect that generally. Sure there are specific mapping implementations for which this is true, but I see no reason to limit the word mapping only to those kind of data-types. What I want from a mapping is that it gives me the correct correspondence between a key and a value for the application I am using it for. If that means a "stable" mapping I'll limit the operations on that mapping as to keep it that way. Which in a number of case can be perfectly done with python-lists. So generally there is no reason to limit the word "mapping" to stable mappings. -- Antoon Pardon From srkunze at mail.de Wed Mar 30 06:07:51 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Wed, 30 Mar 2016 12:07:51 +0200 Subject: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: <56FB0FF6.3000305@harvee.org> References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA00EC.80909@gmail.com> <56FA537F.9090506@mail.de> <56FB0FF6.3000305@harvee.org> Message-ID: <56FBA577.6070607@mail.de> On 30.03.2016 01:29, Eric S. Johansson wrote: > > > On 3/29/2016 6:05 AM, Sven R. Kunze wrote: >> >> Python = English >> > As someone who writes English text and code using speech recognition, > I can assure you that Python is not English. :-) :D Interesting. Never thought of how Python sounds when spoken. Btw. the equivalence was more meant in the context of this thread. ;) Best, Sven From mail at timgolden.me.uk Wed Mar 30 06:14:49 2016 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 30 Mar 2016 11:14:49 +0100 Subject: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: <56FBA577.6070607@mail.de> References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA00EC.80909@gmail.com> <56FA537F.9090506@mail.de> <56FB0FF6.3000305@harvee.org> <56FBA577.6070607@mail.de> Message-ID: <56FBA719.5020105@timgolden.me.uk> On 30/03/2016 11:07, Sven R. Kunze wrote: > On 30.03.2016 01:29, Eric S. Johansson wrote: >> >> >> On 3/29/2016 6:05 AM, Sven R. Kunze wrote: >>> >>> Python = English >>> >> As someone who writes English text and code using speech recognition, >> I can assure you that Python is not English. :-) > > :D Interesting. Never thought of how Python sounds when spoken. Not that you quite meant this, but I'm always amused (and still a little startled) when I listen to talks recorded from, say, PyCon and hear people with American accents pronouncing Python with the stress on the slightly longer second syllable. (I don't know how other English-speaking groups say the word, but in England the first syllable is stressed and the second is the conventional short "uh" sound). TJG From steve at pearwood.info Wed Mar 30 06:17:53 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 30 Mar 2016 21:17:53 +1100 Subject: Suggestion: make sequence and map interfaces more similar References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> Message-ID: <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> On Wed, 30 Mar 2016 06:12 pm, Jussi Piitulainen wrote: > Steven D'Aprano writes: > >> Given a surjection (many-to-one mapping) > > No. And I doubt that Wikipedia says that. No to what? What are you disagreeing with? -- Steven From bc at freeuk.com Wed Mar 30 06:19:12 2016 From: bc at freeuk.com (BartC) Date: Wed, 30 Mar 2016 11:19:12 +0100 Subject: Calculate Bill In-Reply-To: References: Message-ID: On 29/03/2016 23:33, Yum Di wrote: > print ("Menu") > > print ( > "1 = cheese and tomato: 3.50, " > "2 = ham and pineapple: 4.20, " > "3 = vegetarian: 5.20, " > "4 = meat feast: 5.80, " > "5 = seafood: 5.60 " ) > Hey.. this code works. Sure, after you got rid of those list that were causing the trouble! However, i need it to calculate the total cost. > I dont know how to do that. Can someone help me.. > thanks But I think you will need a list of some sort as central place to store descriptions and prices. Several lists actually for the different menus. There are a dozen ways to this. One simple approach is below. pizzas=( ("Cheese and Tomato", 3.50), #0 ("Ham and Pineapple", 4.20,), #1 ("Vegetarian",5.20), #2 ("Meat Feast",5.80), #3 ("Seafood",5.60)) #4 descr = 0 # indices into each record cost = 1 def showmenu(menu): for number,selection in enumerate(menu,1): print ("{:>3} {:30} {:3.2f}".format(number, selection[descr],selection[cost])) showmenu(pizzas) option = 3-1 # vegetarian (3 on displayed menu is 2 in list) quantity = 2 print ("You chose",quantity,"of",pizzas[option][descr]) print ("Total is",pizzas[option][cost]*quantity) -- Bartc From bc at freeuk.com Wed Mar 30 06:21:01 2016 From: bc at freeuk.com (BartC) Date: Wed, 30 Mar 2016 11:21:01 +0100 Subject: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA00EC.80909@gmail.com> <56FA537F.9090506@mail.de> <56FB0FF6.3000305@harvee.org> Message-ID: On 30/03/2016 11:07, Sven R. Kunze wrote: > On 30.03.2016 01:29, Eric S. Johansson wrote: >> >> >> On 3/29/2016 6:05 AM, Sven R. Kunze wrote: >>> >>> Python = English >>> >> As someone who writes English text and code using speech recognition, >> I can assure you that Python is not English. :-) > > :D Interesting. Never thought of how Python sounds when spoken. Among other things, it becomes case insensitive... -- Bartc From srkunze at mail.de Wed Mar 30 06:23:10 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Wed, 30 Mar 2016 12:23:10 +0200 Subject: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: <56FBA719.5020105@timgolden.me.uk> References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA00EC.80909@gmail.com> <56FA537F.9090506@mail.de> <56FB0FF6.3000305@harvee.org> <56FBA577.6070607@mail.de> <56FBA719.5020105@timgolden.me.uk> Message-ID: <56FBA90E.4080402@mail.de> On 30.03.2016 12:14, Tim Golden wrote: > Not that you quite meant this, but I'm always amused (and still a little > startled) when I listen to talks recorded from, say, PyCon and hear > people with American accents pronouncing Python with the stress on the > slightly longer second syllable. > > (I don't know how other English-speaking groups say the word, but in > England the first syllable is stressed and the second is the > conventional short "uh" sound). > > TJG I recognize this too. I also started with the England variant but now I am not so sure anymore. :D Sven From manolo at austrohungaro.com Wed Mar 30 06:26:45 2016 From: manolo at austrohungaro.com (Manolo =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 30 Mar 2016 12:26:45 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20160330102645.GA19818@beagle> On 03/30/16 at 09:17pm, Steven D'Aprano wrote: > On Wed, 30 Mar 2016 06:12 pm, Jussi Piitulainen wrote: > > > Steven D'Aprano writes: > > > >> Given a surjection (many-to-one mapping) > > > > No. And I doubt that Wikipedia says that. > > > No to what? What are you disagreeing with? > I think it's with your definition of surjection. Bijections are surjective, no? Manolo From jussi.piitulainen at helsinki.fi Wed Mar 30 06:28:57 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Wed, 30 Mar 2016 13:28:57 +0300 Subject: Suggestion: make sequence and map interfaces more similar References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano writes: > On Wed, 30 Mar 2016 06:12 pm, Jussi Piitulainen wrote: > >> Steven D'Aprano writes: >> >>> Given a surjection (many-to-one mapping) >> >> No. And I doubt that Wikipedia says that. > > No to what? What are you disagreeing with? Surjection does not mean many-to-one mapping. It means something else. From antoon.pardon at rece.vub.ac.be Wed Mar 30 06:34:24 2016 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Wed, 30 Mar 2016 12:34:24 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56FBABB0.20807@rece.vub.ac.be> Op 30-03-16 om 12:28 schreef Jussi Piitulainen: > Steven D'Aprano writes: > >> On Wed, 30 Mar 2016 06:12 pm, Jussi Piitulainen wrote: >> >>> Steven D'Aprano writes: >>> >>>> Given a surjection (many-to-one mapping) >>> No. And I doubt that Wikipedia says that. >> No to what? What are you disagreeing with? > Surjection does not mean many-to-one mapping. It means something else. I think this is my fault. I used "surjective function" wrongly in my first response. -- Antoon. From jussi.piitulainen at helsinki.fi Wed Mar 30 06:40:08 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Wed, 30 Mar 2016 13:40:08 +0300 Subject: Suggestion: make sequence and map interfaces more similar References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> Message-ID: Manolo Mart?nez writes: > On 03/30/16 at 09:17pm, Steven D'Aprano wrote: >> On Wed, 30 Mar 2016 06:12 pm, Jussi Piitulainen wrote: >> >> > Steven D'Aprano writes: >> > >> >> Given a surjection (many-to-one mapping) >> > >> > No. And I doubt that Wikipedia says that. >> >> >> No to what? What are you disagreeing with? >> > > I think it's with your definition of surjection. Bijections are > surjective, no? Yes, and most many-to-one mappings are *not* surjective. From manolo at austrohungaro.com Wed Mar 30 06:50:35 2016 From: manolo at austrohungaro.com (Manolo =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 30 Mar 2016 12:50:35 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20160330105035.GA21190@beagle> On 03/30/16 at 01:40pm, Jussi Piitulainen wrote: > Manolo Mart?nez writes: > > > I think it's with your definition of surjection. Bijections are > > surjective, no? > > Yes, and most many-to-one mappings are *not* surjective. Well, I don't know about most, there are uncountably many surjective and non-surjective many-to-one mappings :) M From jussi.piitulainen at helsinki.fi Wed Mar 30 06:57:51 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Wed, 30 Mar 2016 13:57:51 +0300 Subject: Suggestion: make sequence and map interfaces more similar References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> Message-ID: Antoon Pardon writes: > Op 30-03-16 om 12:28 schreef Jussi Piitulainen: >> Steven D'Aprano writes: >> >>> On Wed, 30 Mar 2016 06:12 pm, Jussi Piitulainen wrote: >>> >>>> Steven D'Aprano writes: >>>> >>>>> Given a surjection (many-to-one mapping) >>>> No. And I doubt that Wikipedia says that. >>> No to what? What are you disagreeing with? >> Surjection does not mean many-to-one mapping. It means something else. > > I think this is my fault. I used "surjective function" wrongly in > my first response. Thanks. I missed that. Now I at least see why Steven may have brought the concept up at all - it doesn't seem relevant, either. From priisdk at gmail.com Wed Mar 30 07:17:14 2016 From: priisdk at gmail.com (Poul Riis) Date: Wed, 30 Mar 2016 04:17:14 -0700 (PDT) Subject: sympy Message-ID: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> Is it possible to transfer results from sympy to 'normal' python. In the case below I think my intention is clear enough but it does not work as intended. How can it be done? Poul Riis from sympy import * x=Symbol('x') ftext=diff(1/(x**2+1),x) def f(t): return ftext.subs(x,'t') print(f(3)) From jussi.piitulainen at helsinki.fi Wed Mar 30 07:21:43 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Wed, 30 Mar 2016 14:21:43 +0300 Subject: Suggestion: make sequence and map interfaces more similar References: <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> Message-ID: Manolo Mart?nez writes: > On 03/30/16 at 01:40pm, Jussi Piitulainen wrote: >> Manolo Mart?nez writes: > > >> > I think it's with your definition of surjection. Bijections are >> > surjective, no? >> >> Yes, and most many-to-one mappings are *not* surjective. > > Well, I don't know about most, there are uncountably many surjective > and non-surjective many-to-one mappings :) Ok, safer to say that some many-to-one mappings are not surjective. I was thinking of finite sets, and not even really thinking. But even with infinite domain and infinite codomain, there can be uncountably many mappings without any of them being a surjection - just have the codomain be a larger infinity. It depends on the types. Which makes the concept not easily applicable to Python data structures as such. From ben+python at benfinney.id.au Wed Mar 30 07:29:14 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 30 Mar 2016 22:29:14 +1100 Subject: sympy References: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> Message-ID: <85d1qc9pbp.fsf@benfinney.id.au> Poul Riis writes: > Is it possible to transfer results from sympy to 'normal' python. Is Sympy not ?normal Python?? What transfer are you intending? > In the case below I think my intention is clear enough but it does not > work as intended. How can it be done? First: no, your intention is not clear. Please write idiomatic Python: spaces around operators, names which describe the meaning. Follow the coding style guide PEP 8 . Second: no, the intent is obscured because you are using ?from sympy import *?. This clobbers the global namespace, making it much more difficult to tell which names come from a different namespace. Instead, do ?import sympy? and qualify names ?sympy.Symbol?, etc. Third: if the code ?does not work as intended?, then the answer can be no better than ?change it until it works as intended?. If you want more detail, please provide more detail on what it *is* doing, and what you think it *should* do instead. -- \ ?I bet one legend that keeps recurring throughout history, in | `\ every culture, is the story of Popeye.? ?Jack Handey | _o__) | Ben Finney From ned at nedbatchelder.com Wed Mar 30 07:39:10 2016 From: ned at nedbatchelder.com (Ned Batchelder) Date: Wed, 30 Mar 2016 04:39:10 -0700 (PDT) Subject: sympy In-Reply-To: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> References: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> Message-ID: <7a86698a-866f-4dc1-8ef7-80bde8afd6f6@googlegroups.com> On Wednesday, March 30, 2016 at 7:17:33 AM UTC-4, Poul Riis wrote: > Is it possible to transfer results from sympy to 'normal' python. Poul, welcome to the group. > In the case below I think my intention is clear enough but it does not work as intended. How can it be done? > > from sympy import * > x=Symbol('x') > ftext=diff(1/(x**2+1),x) > > def f(t): > return ftext.subs(x,'t') > > print(f(3)) You'd be surprised how hard it is to understand what someone else thinks a small chunk of code should do. :) Even if we can work out what this was meant to do, it will be easier to help if you are explicit about the outcome you are getting, and how that differs from the outcome you want. --Ned. From srkunze at mail.de Wed Mar 30 07:43:35 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Wed, 30 Mar 2016 13:43:35 +0200 Subject: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA00EC.80909@gmail.com> <56FA537F.9090506@mail.de> <56FB0FF6.3000305@harvee.org> Message-ID: <56FBBBE7.3030407@mail.de> On 30.03.2016 12:21, BartC wrote: > On 30/03/2016 11:07, Sven R. Kunze wrote: >> On 30.03.2016 01:29, Eric S. Johansson wrote: >>> >>> >>> On 3/29/2016 6:05 AM, Sven R. Kunze wrote: >>>> >>>> Python = English >>>> >>> As someone who writes English text and code using speech recognition, >>> I can assure you that Python is not English. :-) >> >> :D Interesting. Never thought of how Python sounds when spoken. > > Among other things, it becomes case insensitive... > Now that you mention it... ;) You do coding with speech recognition, too? From marko at pacujo.net Wed Mar 30 07:44:00 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 30 Mar 2016 14:44:00 +0300 Subject: Suggestion: make sequence and map interfaces more similar References: <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8760w4mbr3.fsf@elektro.pacujo.net> Jussi Piitulainen : > Manolo Mart?nez writes: >> On 03/30/16 at 01:40pm, Jussi Piitulainen wrote: >>> Yes, and most many-to-one mappings are *not* surjective. >> >> Well, I don't know about most, there are uncountably many surjective >> and non-surjective many-to-one mappings :) > > Ok, safer to say that some many-to-one mappings are not surjective. > > I was thinking of finite sets, and not even really thinking. But even > with infinite domain and infinite codomain, there can be uncountably > many mappings without any of them being a surjection - just have the > codomain be a larger infinity. I don't even know if you can say much about the cardinality (or countability) of mappings. The general set of mappings can't exist. The *class* of mappings does exist in some set theories, but I don't believe classes have cardinality. Marko From steve at pearwood.info Wed Mar 30 08:22:46 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 30 Mar 2016 23:22:46 +1100 Subject: Suggestion: make sequence and map interfaces more similar References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> On Wed, 30 Mar 2016 09:28 pm, Jussi Piitulainen wrote: > Steven D'Aprano writes: > >> On Wed, 30 Mar 2016 06:12 pm, Jussi Piitulainen wrote: >> >>> Steven D'Aprano writes: >>> >>>> Given a surjection (many-to-one mapping) >>> >>> No. And I doubt that Wikipedia says that. >> >> No to what? What are you disagreeing with? > > Surjection does not mean many-to-one mapping. It means something else. Oh, if only I had linked to the Wikipedia page earlier... oh wait, I did. Here it is again: https://en.wikipedia.org/wiki/Bijection,_injection_and_surjection The relevant definition is: The function is surjective (onto) if every element of the codomain is mapped to by at least one element of the domain. (That is, the image and the codomain of the function are equal.) A surjective function is a surjection. Notationally: \forall y \in B, \exists x \in A \text{ such that } y = f(x).\ and the relevant diagram is the image labelled "Non-injective and surjective", also seen here: https://en.wikipedia.org/wiki/File:Surjection.svg Why is a mapping (such as a dict) best described as a surjection? Consider: d = {1: None, 2: 'a', 3: 'b', 4: None} Every key has exactly one value. There are no values without a key, and every value has *at least* one key. To be an injection or a bijection, it must be one-to-one. Since multiple keys can map to the same value, it's not an injection or a bijection. Every value must have a key: there are no values in the dict without a key. Hence, it's a surjection. Although Wikipedia don't use the description, "many-to-one" is a good way of describing surjections, since you can have many keys mapped to a single value. To be precise, some surjections may be one-to-one, and not all many-to-one relations are surjections. But the distinguishing feature of a surjection is that each value must have *at least* one key, which describes dicts and other such mappings. And for those who don't trust Wikipedia: http://mathsforall.co.uk/userfiles/SECTION%203B%20Injective%20and%20Surjective%20functions%2027_11_06.pdf -- Steven From steve at pearwood.info Wed Mar 30 08:27:58 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 30 Mar 2016 23:27:58 +1100 Subject: Suggestion: make sequence and map interfaces more similar References: <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56fbc650$0$1622$c3e8da3$5496439d@news.astraweb.com> On Wed, 30 Mar 2016 10:21 pm, Jussi Piitulainen wrote: > Ok, safer to say that some many-to-one mappings are not surjective. Can you give an example of a Python dict which is not surjective? Or an example of something which obeys the Mapping ABC which is not surjective? Artificial and contrived examples such as this do not count: class MyDict(dict): def values(self): for value in super().values(): yield value yield object() # It's a value without a key! -- Steven From manolo at austrohungaro.com Wed Mar 30 08:29:20 2016 From: manolo at austrohungaro.com (Manolo =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 30 Mar 2016 14:29:20 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <8760w4mbr3.fsf@elektro.pacujo.net> References: <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <8760w4mbr3.fsf@elektro.pacujo.net> Message-ID: <20160330122920.GA24406@beagle> On 03/30/16 at 02:44pm, Marko Rauhamaa wrote: > Jussi Piitulainen : > > > Manolo Mart?nez writes: > >> On 03/30/16 at 01:40pm, Jussi Piitulainen wrote: > >>> Yes, and most many-to-one mappings are *not* surjective. > >> > >> Well, I don't know about most, there are uncountably many surjective > >> and non-surjective many-to-one mappings :) > > > > Ok, safer to say that some many-to-one mappings are not surjective. > > > > I was thinking of finite sets, and not even really thinking. But even > > with infinite domain and infinite codomain, there can be uncountably > > many mappings without any of them being a surjection - just have the > > codomain be a larger infinity. > > I don't even know if you can say much about the cardinality (or > countability) of mappings. The general set of mappings can't exist. The > *class* of mappings does exist in some set theories, but I don't believe > classes have cardinality. > I guess I was thinking of the cardinality of the set of tuples with members of the domain in the first member and their image in the second. Many of those sets will have a well defined cardinality (unless I'm missing something, which is entirely possible). Anyway, this is all terribly OT. Thanks for humoring me. Manolo From marko at pacujo.net Wed Mar 30 08:48:01 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 30 Mar 2016 15:48:01 +0300 Subject: Suggestion: make sequence and map interfaces more similar References: <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc650$0$1622$c3e8da3$5496439d@news.astraweb.com> Message-ID: <871t6sm8se.fsf@elektro.pacujo.net> Steven D'Aprano : > On Wed, 30 Mar 2016 10:21 pm, Jussi Piitulainen wrote: >> Ok, safer to say that some many-to-one mappings are not surjective. > > Can you give an example of a Python dict which is not surjective? Depends on the codomain. The values() method gives the range. If you have an ordinary Python dictionary that maps strings to strings, it will be neither total nor surjective. Since there are strings that are not among the keys (not total) and there are strings that are not among the values (not surjective). You can of course equate keys() with the domain and values() with the range, in which case the whole discussion becomes nonsensical. However, a collections.defaultdict instance can be both total and surjective in the meaningful senses of the words. Marko From random832 at fastmail.com Wed Mar 30 08:50:22 2016 From: random832 at fastmail.com (Random832) Date: Wed, 30 Mar 2016 08:50:22 -0400 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56fb677f$0$11121$c3e8da3@news.astraweb.com> References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> Message-ID: <1459342222.1950413.563532626.6E23EFFC@webmail.messagingengine.com> On Wed, Mar 30, 2016, at 01:43, Steven D'Aprano wrote: > This is not an argument about dicts being mutable, because clearly they > aren't. This is an argument about key:value pairs being stable. "Stable" > doesn't mean "immutable". If you change the value associated with a key > directly, then it will change. That's the whole point. But if you change > *one* key, the relationship between *other* keys and their values > shouldn't > change. This doesn't mean that an object violates the contract by having a method that changes the relationships between multiple keys and values. I had considered including an example of replacing the _whole dictionary_ with a new object in the ellipsis. Absolutely nothing is stable under a *completely unrestricted* set of operations. > Specifically, insertions and deletions to the mapping never affect the > existing keys. You can't say that, because there is no insert and delete method in the mapping interface. > If somebody wants to insist that this is a kind of mapping, I can't > disagree, but it isn't useful as a mapping type. Javascript seems to manage it just fine. From marko at pacujo.net Wed Mar 30 08:55:06 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 30 Mar 2016 15:55:06 +0300 Subject: Suggestion: make sequence and map interfaces more similar References: <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <8760w4mbr3.fsf@elektro.pacujo.net> Message-ID: <87wpokktw5.fsf@elektro.pacujo.net> Manolo Mart?nez : > On 03/30/16 at 02:44pm, Marko Rauhamaa wrote: >> I don't even know if you can say much about the cardinality (or >> countability) of mappings. The general set of mappings can't exist. >> The *class* of mappings does exist in some set theories, but I don't >> believe classes have cardinality. > > I guess I was thinking of the cardinality of the set of tuples with > members of the domain in the first member and their image in the > second. If you fix the domain and codomain, then we can discuss cardinality again, but the answer depends on the domain and codomain. For example, if the domain is the empty set, there exists precisely one function. And if the codomain is the empty set as well, that function is a bijection. Marko From steve at pearwood.info Wed Mar 30 08:56:31 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 30 Mar 2016 23:56:31 +1100 Subject: sympy References: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> Message-ID: <56fbcd01$0$1599$c3e8da3$5496439d@news.astraweb.com> On Wed, 30 Mar 2016 10:17 pm, Poul Riis wrote: > Is it possible to transfer results from sympy to 'normal' python. > > In the case below I think my intention is clear enough but it does not > work as intended. How can it be done? How can what be done? Unfortunately, we're not able to read your mind. We can read your code, and can see what your code does, but how are we supposed to know what it is supposed to do? > from sympy import * > x=Symbol('x') > ftext=diff(1/(x**2+1),x) > > def f(t): > return ftext.subs(x,'t') > > print(f(3)) This code seems to work perfectly to me. You differentiate an expression, then substitute the 'x' variable for 't': -2*t/(t**2 + 1)**2 What were you expecting? -- Steven From esj at harvee.org Wed Mar 30 09:06:07 2016 From: esj at harvee.org (Eric S. Johansson) Date: Wed, 30 Mar 2016 09:06:07 -0400 Subject: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA00EC.80909@gmail.com> <56FA537F.9090506@mail.de> <56FB0FF6.3000305@harvee.org> Message-ID: <56FBCF3F.8060903@harvee.org> On 3/30/2016 6:21 AM, BartC wrote: > On 30/03/2016 11:07, Sven R. Kunze wrote: >> On 30.03.2016 01:29, Eric S. Johansson wrote: >>> >>> >>> On 3/29/2016 6:05 AM, Sven R. Kunze wrote: >>>> >>>> Python = English >>>> >>> As someone who writes English text and code using speech recognition, >>> I can assure you that Python is not English. :-) >> >> :D Interesting. Never thought of how Python sounds when spoken. > > Among other things, it becomes case insensitive... Which makes complying with Pep 8 quite the bitch. Fortunately, I have a workaround (togglename) which lets me dictate what I need to say and preserve the spoken to code for mapping for later translation. (I.e. this thing is that thing mapping). I need a co-conspirator with better hands than mine to get through the next stage which is some form of an AST smart editor that operates on larger chunks such as idioms or snippets in a speech friendly way. Ideally I'd like to see a bidirectional transform between the spoken form and a code form so that you can edit the spoken form and regenerate the code. Just one example of what I am thinking of is when you say the string name of a previously defined class instance, you get a dialogue of all available methods and string names. When you are at the point of speaking the argument list, it gives you an abstract form of the argument list that is filled in with a minimal set of speech commands. I'm too lazy to create the full description right now what if anybody wants to know more, ask and I'll fill in the blanks. It's important to remember though that using simple or accelerated methods for creating code is the easy part of the problem. It's editing existing code that is hard because you've lost a lot of the information necessary for speech user interface. This is where I think an AST based editor will come in quite handy. So far, I haven't found any. From rosuav at gmail.com Wed Mar 30 09:09:52 2016 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 31 Mar 2016 00:09:52 +1100 Subject: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: <56FBCF3F.8060903@harvee.org> References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA00EC.80909@gmail.com> <56FA537F.9090506@mail.de> <56FB0FF6.3000305@harvee.org> <56FBCF3F.8060903@harvee.org> Message-ID: On Thu, Mar 31, 2016 at 12:06 AM, Eric S. Johansson wrote: > I need a co-conspirator with better hands than mine to get through the next > stage which is some form of an AST smart editor that operates on larger > chunks such as idioms or snippets in a speech friendly way. Ideally I'd like > to see a bidirectional transform between the spoken form and a code form so > that you can edit the spoken form and regenerate the code. Sounds to me like what you want is a variant language, a speech-friendly programming language that compiles to Python. You effectively store the spoken version, and translate it (one way) to Python for execution. ChrisA From mr.eightnoteight at gmail.com Wed Mar 30 09:10:19 2016 From: mr.eightnoteight at gmail.com (srinivas devaki) Date: Wed, 30 Mar 2016 18:40:19 +0530 Subject: Help me In-Reply-To: <85oa9w9xhc.fsf@benfinney.id.au> References: <85oa9w9xhc.fsf@benfinney.id.au> Message-ID: ahh, this is the beginning of a conspiracy to waste my time. PS: just for laughs. not to offend any one. Regards Srinivas Devaki Junior (3rd yr) student at Indian School of Mines,(IIT Dhanbad) Computer Science and Engineering Department ph: +91 9491 383 249 telegram_id: @eightnoteight On Mar 30, 2016 2:11 PM, "Ben Finney" wrote: > Smith writes: > > > Il 29/03/2016 11:17, Ben Finney ha scritto: > > > You'll get better help if you: > > > > > > * Summarise the problem briefly in the Subject field. > > > > > > * Actually say anything useful in the message body. > > > > > thanks a lot > > You're welcome. Feel free to ask about the Python language here, > following the advice above. > > -- > \ ?Programs must be written for people to read, and only | > `\ incidentally for machines to execute.? ?Abelson & Sussman, | > _o__) _Structure and Interpretation of Computer Programs_ | > Ben Finney > > -- > https://mail.python.org/mailman/listinfo/python-list > From antoon.pardon at rece.vub.ac.be Wed Mar 30 09:12:29 2016 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Wed, 30 Mar 2016 15:12:29 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56FBD0BD.5030104@rece.vub.ac.be> Op 30-03-16 om 14:22 schreef Steven D'Aprano: > On Wed, 30 Mar 2016 09:28 pm, Jussi Piitulainen wrote: > >> Steven D'Aprano writes: >> >>> On Wed, 30 Mar 2016 06:12 pm, Jussi Piitulainen wrote: >>> >>>> Steven D'Aprano writes: >>>> >>>>> Given a surjection (many-to-one mapping) >>>> No. And I doubt that Wikipedia says that. >>> No to what? What are you disagreeing with? >> Surjection does not mean many-to-one mapping. It means something else. > > Oh, if only I had linked to the Wikipedia page earlier... oh wait, I did. > Here it is again: > > https://en.wikipedia.org/wiki/Bijection,_injection_and_surjection > > > The relevant definition is: > > > The function is surjective (onto) if every element of the codomain is > mapped to by at least one element of the domain. (That is, the image and > the codomain of the function are equal.) A surjective function is a > surjection. Notationally: > > \forall y \in B, \exists x \in A \text{ such that } y = f(x).\ > > > > and the relevant diagram is the image labelled "Non-injective and > surjective", also seen here: > > https://en.wikipedia.org/wiki/File:Surjection.svg > > > Why is a mapping (such as a dict) best described as a surjection? Consider: > > d = {1: None, 2: 'a', 3: 'b', 4: None} > > > Every key has exactly one value. There are no values without a key, and > every value has *at least* one key. That second remark depends on what you consider the codomain. You could of course define the codomain as the set of actual values in the mapping, but that seems to be very artificial since it means that the codomain can changes any time a value is changed, added or removed. A more intuitive view would be that the codomain is the set of things that potentially can be a value in your mapping (in this application). So looking at your example 'c' seems to be such a potential value which for the moment doesn't have a key. So your mapping is no surjection. > To be an injection or a bijection, it must be one-to-one. Since multiple > keys can map to the same value, it's not an injection or a bijection. > > Every value must have a key: there are no values in the dict without a key. > Hence, it's a surjection. Only if you use the special python meaning of (dictionary) values in this context. If you use the ordinary (mathematical) meaning, there are lots of values that don't have a key, like every two characters string. -- Antoon. From manolo at austrohungaro.com Wed Mar 30 09:13:06 2016 From: manolo at austrohungaro.com (Manolo =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 30 Mar 2016 15:13:06 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <87wpokktw5.fsf@elektro.pacujo.net> References: <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <8760w4mbr3.fsf@elektro.pacujo.net> <87wpokktw5.fsf@elektro.pacujo.net> Message-ID: <20160330131306.GA26097@beagle> On 03/30/16 at 03:55pm, Marko Rauhamaa wrote: > Manolo Mart?nez : > > > On 03/30/16 at 02:44pm, Marko Rauhamaa wrote: > >> I don't even know if you can say much about the cardinality (or > >> countability) of mappings. The general set of mappings can't exist. > >> The *class* of mappings does exist in some set theories, but I don't > >> believe classes have cardinality. > > > > I guess I was thinking of the cardinality of the set of tuples with > > members of the domain in the first member and their image in the > > second. > > If you fix the domain and codomain, then we can discuss cardinality > again, but the answer depends on the domain and codomain. For example, > if the domain is the empty set, there exists precisely one function. And > if the codomain is the empty set as well, that function is a bijection. Yeah, what I said and you quote above is wrong: I was thinking of the cardinality of the set of those sets of tuples. This seems like the kind of thing that would result in set-theoretic paradoxes, so yes, you are probably right that the cardinality of mappings is not well defined. Manolo From alanoe at linux.vnet.ibm.com Wed Mar 30 09:13:10 2016 From: alanoe at linux.vnet.ibm.com (Alan Evangelista) Date: Wed, 30 Mar 2016 10:13:10 -0300 Subject: =?UTF-8?Q?Re:_Instala=c3=a7=c3=a3o?= In-Reply-To: References: Message-ID: <56FBD0E6.7010307@linux.vnet.ibm.com> > N?o consigo instalar o python no meu Windows,gostaria de alguma ajuda ou esclarecimento Natalia, you should use English in this mailing list. - download latest Python. Python has 2 different versions under development: Python 2 and Python 3. As you are a beginner, I recommend you use the more popular Python 2 version. Its latest version is 2.7.11. I recommend you download the Python 2.7.11 x86_64 MSI installer in https://www.python.org/ftp/python/2.7.11/python-2.7.11.amd64.msi - run the installer Python is installed. You can run it from the command line. Regards, Alan Evangelista From breamoreboy at yahoo.co.uk Wed Mar 30 09:14:18 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 30 Mar 2016 14:14:18 +0100 Subject: Adding borders to ttk radiobuttons Message-ID: I believe something like this should suffice to display borders around the radiobuttons. import tkinter as tk import tkinter.ttk as ttk root = tk.Tk() style = ttk.Style() style.configure('BW.TRadiobutton', borderwidth=5) buttonVar = tk.IntVar() rb1 = ttk.Radiobutton(text='Hello mum', variable=buttonVar, value=1) rb1.configure(style='BW.TRadiobutton') rb1.grid(row=0, column=0) rb2 = ttk.Radiobutton(text='Hello dad', variable=buttonVar, value=2) rb2.configure(style='BW.TRadiobutton') rb2.grid(row=1, column=0) root.mainloop() Sadly no borders :( What have I missed? Python 3.5.1 on Windows 10. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From ikorot01 at gmail.com Wed Mar 30 09:28:08 2016 From: ikorot01 at gmail.com (Igor Korot) Date: Wed, 30 Mar 2016 09:28:08 -0400 Subject: =?UTF-8?B?UmU6IEluc3RhbGHDp8Ojbw==?= In-Reply-To: <56FBD0E6.7010307@linux.vnet.ibm.com> References: <56FBD0E6.7010307@linux.vnet.ibm.com> Message-ID: Hi, Natalia, On Wed, Mar 30, 2016 at 9:13 AM, Alan Evangelista wrote: > >> N?o consigo instalar o python no meu Windows,gostaria de alguma ajuda ou >> esclarecimento > > > Natalia, you should use English in this mailing list. > > - download latest Python. Python has 2 different versions under development: > Python 2 and Python 3. > As you are a beginner, I recommend you use the more popular Python 2 > version. Its latest version is 2.7.11. > I recommend you download the Python 2.7.11 x86_64 MSI installer in > https://www.python.org/ftp/python/2.7.11/python-2.7.11.amd64.msi > > - run the installer > > Python is installed. You can run it from the command line. If you run into any issues during the install, you can send an e-mail here with the exact error message (possibly translated into English). Thank you. > > > Regards, > Alan Evangelista > > -- > https://mail.python.org/mailman/listinfo/python-list From breamoreboy at yahoo.co.uk Wed Mar 30 09:36:56 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 30 Mar 2016 14:36:56 +0100 Subject: =?UTF-8?Q?Re:_Instala=c3=a7=c3=a3o?= In-Reply-To: <56FBD0E6.7010307@linux.vnet.ibm.com> References: <56FBD0E6.7010307@linux.vnet.ibm.com> Message-ID: On 30/03/2016 14:13, Alan Evangelista wrote: > >> N?o consigo instalar o python no meu Windows,gostaria de alguma ajuda >> ou esclarecimento > > Natalia, you should use English in this mailing list. > > - download latest Python. Python has 2 different versions under > development: Python 2 and Python 3. > As you are a beginner, I recommend you use the more popular Python 2 > version. Its latest version is 2.7.11. I completely disagree. A beginner should definitely start with Python 3 and only use 2 if there's a library they need which hasn't yet been ported, something which is becoming increasingly rare. Grab 3.5.1 from here https://www.python.org/downloads/ -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From esj at harvee.org Wed Mar 30 09:37:00 2016 From: esj at harvee.org (Eric S. Johansson) Date: Wed, 30 Mar 2016 09:37:00 -0400 Subject: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA00EC.80909@gmail.com> <56FA537F.9090506@mail.de> <56FB0FF6.3000305@harvee.org> <56FBCF3F.8060903@harvee.org> Message-ID: <56FBD67C.5090007@harvee.org> On 3/30/2016 9:09 AM, Chris Angelico wrote: > On Thu, Mar 31, 2016 at 12:06 AM, Eric S. Johansson wrote: >> I need a co-conspirator with better hands than mine to get through the next >> stage which is some form of an AST smart editor that operates on larger >> chunks such as idioms or snippets in a speech friendly way. Ideally I'd like >> to see a bidirectional transform between the spoken form and a code form so >> that you can edit the spoken form and regenerate the code. > Sounds to me like what you want is a variant language, a > speech-friendly programming language that compiles to Python. You > effectively store the spoken version, and translate it (one way) to > Python for execution. That would be ideal but the problem comes with working with the team. I can't expect the other members the team to learn the system. I need to be able to work according to the teams rules (coding style etc.) for proper integration into an effort. Maybe I should be looking at machine learning for identifying patterns in the code and translation back to a spoken form. It be interesting to see what people could come up with though for a speech friendly Python model. I've been wrestling with the problem so long, I probably have tons of blind spots. From Cecil at decebal.nl Wed Mar 30 10:19:07 2016 From: Cecil at decebal.nl (Cecil Westerhof) Date: Wed, 30 Mar 2016 16:19:07 +0200 Subject: =?utf-8?B?SW5zdGFsYcOnw6Nv?= References: <56FBD0E6.7010307@linux.vnet.ibm.com> Message-ID: <87lh50m4kk.fsf@Equus.decebal.nl> On Wednesday 30 Mar 2016 15:36 CEST, Mark Lawrence wrote: > On 30/03/2016 14:13, Alan Evangelista wrote: >> >>> N?o consigo instalar o python no meu Windows,gostaria de alguma >>> ajuda ou esclarecimento >> >> Natalia, you should use English in this mailing list. >> >> - download latest Python. Python has 2 different versions under >> development: Python 2 and Python 3. As you are a beginner, I >> recommend you use the more popular Python 2 version. Its latest >> version is 2.7.11. > > I completely disagree. A beginner should definitely start with > Python 3 and only use 2 if there's a library they need which hasn't > yet been ported, something which is becoming increasingly rare. I agree, with one exception: if they want to run there code also in the JVM. As far as I know jython is only for Python 2. -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof From jussi.piitulainen at helsinki.fi Wed Mar 30 10:25:38 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Wed, 30 Mar 2016 17:25:38 +0300 Subject: Suggestion: make sequence and map interfaces more similar References: <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc650$0$1622$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano writes: > On Wed, 30 Mar 2016 10:21 pm, Jussi Piitulainen wrote: > >> Ok, safer to say that some many-to-one mappings are not surjective. > > Can you give an example of a Python dict which is not surjective? Can you give an example of a mapping which is not surjective? Can you represent it as a Python dict? Surjectivity requires a specified codomain. Python dicts as such do not have one. The Wikipedia article that you cite (the one that doesn't say what you think it says) is about functions f that have a specified domain, which is some set A, and a specified codomain, which is some set B. They indicate this by writing f : A -> B. (I'm not sure if I need to point out that the A and B in that notation in the text need not have anything to do with the A and B in the diagrams next to the text on top of the page. Instead they correspond to the X and Y in the diagrams.) Do you think {1: 'D', 2: 'B', 3: 'A'} is surjective? Do you think {1: 'd', 2: 'd', 3: 'c'} is surjective? Those are the Wikipedia examples of non-surjective mappings on top of the page. Strictly speaking, these dicts represent the *graphs* of the functions, and set("ABD") and set("cd") are the *images* of the two mappings. The specified codomains are not recoverable from the dicts. (Do I need to point out that the A, B, C, D and a, b, c, d in the diagrams are abstract placeholders rather than characters or one-character strings but using Python strings in their place does not change the abstract structure of the data, and it's intended in these diagrams that they are four different things when they are inside the same oval even though that doesn't seem to be made explicit in the page?) Yes, the restriction of any mapping to its image is surjective. No, this does not make it even minimally informative to say of any particular mapping that its restriction to its image is surjective - its image is its image? Of course it is. But it may be informative to say of a dict whether it has at least one key for every value *in some intended codomain* - whether its image is its codomain. That is surjectivity. (I'm running out of pedantry, but just in case: I'm quite aware that I didn't *explicitly* rule out the possibility of values in the dict but not in the intended codomain. Should I have? It's part of the notion of an intended codomain that values outside of it are not allowed at all.) I don't think this has anything to do with the topic of the thread. From ben.usenet at bsb.me.uk Wed Mar 30 10:26:38 2016 From: ben.usenet at bsb.me.uk (Ben Bacarisse) Date: Wed, 30 Mar 2016 15:26:38 +0100 Subject: Statements as expressions [was Re: Undefined behaviour in C] References: <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> <878u125ugc.fsf@nightsong.com> <720bdbcc-862d-425d-abc0-2dacaaf8f7d9@googlegroups.com> Message-ID: <87zitgujmp.fsf@bsb.me.uk> Dennis Lee Bieber writes: > On Tue, 29 Mar 2016 20:14:02 -0700 (PDT), Rustom Mody > declaimed the following: > > >>Pascal ? C ? Python is a slide down because >>Pascal had the clear distinction of procedure and function > > That goes back to FORTRAN (in which one has SUBROUTINE subprocedures, > and FUNCTION subprocedures -- yes, that is how the standard document used > to define them), which quite predates Pascal. Strangely, the precursor to > Pascal -- ALGOL -- apparently used PROC for both procedures and > functions. Algol 60 used "procedure" but it maintained the distinction in that functions had (have?) a type and subroutines didn't (don't). Algol 68 uses PROC for both and the type VOID for procedures with no value. -- Ben. From jussi.piitulainen at helsinki.fi Wed Mar 30 10:38:19 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Wed, 30 Mar 2016 17:38:19 +0300 Subject: Suggestion: make sequence and map interfaces more similar References: <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc650$0$1622$c3e8da3$5496439d@news.astraweb.com> <871t6sm8se.fsf@elektro.pacujo.net> Message-ID: Marko Rauhamaa writes: > Steven D'Aprano: > >> On Wed, 30 Mar 2016 10:21 pm, Jussi Piitulainen wrote: >>> Ok, safer to say that some many-to-one mappings are not surjective. >> >> Can you give an example of a Python dict which is not surjective? > > Depends on the codomain. The values() method gives the range. > > If you have an ordinary Python dictionary that maps strings to strings, > it will be neither total nor surjective. Since there are strings that > are not among the keys (not total) and there are strings that are not > among the values (not surjective). > > You can of course equate keys() with the domain and values() with the > range, in which case the whole discussion becomes nonsensical. > > However, a collections.defaultdict instance can be both total and > surjective in the meaningful senses of the words. The cited Wikipedia article uses "image" for what Marko here calls "range" (unfortunately it also calls individual values "images" (and the elements of the domain and codomain, "expressions"), and "range" is also sometimes used to mean codomain :). I'm just pointing this out because range aka image is a key concept here, together with codomain. From nomail at com.invalid Wed Mar 30 10:45:37 2016 From: nomail at com.invalid (ast) Date: Wed, 30 Mar 2016 16:45:37 +0200 Subject: Adding borders to ttk radiobuttons In-Reply-To: References: Message-ID: <56fbe699$0$4548$426a74cc@news.free.fr> "Mark Lawrence" a ?crit dans le message de news:mailman.204.1459343690.28225.python-list at python.org... >I believe something like this should suffice to display borders around the radiobuttons. > > import tkinter as tk > import tkinter.ttk as ttk > root = tk.Tk() > style = ttk.Style() > style.configure('BW.TRadiobutton', borderwidth=5) > buttonVar = tk.IntVar() > rb1 = ttk.Radiobutton(text='Hello mum', variable=buttonVar, value=1) > rb1.configure(style='BW.TRadiobutton') > rb1.grid(row=0, column=0) > rb2 = ttk.Radiobutton(text='Hello dad', variable=buttonVar, value=2) > rb2.configure(style='BW.TRadiobutton') > rb2.grid(row=1, column=0) > root.mainloop() > > Sadly no borders :( What have I missed? Python 3.5.1 on Windows 10. > it seems there is no border on the radio button > style.layout('BW.TRadiobutton') [('Radiobutton.padding', {'children': [('Radiobutton.indicator', {'side': 'left', 'sticky': ''}), ('Radiobutton.focus', {'side': 'left', 'sticky': '', 'children': [('Radiobutton.label', {'sticky': 'nswe'})]})], 'sticky': 'nswe'})] From nomail at com.invalid Wed Mar 30 10:55:55 2016 From: nomail at com.invalid (ast) Date: Wed, 30 Mar 2016 16:55:55 +0200 Subject: Adding borders to ttk radiobuttons In-Reply-To: <56fbe699$0$4548$426a74cc@news.free.fr> References: <56fbe699$0$4548$426a74cc@news.free.fr> Message-ID: <56fbe905$0$4540$426a74cc@news.free.fr> "ast" a ?crit dans le message de news:56fbe699$0$4548$426a74cc at news.free.fr... > > "Mark Lawrence" a ?crit dans le message de > news:mailman.204.1459343690.28225.python-list at python.org... >>I believe something like this should suffice to display borders around the radiobuttons. >> >> import tkinter as tk >> import tkinter.ttk as ttk >> root = tk.Tk() >> style = ttk.Style() >> style.configure('BW.TRadiobutton', borderwidth=5) >> buttonVar = tk.IntVar() >> rb1 = ttk.Radiobutton(text='Hello mum', variable=buttonVar, value=1) >> rb1.configure(style='BW.TRadiobutton') >> rb1.grid(row=0, column=0) >> rb2 = ttk.Radiobutton(text='Hello dad', variable=buttonVar, value=2) >> rb2.configure(style='BW.TRadiobutton') >> rb2.grid(row=1, column=0) >> root.mainloop() >> >> Sadly no borders :( What have I missed? Python 3.5.1 on Windows 10. >> > > it seems there is no border on the radio button > >> style.layout('BW.TRadiobutton') > > [('Radiobutton.padding', {'children': [('Radiobutton.indicator', {'side': 'left', 'sticky': ''}), > ('Radiobutton.focus', {'side': 'left', 'sticky': '', 'children': [('Radiobutton.label', {'sticky': > 'nswe'})]})], 'sticky': 'nswe'})] for more help: http://www.tkdocs.com/tutorial/styles.html From breamoreboy at yahoo.co.uk Wed Mar 30 11:01:07 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 30 Mar 2016 16:01:07 +0100 Subject: Adding borders to ttk radiobuttons In-Reply-To: <56fbe699$0$4548$426a74cc@news.free.fr> References: <56fbe699$0$4548$426a74cc@news.free.fr> Message-ID: On 30/03/2016 15:45, ast wrote: > > "Mark Lawrence" a ?crit dans le message de > news:mailman.204.1459343690.28225.python-list at python.org... >> I believe something like this should suffice to display borders around >> the radiobuttons. >> >> import tkinter as tk >> import tkinter.ttk as ttk >> root = tk.Tk() >> style = ttk.Style() >> style.configure('BW.TRadiobutton', borderwidth=5) >> buttonVar = tk.IntVar() >> rb1 = ttk.Radiobutton(text='Hello mum', variable=buttonVar, value=1) >> rb1.configure(style='BW.TRadiobutton') >> rb1.grid(row=0, column=0) >> rb2 = ttk.Radiobutton(text='Hello dad', variable=buttonVar, value=2) >> rb2.configure(style='BW.TRadiobutton') >> rb2.grid(row=1, column=0) >> root.mainloop() >> >> Sadly no borders :( What have I missed? Python 3.5.1 on Windows 10. >> > > it seems there is no border on the radio button > >> style.layout('BW.TRadiobutton') > > [('Radiobutton.padding', {'children': [('Radiobutton.indicator', > {'side': 'left', 'sticky': ''}), ('Radiobutton.focus', {'side': 'left', > 'sticky': '', 'children': [('Radiobutton.label', {'sticky': > 'nswe'})]})], 'sticky': 'nswe'})] That's as may be, but from Table 56 "ttk Radiobutton options not in ttk.Radiobutton" here http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-Radiobutton.html it says "borderwidth or bd - Configure this option using a style." -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at yahoo.co.uk Wed Mar 30 11:14:15 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 30 Mar 2016 16:14:15 +0100 Subject: Adding borders to ttk radiobuttons In-Reply-To: <56fbe905$0$4540$426a74cc@news.free.fr> References: <56fbe699$0$4548$426a74cc@news.free.fr> <56fbe905$0$4540$426a74cc@news.free.fr> Message-ID: On 30/03/2016 15:55, ast wrote: > > "ast" a ?crit dans le message de > news:56fbe699$0$4548$426a74cc at news.free.fr... >> >> "Mark Lawrence" a ?crit dans le message de >> news:mailman.204.1459343690.28225.python-list at python.org... >>> I believe something like this should suffice to display borders >>> around the radiobuttons. >>> >>> import tkinter as tk >>> import tkinter.ttk as ttk >>> root = tk.Tk() >>> style = ttk.Style() >>> style.configure('BW.TRadiobutton', borderwidth=5) >>> buttonVar = tk.IntVar() >>> rb1 = ttk.Radiobutton(text='Hello mum', variable=buttonVar, value=1) >>> rb1.configure(style='BW.TRadiobutton') >>> rb1.grid(row=0, column=0) >>> rb2 = ttk.Radiobutton(text='Hello dad', variable=buttonVar, value=2) >>> rb2.configure(style='BW.TRadiobutton') >>> rb2.grid(row=1, column=0) >>> root.mainloop() >>> >>> Sadly no borders :( What have I missed? Python 3.5.1 on Windows 10. >>> >> >> it seems there is no border on the radio button >> >>> style.layout('BW.TRadiobutton') >> >> [('Radiobutton.padding', {'children': [('Radiobutton.indicator', >> {'side': 'left', 'sticky': ''}), ('Radiobutton.focus', {'side': >> 'left', 'sticky': '', 'children': [('Radiobutton.label', {'sticky': >> 'nswe'})]})], 'sticky': 'nswe'})] > > for more help: > http://www.tkdocs.com/tutorial/styles.html For this particular problem not of much use, or I wouldn't be asking :( -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From priisdk at gmail.com Wed Mar 30 11:23:26 2016 From: priisdk at gmail.com (Poul Riis) Date: Wed, 30 Mar 2016 08:23:26 -0700 (PDT) Subject: sympy In-Reply-To: <56fbcd01$0$1599$c3e8da3$5496439d@news.astraweb.com> References: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> <56fbcd01$0$1599$c3e8da3$5496439d@news.astraweb.com> Message-ID: <99b7cf43-50ff-4de7-8de0-e324658682bf@googlegroups.com> What I intend to do is to let sympy find the derivative of some welldefined function and next define the foundation derivative as a normal function so that I can calculate numerical values or even make a graph. From robert.kern at gmail.com Wed Mar 30 11:29:51 2016 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 30 Mar 2016 16:29:51 +0100 Subject: sympy In-Reply-To: <99b7cf43-50ff-4de7-8de0-e324658682bf@googlegroups.com> References: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> <56fbcd01$0$1599$c3e8da3$5496439d@news.astraweb.com> <99b7cf43-50ff-4de7-8de0-e324658682bf@googlegroups.com> Message-ID: On 2016-03-30 16:23, Poul Riis wrote: > What I intend to do is to let sympy find the derivative of some welldefined function and next define the foundation derivative as a normal function so that I can calculate numerical values or even make a graph. http://docs.sympy.org/dev/modules/utilities/lambdify.html#sympy.utilities.lambdify.lambdify -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From invalid at invalid.invalid Wed Mar 30 11:36:12 2016 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 30 Mar 2016 15:36:12 +0000 (UTC) Subject: pygtk button right/middle click Message-ID: I'm trying to figure out how to get a pygtk button respond to somehting other than just a simple "left click". With a standard 3-button mouse, X11 provides at least 9 different "click" types, but the pygtk button only seems to support one of them. [Yes, I know there are left-handled mouse configurations -- by "left" click I'm using the common term to mean the primary mouse button.] After googling for some time, I haven't found any good answers. Some people just say things like "use the button_release_event signal of the button widget". But, that signal is depricated (and AFAICT still doesn't make the button actually respond to the left/middle click by "depressing" the way it should). Other answers are things like "you'll have to write you own button class in C, not C++". Is the gtk button widget really incapable of handling left or middle mouse buttons or shift/ctrl/alt modifiers? -- Grant Edwards grant.b.edwards Yow! CHUBBY CHECKER just at had a CHICKEN SANDWICH in gmail.com downtown DULUTH! From kyosohma at gmail.com Wed Mar 30 11:37:18 2016 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 30 Mar 2016 08:37:18 -0700 (PDT) Subject: ANN: Python 201 - Intermediate Python book Message-ID: <3ba58226-1196-44c8-bea5-b1c7c4833529@googlegroups.com> Hi, I just wanted to let you know that I am hard at work on my second book, which is entitled Python 201 which will come out this Fall 2016. I currently have a Kickstarter going where you can pre-order the book: https://www.kickstarter.com/projects/34257246/python-201-intermediate-python I actually posted to this list last year about what you would consider to be intermediate topics in Python. From that discussion and from some ideas I had already been working, this book was born. The book is aimed for people who already know the basics of Python but would like to learn more. It is also written with Python 3 in mind. Let me know if you have any questions. Thanks, Mike Driscoll From __peter__ at web.de Wed Mar 30 11:52:09 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 Mar 2016 17:52:09 +0200 Subject: repeat items in a list References: <8935d5dc-5e62-4fa8-8e8f-bd5b1787ee9f@googlegroups.com> <29bb9c16-eef4-4c00-9e41-ce8419405c29@googlegroups.com> <1459173882.380114.561434386.096F166A@webmail.messagingengine.com> Message-ID: Michael Selik wrote: > I prefer itertools.chain.from_iterable to the sum trick. > >>>> from itertools import chain >>>> lst = list('abc') >>>> list(chain.from_iterable([s]*3 for s in lst)) > ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'] If you want to make this completely lazy: >>> from functools import partial >>> from itertools import repeat, chain >>> items = list("abc") >>> list(chain.from_iterable(map(partial(repeat, times=3), items))) ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'] From steve at pearwood.info Wed Mar 30 11:56:43 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 31 Mar 2016 02:56:43 +1100 Subject: Suggestion: make sequence and map interfaces more similar References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> On Thu, 31 Mar 2016 12:12 am, Antoon Pardon wrote: > Op 30-03-16 om 14:22 schreef Steven D'Aprano: [...] >> Why is a mapping (such as a dict) best described as a surjection? >> Consider: >> >> d = {1: None, 2: 'a', 3: 'b', 4: None} >> >> >> Every key has exactly one value. There are no values without a key, and >> every value has *at least* one key. > > That second remark depends on what you consider the codomain. You could > of course define the codomain as the set of actual values in the mapping, > but that seems to be very artificial since it means that the codomain can > changes any time a value is changed, added or removed. But that's exactly what the mapping does. Let's start with something that looks like a mathematical mapping, a function f(x) from positive integers to positive integers: f(x) = x**2 Here's our dict: d = {1: 1, 2: 4, 3: 9, 4: 16} You're saying that the codomain should be "all positive integers", and likewise the domain. But this is wrong, because the mapping d isn't defined for all positive integers: d[5] # raise KeyError We can only say that the domain is the *actual keys in the dict*. And likewise for the codomain. We can't say that the codomain is all positive integers, since the mapping is not defined for any values of x except the given keys. Because dicts are mutable, we can do this: d[2] = 7 but that's precisely what we *can't* do with mathematical functions! We can't just declare that, from now on, x**2 will equal 7 if x is 2. So any modification of the dict must give us a new and different function. Before, we had the function: # d equivalent to f(x): {1,2,3,4} --> {1,4,9,16} where f(1) = 1 f(2) = 4 f(3) = 9 f(4) = 16 After executing the line d[2] = 7, we have the completely different function: f(x): {1,2,3,4} --> {1,7,9,16} where f(1) = 1 f(2) = 7 f(3) = 9 f(4) = 16 Now consider what happens when we execute: del d[4] d['a'] = None That's the nature of dicts as mappings: they don't actually come very close to the semantics of mathematical functions. Any talk of surjections, domains, codomains etc is going to be, at best, an analogy. So all of this discussion is stretching the mathematical terms to their breaking point. Dicts aren't actually functions in the mathematical sense, and in the general case, they don't have well-defined domains and codomains. Describing them as surjective (or any other such term) requires a lot of hand-waving. I happen to think that the analogy works very well (otherwise I wouldn't have given it), but others think I'm being sloppy, well, yes I am, and I'll withdraw it. Because fundamentally, it doesn't matter whether dicts are surjections or not. They're still many-to-one mappings, and those mappings between keys and values should not change due to the insertion or deletion of unrelated keys. If the OP wants to create his own "StrangeDict", which he himself described as "terrible", then he can do so. But to make all dicts and lists behave in this "terrible" and "strange" way is a terrible idea. [...] > Only if you use the special python meaning of (dictionary) values in this > context. If you use the ordinary (mathematical) meaning, there are lots of > values that don't have a key, like every two characters string. Well, we're actually discussing Python dictionaries. So, damn straight, of course I'm going to use the meaning of words as they apply to dicts. -- Steven From rosuav at gmail.com Wed Mar 30 11:58:11 2016 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 31 Mar 2016 02:58:11 +1100 Subject: pygtk button right/middle click In-Reply-To: References: Message-ID: On Thu, Mar 31, 2016 at 2:36 AM, Grant Edwards wrote: > I'm trying to figure out how to get a pygtk button respond to > somehting other than just a simple "left click". With a standard > 3-button mouse, X11 provides at least 9 different "click" types, but > the pygtk button only seems to support one of them. You're looking at a couple of different, but related, things. The clicked() event means "the button was activated", which might have been caused by a mouse event, or possibly a keyboard or other activation. What you want is to react to other forms of mouse event. For that, you should be able to hook the generic widget handling... > After googling for some time, I haven't found any good answers. Some > people just say things like "use the button_release_event signal of > the button widget". ... which is what this is talking about. What you'll get is button press and release events, and it'll be up to you to figure out if they represent clicks or not. But you'll get events for every mouse button that way. ChrisA From steve at pearwood.info Wed Mar 30 11:59:34 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 31 Mar 2016 02:59:34 +1100 Subject: sympy References: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> <56fbcd01$0$1599$c3e8da3$5496439d@news.astraweb.com> <99b7cf43-50ff-4de7-8de0-e324658682bf@googlegroups.com> Message-ID: <56fbf7e7$0$1591$c3e8da3$5496439d@news.astraweb.com> On Thu, 31 Mar 2016 02:23 am, Poul Riis wrote: > What I intend to do is to let sympy find the derivative of some > welldefined function and next define the foundation derivative as a normal > function so that I can calculate numerical values or even make a graph. I'm glad you explained what you *actually* wanted, because I was going to guess that you wanted to evaluate the derivative at x = 3: py> ftext.evalf(subs={x:3}) -0.0600000000000000 -- Steven From steve at pearwood.info Wed Mar 30 12:02:00 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 31 Mar 2016 03:02:00 +1100 Subject: Suggestion: make sequence and map interfaces more similar References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> Message-ID: <56fbf879$0$1591$c3e8da3$5496439d@news.astraweb.com> On Wed, 30 Mar 2016 11:50 pm, Random832 wrote: > Absolutely nothing is stable under a *completely unrestricted* set of > operations. Yes, you're absolutely correct. If I create a Python dict, {1: 'a'}, and then smash the computer to smithereens with a 50lb sledge hammer, neither the key nor the value will still be accessible. Well done. I never would have thought of that violation of the dict invariants without you. >> Specifically, insertions and deletions to the mapping never affect the >> existing keys. > > You can't say that, because there is no insert and delete method in the > mapping interface. There are in the dict API though. # insertions d[key] = value # deletions del d[key] >> If somebody wants to insist that this is a kind of mapping, I can't >> disagree, but it isn't useful as a mapping type. > > Javascript seems to manage it just fine. I wouldn't exactly hold Javascript up as the exemplar of intelligent design decisions. -- Steven From tjreedy at udel.edu Wed Mar 30 12:35:39 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Mar 2016 12:35:39 -0400 Subject: Adding borders to ttk radiobuttons In-Reply-To: References: <56fbe699$0$4548$426a74cc@news.free.fr> Message-ID: On 3/30/2016 11:01 AM, Mark Lawrence via Python-list wrote: > On 30/03/2016 15:45, ast wrote: >> >> "Mark Lawrence" a ?crit dans le message de >> news:mailman.204.1459343690.28225.python-list at python.org... >>> I believe something like this should suffice to display borders around >>> the radiobuttons. >>> >>> import tkinter as tk >>> import tkinter.ttk as ttk >>> root = tk.Tk() >>> style = ttk.Style() >>> style.configure('BW.TRadiobutton', borderwidth=5) >>> buttonVar = tk.IntVar() >>> rb1 = ttk.Radiobutton(text='Hello mum', variable=buttonVar, value=1) >>> rb1.configure(style='BW.TRadiobutton') >>> rb1.grid(row=0, column=0) >>> rb2 = ttk.Radiobutton(text='Hello dad', variable=buttonVar, value=2) >>> rb2.configure(style='BW.TRadiobutton') >>> rb2.grid(row=1, column=0) >>> root.mainloop() >>> >>> Sadly no borders :( What have I missed? Python 3.5.1 on Windows 10. >>> >> >> it seems there is no border on the radio button >> >>> style.layout('BW.TRadiobutton') >> >> [('Radiobutton.padding', {'children': [('Radiobutton.indicator', >> {'side': 'left', 'sticky': ''}), ('Radiobutton.focus', {'side': 'left', >> 'sticky': '', 'children': [('Radiobutton.label', {'sticky': >> 'nswe'})]})], 'sticky': 'nswe'})] > > That's as may be, but from Table 56 "ttk Radiobutton options not in > ttk.Radiobutton" here > http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-Radiobutton.html > it says "borderwidth or bd - Configure this option using a style." Components depend on the theme. In some themes, Radiobutton does have a border. On Windows 10, I ran >>> for s in style.theme_names(): style.theme_use(s) style.theme_use() style.layout('TRadiobutton') Theme names are ('winnative', 'clam', 'alt', 'default', 'classic', 'vista', 'xpnative') with 'vista'the default. Outputs were the same as above 'vista' [('Radiobutton.padding', {'sticky': 'nswe', 'children': [('Radiobutton.indicator', {'sticky': '', 'side': 'left'}), ('Radiobutton.focus', {'sticky': '', 'children': [('Radiobutton.label', {'sticky': 'nswe'})], 'side': 'left'})]})] except for this 'classic' [('Radiobutton.highlight', {'sticky': 'nswe', 'children': [('Radiobutton.border', {'sticky': 'nswe', 'children': [('Radiobutton.padding', {'sticky': 'nswe', 'children': [('Radiobutton.indicator', {'sticky': '', 'side': 'left'}), ('Radiobutton.label', {'sticky': 'nswe', 'side': 'left'})]})]})]})] .theme_names() only displays the themes for the OS. I believe that there is a way to access themes for other OSes (unix, mac) but don't remember. -- Terry Jan Reedy From ethan at stoneleaf.us Wed Mar 30 12:38:05 2016 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 30 Mar 2016 09:38:05 -0700 Subject: Help me In-Reply-To: References: <85oa9w9xhc.fsf@benfinney.id.au> Message-ID: <56FC00ED.8000309@stoneleaf.us> On 03/30/2016 06:10 AM, srinivas devaki wrote: > ahh, this is the beginning of a conspiracy to waste my time. > > PS: just for laughs. not to offend any one. It's fair: you waste ours, we waste yours. :) A fair, if not good, trade. -- ~Ethan~ From tjreedy at udel.edu Wed Mar 30 12:38:27 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Mar 2016 12:38:27 -0400 Subject: Adding borders to ttk radiobuttons In-Reply-To: References: <56fbe699$0$4548$426a74cc@news.free.fr> <56fbe905$0$4540$426a74cc@news.free.fr> Message-ID: On 3/30/2016 11:14 AM, Mark Lawrence via Python-list wrote: > On 30/03/2016 15:55, ast wrote: >> >> "ast" a ?crit dans le message de >> news:56fbe699$0$4548$426a74cc at news.free.fr... >>> >>> "Mark Lawrence" a ?crit dans le message de >>> news:mailman.204.1459343690.28225.python-list at python.org... >>>> I believe something like this should suffice to display borders >>>> around the radiobuttons. >>>> >>>> import tkinter as tk >>>> import tkinter.ttk as ttk >>>> root = tk.Tk() >>>> style = ttk.Style() >>>> style.configure('BW.TRadiobutton', borderwidth=5) >>>> buttonVar = tk.IntVar() >>>> rb1 = ttk.Radiobutton(text='Hello mum', variable=buttonVar, value=1) >>>> rb1.configure(style='BW.TRadiobutton') >>>> rb1.grid(row=0, column=0) >>>> rb2 = ttk.Radiobutton(text='Hello dad', variable=buttonVar, value=2) >>>> rb2.configure(style='BW.TRadiobutton') >>>> rb2.grid(row=1, column=0) >>>> root.mainloop() >>>> >>>> Sadly no borders :( What have I missed? Python 3.5.1 on Windows 10. >>>> >>> >>> it seems there is no border on the radio button >>> >>>> style.layout('BW.TRadiobutton') >>> >>> [('Radiobutton.padding', {'children': [('Radiobutton.indicator', >>> {'side': 'left', 'sticky': ''}), ('Radiobutton.focus', {'side': >>> 'left', 'sticky': '', 'children': [('Radiobutton.label', {'sticky': >>> 'nswe'})]})], 'sticky': 'nswe'})] >> >> for more help: >> http://www.tkdocs.com/tutorial/styles.html > > For this particular problem not of much use, or I wouldn't be asking :( This page has some of the info needed to get a radiobutton with a border, at least my machine. See my answer to your other response. -- Terry Jan Reedy From random832 at fastmail.com Wed Mar 30 12:52:16 2016 From: random832 at fastmail.com (Random832) Date: Wed, 30 Mar 2016 12:52:16 -0400 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56fbf879$0$1591$c3e8da3$5496439d@news.astraweb.com> References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fbf879$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1459356736.2010715.563787058.488E77C8@webmail.messagingengine.com> This discussion is getting a bit distracted from the original request. Let's look at it from a higher level. What is being requested, regardless of if you call it a "map interface" or whatever, is a single way, for sequences and maps... broadly, anything with a __getitem__, to iterate over all values which one might pass to __getitem__, so that one might (among other things) call __setitem__ to mutate the collection. Like, these are common patterns: for i, x in enumerate(l): # do some stuff, sometimes assign l[i] for k, v in d.items(): # do some stuff, sometimes assign d[k] A way to apply that pattern generically to an object which may be either a sequence or a mapping might be nice. Or some other way of doing this operation - maybe a writable iterator like C++ or Java. From rustompmody at gmail.com Wed Mar 30 12:59:56 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 30 Mar 2016 09:59:56 -0700 (PDT) Subject: Statements as expressions [was Re: Undefined behaviour in C] In-Reply-To: <87zitgujmp.fsf@bsb.me.uk> References: <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> <878u125ugc.fsf@nightsong.com> <720bdbcc-862d-425d-abc0-2dacaaf8f7d9@googlegroups.com> <87zitgujmp.fsf@bsb.me.uk> Message-ID: On Wednesday, March 30, 2016 at 7:56:50 PM UTC+5:30, Ben Bacarisse wrote: > Dennis Lee Bieber writes: Sorry Dennis Dont see you at all Neither on googlegroups -- which of course everyone loves to hate Nor the archive: https://mail.python.org/pipermail/python-list/2016-March/date.html Only see your posts when someone quotes them Yes Fortran (and Basic) had procedures and functions At least the BBC-micros that I grew up on had that distinction From random832 at fastmail.com Wed Mar 30 13:07:37 2016 From: random832 at fastmail.com (Random832) Date: Wed, 30 Mar 2016 13:07:37 -0400 Subject: Statements as expressions [was Re: Undefined behaviour in C] In-Reply-To: References: <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> <878u125ugc.fsf@nightsong.com> <720bdbcc-862d-425d-abc0-2dacaaf8f7d9@googlegroups.com> <87zitgujmp.fsf@bsb.me.uk> Message-ID: <1459357657.2013677.563815506.596B2C8F@webmail.messagingengine.com> On Wed, Mar 30, 2016, at 12:59, Rustom Mody wrote: > On Wednesday, March 30, 2016 at 7:56:50 PM UTC+5:30, Ben Bacarisse wrote: > > Dennis Lee Bieber writes: > > Sorry Dennis > Dont see you at all > Neither on googlegroups -- which of course everyone loves to hate > Nor the archive: > https://mail.python.org/pipermail/python-list/2016-March/date.html Looking at the headers of his emails, I see "X-No-Archive: YES" From rustompmody at gmail.com Wed Mar 30 13:28:02 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 30 Mar 2016 10:28:02 -0700 (PDT) Subject: Statements as expressions [was Re: Undefined behaviour in C] In-Reply-To: References: <87poug5t0c.fsf@nightsong.com> <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> <878u125ugc.fsf@nightsong.com> <720bdbcc-862d-425d-abc0-2dacaaf8f7d9@googlegroups.com> <87zitgujmp.fsf@bsb.me.uk> Message-ID: <9fdb4edf-7a57-46ea-91f1-3f7b1fe5c3f1@googlegroups.com> On Wednesday, March 30, 2016 at 10:37:58 PM UTC+5:30, Random832 wrote: > On Wed, Mar 30, 2016, at 12:59, Rustom Mody wrote: > > On Wednesday, March 30, 2016 at 7:56:50 PM UTC+5:30, Ben Bacarisse wrote: > > > Dennis Lee Bieber writes: > > > > Sorry Dennis > > Dont see you at all > > Neither on googlegroups -- which of course everyone loves to hate > > Nor the archive: > > https://mail.python.org/pipermail/python-list/2016-March/date.html > > Looking at the headers of his emails, I see "X-No-Archive: YES" Yes Earlier I used to see (in GG) Dennis' posts with some message such as "Will be removed in 6 days" or some such Now not at all. From salvatore.didio at gmail.com Wed Mar 30 13:32:59 2016 From: salvatore.didio at gmail.com (Salvatore DI DIO) Date: Wed, 30 Mar 2016 10:32:59 -0700 (PDT) Subject: ArtWork in PyPyBox - Pure Python Message-ID: In pure Python, here is a nice image (for me at least) http://salvatore.diodev.fr/pypybox/ Regards From invalid at invalid.invalid Wed Mar 30 13:44:10 2016 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 30 Mar 2016 17:44:10 +0000 (UTC) Subject: pygtk button right/middle click References: Message-ID: On 2016-03-30, Chris Angelico wrote: > On Thu, Mar 31, 2016 at 2:36 AM, Grant Edwards wrote: >> I'm trying to figure out how to get a pygtk button respond to >> somehting other than just a simple "left click". With a standard >> 3-button mouse, X11 provides at least 9 different "click" types, but >> the pygtk button only seems to support one of them. > > You're looking at a couple of different, but related, things. The > clicked() event means "the button was activated", which might have > been caused by a mouse event, or possibly a keyboard or other > activation. Right. > What you want is to react to other forms of mouse event. For that, > you should be able to hook the generic widget handling... So I've got to re-implement all the low-level stuff that the button already does for the "left" button (changing appearance on button-press and restoring it on button-release), calling the handler, etc. I sure seems like the batteries are missing... -- Grant Edwards grant.b.edwards Yow! Hmmm ... A hash-singer at and a cross-eyed guy were gmail.com SLEEPING on a deserted island, when ... From walters.justin01 at gmail.com Wed Mar 30 13:59:08 2016 From: walters.justin01 at gmail.com (justin walters) Date: Wed, 30 Mar 2016 10:59:08 -0700 Subject: ANN: Python 201 - Intermediate Python book In-Reply-To: <3ba58226-1196-44c8-bea5-b1c7c4833529@googlegroups.com> References: <3ba58226-1196-44c8-bea5-b1c7c4833529@googlegroups.com> Message-ID: On Mar 30, 2016 8:41 AM, "Mike Driscoll" wrote: > > Hi, > > I just wanted to let you know that I am hard at work on my second book, which is entitled Python 201 which will come out this Fall 2016. I currently have a Kickstarter going where you can pre-order the book: https://www.kickstarter.com/projects/34257246/python-201-intermediate-python > > I actually posted to this list last year about what you would consider to be intermediate topics in Python. From that discussion and from some ideas I had already been working, this book was born. The book is aimed for people who already know the basics of Python but would like to learn more. It is also written with Python 3 in mind. > > Let me know if you have any questions. > > Thanks, > Mike Driscoll > > -- > https://mail.python.org/mailman/listinfo/python-list Can you go over a couple of the topics you are going to cover? Are you going to cover any of the most popular packages such as Django and scrapy? From kyosohma at gmail.com Wed Mar 30 14:15:19 2016 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 30 Mar 2016 11:15:19 -0700 (PDT) Subject: ANN: Python 201 - Intermediate Python book In-Reply-To: References: <3ba58226-1196-44c8-bea5-b1c7c4833529@googlegroups.com> Message-ID: <649ede42-4ce4-43d8-bff8-5d207c4511c1@googlegroups.com> Hi Justin, > > https://mail.python.org/mailman/listinfo/python-list > > Can you go over a couple of the topics you are going to cover? > > Are you going to cover any of the most popular packages such as Django and > scrapy? Sure! I'm planning on covering several of the more popular intermediate-level modules from Python's standard library, such as collections, contextlib, functools and itertools. I am also going to be covering benchmarking, encryption, connecting to databases, etc. There is a section on Web-related chapters. While I don't plan to cover a web framework, I am going to cover other items related to working with the internet using Python. I do plan to talk about creating a web crawler / scraper, but I hadn't decided if I was going to use scrapy for that or not. I also plan to write about working with web APIs, such as Amazon's or Google's APIs. There will probably be some kind of chapter about Selenium / Web Driver too. I have some other ideas too. I hope that answered your question. Mike From walters.justin01 at gmail.com Wed Mar 30 14:41:47 2016 From: walters.justin01 at gmail.com (justin walters) Date: Wed, 30 Mar 2016 11:41:47 -0700 Subject: ANN: Python 201 - Intermediate Python book In-Reply-To: <649ede42-4ce4-43d8-bff8-5d207c4511c1@googlegroups.com> References: <3ba58226-1196-44c8-bea5-b1c7c4833529@googlegroups.com> <649ede42-4ce4-43d8-bff8-5d207c4511c1@googlegroups.com> Message-ID: On Mar 30, 2016 11:21 AM, "Mike Driscoll" wrote: > > Hi Justin, > > > > https://mail.python.org/mailman/listinfo/python-list > > > > Can you go over a couple of the topics you are going to cover? > > > > Are you going to cover any of the most popular packages such as Django and > > scrapy? > > Sure! I'm planning on covering several of the more popular intermediate-level modules from Python's standard library, such as collections, contextlib, functools and itertools. > > I am also going to be covering benchmarking, encryption, connecting to databases, etc. > > There is a section on Web-related chapters. While I don't plan to cover a web framework, I am going to cover other items related to working with the internet using Python. I do plan to talk about creating a web crawler / scraper, but I hadn't decided if I was going to use scrapy for that or not. I also plan to write about working with web APIs, such as Amazon's or Google's APIs. There will probably be some kind of chapter about Selenium / Web Driver too. I have some other ideas too. > > I hope that answered your question. > > Mike > -- > https://mail.python.org/mailman/listinfo/python-list That absolutely answers my questions. I'll keep an eye out for your book when it is realeased. It seems like it will cover some topics that could be useful in continuing my learning. I am especially interested in encryption as that is something I have yet to dive into. From antoon.pardon at rece.vub.ac.be Wed Mar 30 15:07:29 2016 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Wed, 30 Mar 2016 21:07:29 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56FC23F1.9060000@rece.vub.ac.be> Op 30-03-16 om 17:56 schreef Steven D'Aprano: > On Thu, 31 Mar 2016 12:12 am, Antoon Pardon wrote: > >> Op 30-03-16 om 14:22 schreef Steven D'Aprano: > > [...] >>> Why is a mapping (such as a dict) best described as a surjection? >>> Consider: >>> >>> d = {1: None, 2: 'a', 3: 'b', 4: None} >>> >>> >>> Every key has exactly one value. There are no values without a key, and >>> every value has *at least* one key. >> >> That second remark depends on what you consider the codomain. You could >> of course define the codomain as the set of actual values in the mapping, >> but that seems to be very artificial since it means that the codomain can >> changes any time a value is changed, added or removed. > > But that's exactly what the mapping does. No it generally doesn't. I see no reason when at one moment I can write the following. assert map.values == {2, 5, 7, 9} map[3] = 8 to claim the codomain has changed. The actual function has changed yes but since the application shows that the universe of possible mapping represented by this specific variable containes functions in which 8 is an element of the function image. This is best expressed by saying 8 is part of the codomain whether or not 8 is part of the actual values at any specific moment. Sure you sometimes work with a map in which the image is the domain, like you did with your map of a limit square function but I consider those as exceptions, not the general case. > And likewise for the codomain. We can't say that the codomain is all > positive integers, since the mapping is not defined for any values of x > except the given keys. > > Because dicts are mutable, we can do this: > > d[2] = 7 > > > but that's precisely what we *can't* do with mathematical functions! We > can't just declare that, from now on, x**2 will equal 7 if x is 2. So any > modification of the dict must give us a new and different function. Before, > we had the function: So? The best way IMO to look at this is as a family of functions between a domain and a codomain. Because that is the problem space you are looking at. If within this problem space you have found a surjection, the normal way to understand that is that you have found a function in which the image is the total of the possible value set. > # d equivalent to > f(x): {1,2,3,4} --> {1,4,9,16} where > f(1) = 1 > f(2) = 4 > f(3) = 9 > f(4) = 16 > > > After executing the line d[2] = 7, we have the completely different > function: So? Since this change of a function is presumably a step in searching a solution within some problem space, the domain and codomain of both functions are the same. Even if the function is not total nor surjective in this way. > That's the nature of dicts as mappings: they don't actually come very close > to the semantics of mathematical functions. Any talk of surjections, > domains, codomains etc is going to be, at best, an analogy. At any specific time a dictionary is a perfect representation of a mathematical function. > So all of this discussion is stretching the mathematical terms to their > breaking point. Dicts aren't actually functions in the mathematical sense, > and in the general case, they don't have well-defined domains and > codomains. But that part of the problem you represent by the dictionary often enough has a well defined domain and codomain. > Because fundamentally, it doesn't matter whether dicts are surjections or > not. They're still many-to-one mappings, and those mappings between keys > and values should not change due to the insertion or deletion of unrelated > keys. Repeating your opion without further arguments doesn't lend any support to that opinion. If within the problem space you are working on, such a change would make sense as a step to generate the next mapping from the previous one, i don't see what the problem is if one could make use of this. > If the OP wants to create his own "StrangeDict", which he himself described > as "terrible", then he can do so. But to make all dicts and lists behave in > this "terrible" and "strange" way is a terrible idea. Calling something a terrible idea isn't a strong arguement. Other "terrible" ideas have made it in the language. > [...] >> Only if you use the special python meaning of (dictionary) values in this >> context. If you use the ordinary (mathematical) meaning, there are lots of >> values that don't have a key, like every two characters string. > > Well, we're actually discussing Python dictionaries. So, damn straight, of > course I'm going to use the meaning of words as they apply to dicts. How so? We were talking about functions and how dicts could represent them. So when next we talk about a characteristic of such functions I don't see why we should use the meaning as they apply to dicts, since we weren't talking about the dicts. -- Antoon. From best_lay at yahoo.com Wed Mar 30 15:16:34 2016 From: best_lay at yahoo.com (Wildman) Date: Wed, 30 Mar 2016 14:16:34 -0500 Subject: pygtk button right/middle click References: Message-ID: On Wed, 30 Mar 2016 15:36:12 +0000, Grant Edwards wrote: > I'm trying to figure out how to get a pygtk button respond to > somehting other than just a simple "left click". With a standard > 3-button mouse, X11 provides at least 9 different "click" types, but > the pygtk button only seems to support one of them. > > [Yes, I know there are left-handled mouse configurations -- by "left" > click I'm using the common term to mean the primary mouse button.] > > After googling for some time, I haven't found any good answers. Some > people just say things like "use the button_release_event signal of > the button widget". > > But, that signal is depricated (and AFAICT still doesn't make the > button actually respond to the left/middle click by "depressing" the > way it should). > > Other answers are things like "you'll have to write you own button > class in C, not C++". > > Is the gtk button widget really incapable of handling left or middle > mouse buttons or shift/ctrl/alt modifiers? This might help... http://faq.pygtk.org/index.py?req=show&file=faq05.004.htp -- GNU/Linux user #557453 May the Source be with you. From ethan at stoneleaf.us Wed Mar 30 15:21:26 2016 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 30 Mar 2016 12:21:26 -0700 Subject: ANN: Python 201 - Intermediate Python book In-Reply-To: References: <3ba58226-1196-44c8-bea5-b1c7c4833529@googlegroups.com> <649ede42-4ce4-43d8-bff8-5d207c4511c1@googlegroups.com> Message-ID: <56FC2736.7000800@stoneleaf.us> On 03/30/2016 11:41 AM, justin walters wrote: > That absolutely answers my questions. I'll keep an eye out for your book > when it is realeased. It seems like it will cover some topics that could be > useful in continuing my learning. KickStarter plug: If you want to pledge to buying the book now on KickStarter, that will guarantee you the book when it comes out, plus contribute to possibly have more content in the book as higher reward levels are unlocked. Currenty his book is past the "it will definitely happen" stage, and the next reward level will unsure even more content. Note: I'm not affiliated with the book, probably won't pledge (only a couple topics apply to me), but I am a KickStarter fan (having purchased more games than was probably wise ;) . -- ~Ethan~ From invalid at invalid.invalid Wed Mar 30 15:21:32 2016 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 30 Mar 2016 19:21:32 +0000 (UTC) Subject: pygtk button right/middle click References: Message-ID: On 2016-03-30, Wildman wrote: >> Is the gtk button widget really incapable of handling left or middle >> mouse buttons or shift/ctrl/alt modifiers? > > This might help... > > http://faq.pygtk.org/index.py?req=show&file=faq05.004.htp Yep, I found that. I'm just missing the clues required to use those two pieces. -- Grant Edwards grant.b.edwards Yow! My face is new, my at license is expired, and I'm gmail.com under a doctor's care!!!! From invalid at invalid.invalid Wed Mar 30 15:23:35 2016 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 30 Mar 2016 19:23:35 +0000 (UTC) Subject: pygtk button right/middle click References: Message-ID: On 2016-03-30, Grant Edwards wrote: > On 2016-03-30, Wildman wrote: > >>> Is the gtk button widget really incapable of handling left or middle >>> mouse buttons or shift/ctrl/alt modifiers? >> >> This might help... >> >> http://faq.pygtk.org/index.py?req=show&file=faq05.004.htp > > Yep, I found that. I'm just missing the clues required to use those > two pieces. FWIW, I've decided to give up on this. Since it took only a few lines of code to handle the "left" click, I assumed that like some other toolkits, it would be similarly easy to handle "right" and "middle". I don't have the time to re-invent the wheel at the moment, so this project will have to be postponed. -- Grant Edwards grant.b.edwards Yow! I want to mail a at bronzed artichoke to gmail.com Nicaragua! From mail.python.org at marco.sulla.e4ward.com Wed Mar 30 15:35:59 2016 From: mail.python.org at marco.sulla.e4ward.com (Marco Sulla) Date: Wed, 30 Mar 2016 21:35:59 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 30 March 2016 at 02:55, Terry Reedy wrote: > To me [seq.items() and seq.keys()] are useless and confusing duplications since enumerate()(seq) > and range(len(seq)) are quite different from dict.items and dict.keys. It's true. Indeed IMHO it's enumerate() that will be a confusing duplication. On 30 March 2016 at 02:55, Terry Reedy wrote: > At least in CPython, changing a dict disables view iterators. OrderedDict does not. On 30 March 2016 at 07:43, Steven D'Aprano wrote: > This is not an argument about dicts being mutable, because clearly they > aren't. This is an argument about key:value pairs being stable. So you basically say "I expect to get the value x from key y". Let me apply your point of view to lists. In lists, I expect to get the value x from index y. If I insert an item in a position before index y, I expect to get x at index y+1. But what if I write a class with a method insertPlus() that sets None at y+1 and x at y+2? I can say it does not violate the list contract, since you're extending the base class and implementing a new method that is not present in base class. If you extend a dict to act as a list, you're only adding *constraints* to existing methods and adding new methods. You're not completely change the existing ones, so the implementation is perfectly valid. Finally, let me quote the official docs: A mapping object maps hashable values to arbitrary objects [...] A dictionary?s keys are almost arbitrary values [...] https://docs.python.org/3/library/stdtypes.html#dict Mapping:A container object that supports arbitrary key lookups https://docs.python.org/3/glossary.html#term-mapping A sequence satisfies all these requirements, with the only exception that keys are not arbitrary. But no one will tell you that a child class that make a *restriction* over the original one will break rules. On 30 March 2016 at 17:56, Steven D'Aprano wrote: > If the OP wants to create his own "StrangeDict", which he himself described > as "terrible", then he can do so. But to make all dicts and lists behave in > this "terrible" and "strange" way is a terrible idea. You did not understand well what I mean, my dear friend. I applied the word "terrible" to my code, not to the concept. You've demonstrated that a fair thinker, so do not fall in the temptation to play with words. From mail.python.org at marco.sulla.e4ward.com Wed Mar 30 16:00:58 2016 From: mail.python.org at marco.sulla.e4ward.com (Marco Sulla) Date: Wed, 30 Mar 2016 22:00:58 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56fbf879$0$1591$c3e8da3$5496439d@news.astraweb.com> References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fbf879$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: Let me also add that even if it seems that my idea will not break any official contracts, I can create a new ABC class and let maps and sequence types inherit from it. IMHO it's absolutely not needed, but at least the discussion will be no more distracted my secondary considerations, since the main topic is about the usefulness and the advantage to have a base contract for maps and sequences. PS: I intend to write: You've demonstrated to be a fair thinker, so do not fall into temptation to play with words. My English is terrible as much as StrangeDict code. From breamoreboy at yahoo.co.uk Wed Mar 30 16:31:21 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 30 Mar 2016 21:31:21 +0100 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 30/03/2016 20:35, Marco Sulla via Python-list wrote: > On 30 March 2016 at 02:55, Terry Reedy wrote: >> To me [seq.items() and seq.keys()] are useless and confusing duplications since enumerate()(seq) >> and range(len(seq)) are quite different from dict.items and dict.keys. > > It's true. Indeed IMHO it's enumerate() that will be a confusing duplication. > Please explain how a builtin that was brought in due to popular demand can be a "confusing duplication". -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at yahoo.co.uk Wed Mar 30 16:36:59 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 30 Mar 2016 21:36:59 +0100 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fbf879$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 30/03/2016 21:00, Marco Sulla via Python-list wrote: > Let me also add that even if it seems that my idea will not break any > official contracts, I can create a new ABC class and let maps and > sequence types inherit from it. IMHO it's absolutely not needed, but > at least the discussion will be no more distracted my secondary > considerations, since the main topic is about the usefulness and the > advantage to have a base contract for maps and sequences. 1) maps ain't sequences, sequences ain't maps, and never the twain shall meet. 2) if it ain't broke, don't fix it. 3) KISS > > PS: I intend to write: > You've demonstrated to be a fair thinker, so do not fall into > temptation to play with > words. No idea at all what you mean by this, please explain. > My English is terrible as much as StrangeDict code. > StrangeDict broke "Practicality beats purity", no further comment needed. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From kyosohma at gmail.com Wed Mar 30 16:51:12 2016 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 30 Mar 2016 13:51:12 -0700 (PDT) Subject: ANN: Python 201 - Intermediate Python book In-Reply-To: References: <3ba58226-1196-44c8-bea5-b1c7c4833529@googlegroups.com> <649ede42-4ce4-43d8-bff8-5d207c4511c1@googlegroups.com> Message-ID: <6b77d2be-8874-4d3f-bc04-7eb249a9bf9c@googlegroups.com> On Wednesday, March 30, 2016 at 2:21:08 PM UTC-5, Ethan Furman wrote: > On 03/30/2016 11:41 AM, justin walters wrote: > > > That absolutely answers my questions. I'll keep an eye out for your book > > when it is realeased. It seems like it will cover some topics that could be > > useful in continuing my learning. > > KickStarter plug: > > If you want to pledge to buying the book now on KickStarter, that will > guarantee you the book when it comes out, plus contribute to possibly > have more content in the book as higher reward levels are unlocked. > > Currenty his book is past the "it will definitely happen" stage, and the > next reward level will unsure even more content. > > Note: I'm not affiliated with the book, probably won't pledge (only a > couple topics apply to me), but I am a KickStarter fan (having purchased > more games than was probably wise ;) . > > -- > ~Ethan~ You'll also get early access to the book so you'll get to see the chapters as soon as I'm done with them (most of the time). Mike From greg.ewing at canterbury.ac.nz Wed Mar 30 17:36:23 2016 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 31 Mar 2016 10:36:23 +1300 Subject: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA00EC.80909@gmail.com> <56FA537F.9090506@mail.de> <56FB0FF6.3000305@harvee.org> <56FBA577.6070607@mail.de> Message-ID: Tim Golden wrote: > (I don't know how other English-speaking groups say the word, but in > England the first syllable is stressed and the second is the > conventional short "uh" sound). I can attest that New Zealand follows the UK on this. I was surprised when I first heard an American pronounce it too. The curious can hear the difference on these pages: British: http://www.oxforddictionaries.com/definition/english/python American: http://www.dictionary.com/browse/python?s=t -- Greg From best_lay at yahoo.com Wed Mar 30 17:37:00 2016 From: best_lay at yahoo.com (Wildman) Date: Wed, 30 Mar 2016 16:37:00 -0500 Subject: pygtk button right/middle click References: Message-ID: On Wed, 30 Mar 2016 19:23:35 +0000, Grant Edwards wrote: > On 2016-03-30, Grant Edwards wrote: >> On 2016-03-30, Wildman wrote: >> >>>> Is the gtk button widget really incapable of handling left or middle >>>> mouse buttons or shift/ctrl/alt modifiers? >>> >>> This might help... >>> >>> http://faq.pygtk.org/index.py?req=show&file=faq05.004.htp >> >> Yep, I found that. I'm just missing the clues required to use those >> two pieces. > > FWIW, I've decided to give up on this. Since it took only a few lines > of code to handle the "left" click, I assumed that like some other > toolkits, it would be similarly easy to handle "right" and "middle". > > I don't have the time to re-invent the wheel at the moment, so this > project will have to be postponed. I'm sorry to say I have no experience using pygtk. My only gui experience is with Tkinter. In Tk you would do something like this to trap a right-click. # create the popup menu and add commands as needed self.menu = tk.Menu(self, tearoff=0) self.menu.add_command(label="Whatever", command=self.do_whatever) # bind the button with mouse right-click self.button.bind("", self.popup) # define the handler for the menu def do_whatever(self): # do whatever # define the popup handler, this displays the menu def popup(self, event): self.menu.post(event.x_root, event.y_root) I posted this on the off chance there might be a way to translate this to gtk code. -- GNU/Linux user #557453 "The Constitution only gives people the right to pursue happiness. You have to catch it yourself." -Benjamin Franklin From breamoreboy at yahoo.co.uk Wed Mar 30 19:41:18 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 31 Mar 2016 00:41:18 +0100 Subject: Adding borders to ttk radiobuttons In-Reply-To: References: <56fbe699$0$4548$426a74cc@news.free.fr> Message-ID: On 30/03/2016 17:35, Terry Reedy wrote: > > .theme_names() only displays the themes for the OS. I believe that > there is a way to access themes for other OSes (unix, mac) but don't > remember. > Possibly http://bugs.python.org/issue17397 which refers to http://code.activestate.com/lists/python-tkinter-discuss/3373/ ? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From random832 at fastmail.com Wed Mar 30 20:15:36 2016 From: random832 at fastmail.com (Random832) Date: Wed, 30 Mar 2016 20:15:36 -0400 Subject: Statements as expressions [was Re: Undefined behaviour in C] In-Reply-To: References: <1344e2bf-15d2-412e-9512-b0aba800dada@googlegroups.com> <56f880ba$0$1617$c3e8da3$5496439d@news.astraweb.com> <878u125ugc.fsf@nightsong.com> <720bdbcc-862d-425d-abc0-2dacaaf8f7d9@googlegroups.com> <87zitgujmp.fsf@bsb.me.uk> <1459357657.2013677.563815506.596B2C8F@webmail.messagingengine.com> Message-ID: <1459383336.3381713.564172506.4D1D8449@webmail.messagingengine.com> On Wed, Mar 30, 2016, at 19:01, Dennis Lee Bieber wrote: > Though I'm surprised GoogleGroups would expire that fast. > > Google is the reason I inserted that header -- I started back in the > days when news-servers routinely expired stuff (text groups about monthly > lifespan, the binary groups were expiring at 24 hours). Then along came > Google with the "lifetime availability" threat. I guess I'm not sure I understand the motive for considering such a thing a "threat". Why do you _care_ if technical discussions about Python are available forever? I mean, it's useful for there to be a record of the discussion that led to making a decision about a PEP, or prior arguments against an idea. Sure, one person's posts being missing doesn't do much to that overall, but I do have to wonder why you care. AIUI, most people's contemporary reasoning for objecting to DejaNews (if "Google" was truly the reason you inserted it, you're a latecomer to the idea) was the supposed exploitation inherent in the fact that it was ad-funded, and most never claimed to care about it being around forever. From rosuav at gmail.com Wed Mar 30 20:50:12 2016 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 31 Mar 2016 11:50:12 +1100 Subject: ANN: Python 201 - Intermediate Python book In-Reply-To: <56FC2736.7000800@stoneleaf.us> References: <3ba58226-1196-44c8-bea5-b1c7c4833529@googlegroups.com> <649ede42-4ce4-43d8-bff8-5d207c4511c1@googlegroups.com> <56FC2736.7000800@stoneleaf.us> Message-ID: On Thu, Mar 31, 2016 at 6:21 AM, Ethan Furman wrote: > Note: I'm not affiliated with the book, probably won't pledge (only a > couple topics apply to me), but I am a KickStarter fan (having purchased > more games than was probably wise ;) . Heh, me too - though more other things than games. Between Kickstarter and Twitch.tv, I've collected a lot of great artwork and Alice in Wonderland memorabilia. This also isn't for me, but if anyone's interested, I strongly encourage going for it. Don't worry if you don't have the money yet; you won't be charged until the campaign ends (in a week or thereabouts). Get the book sooner than anyone else does, and be a part of making it happen! ChrisA From steve at pearwood.info Wed Mar 30 22:40:08 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 31 Mar 2016 13:40:08 +1100 Subject: Suggestion: make sequence and map interfaces more similar References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> On Thu, 31 Mar 2016 06:07 am, Antoon Pardon wrote: >> Because fundamentally, it doesn't matter whether dicts are surjections or >> not. They're still many-to-one mappings, and those mappings between keys >> and values should not change due to the insertion or deletion of >> unrelated keys. > > Repeating your opion without further arguments doesn't lend any support > to that opinion. If within the problem space you are working on, such a > change would make sense as a step to generate the next mapping from the > previous one, i don't see what the problem is if one could make use of > this. Enough of the hypothetical arguments about what one could do or might do. Let's see a concrete example of actual real world code used in production, not a mickey-mouse toy program, where it is desirable that adding or deleting one key will modify the rest of the keys in the mapping. Arguing for the sake of arguing about what somebody might want is not productive. Let's see some actual concrete use cases where you have a database or mapping between keys and values, say something like this: mapping = { # name: address "fred": "123 Smith Street", "george": "27 Main Road", "sally": "72a Short Street" } where it is desirable to have this behaviour: # adding a new key mapping["mary"] = "31 King Street" # changes the other keys assert mapping["george"] != "27 Main Road" No hypothetical cases where somebody might or could want this behaviour. I'm not interested in "mights" and "coulds". I want to see an actual application where adding a new key to a mapping is expected to change the other keys. -- Steven From steve at pearwood.info Wed Mar 30 22:44:47 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 31 Mar 2016 13:44:47 +1100 Subject: Suggestion: make sequence and map interfaces more similar References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fbf879$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56fc8f20$0$1600$c3e8da3$5496439d@news.astraweb.com> On Thu, 31 Mar 2016 03:52 am, Random832 wrote: > Like, these are common patterns: > > for i, x in enumerate(l): > # do some stuff, sometimes assign l[i] > > for k, v in d.items(): > # do some stuff, sometimes assign d[k] for a, b in zip(spam, eggs): # do some stuff, sometimes assign x[a] or b[a] or who knows what? Does this mean that "lists, dicts and zip" should all support the same interface? Not every coincidental and trivial piece of similar code is actually related. > A way to apply that pattern generically to an object which may be either > a sequence or a mapping might be nice. Nice, and easy. # Duck-typing version. def iterpairs(obj): if hasattr(obj, 'items'): it = obj.items else: it = enum(obj) yield from it # Type-checking version. def iterpairs(obj): if isinstance(obj, collections.abc.Mapping): it = obj.items elif isinstance(obj, collections.abc.Sequence): it = enum(obj) else: raise TypeError('not a sequence or a mapping') yield from it Pick which one you prefer, stick it in your own personal toolbox of useful utilities functions, and off you go. -- Steven From no.email at nospam.invalid Wed Mar 30 22:45:58 2016 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 30 Mar 2016 19:45:58 -0700 Subject: Suggestion: make sequence and map interfaces more similar References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> Message-ID: <874mbntleh.fsf@nightsong.com> Steven D'Aprano writes: > I want to see an actual application where adding a new key to a > mapping is expected to change the other keys. directory["mary.roommate"] = "bob" directory["mary.address"] = None # unknown address ... directory["bob.address"] = "132 Elm Street" Since Bob and Mary are roommates, they have the same address, so the application might want to update both addresses once it learns one of them. From greg.ewing at canterbury.ac.nz Thu Mar 31 00:49:14 2016 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 31 Mar 2016 17:49:14 +1300 Subject: sympy In-Reply-To: <56fbf7e7$0$1591$c3e8da3$5496439d@news.astraweb.com> References: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> <56fbcd01$0$1599$c3e8da3$5496439d@news.astraweb.com> <99b7cf43-50ff-4de7-8de0-e324658682bf@googlegroups.com> <56fbf7e7$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Thu, 31 Mar 2016 02:23 am, Poul Riis wrote: > >>What I intend to do is to let sympy find the derivative of some >>welldefined function and next define the foundation derivative as a normal >>function > > py> ftext.evalf(subs={x:3}) > -0.0600000000000000 Given all that, it looks like you want def f(t): return ftext.evalf(subs={x:t}) -- Greg From mark at msapiro.net Thu Mar 31 00:50:54 2016 From: mark at msapiro.net (Mark Sapiro) Date: Wed, 30 Mar 2016 21:50:54 -0700 Subject: Threading is foobared? In-Reply-To: <56F7B5FA.4040002@timgolden.me.uk> References: <56F7B5FA.4040002@timgolden.me.uk> Message-ID: <56FCACAE.3060405@msapiro.net> Hi all, I'm jumping in on this thread because Tim asked. I'm here because I'm a Mailman developer and the primary maintainer of Mailman for the @python.org lists. Regarding the initial post in this thread from Steven D'Aprano suggesting that broken threading is more common recently and quoting a couple of Message-ID:/References: headers wherein a message ID was apparently munged from <1392737302.749065.1459024715818.JavaMail.yahoo at mail.yahoo.com> to <1392737302.749065.1459024715818.JavaMail.yahoo.ref at mail.yahoo.com> Some Background: Our long time mail.python.org server provided by xs4all died of severe hardware failure late last October. We were able to get a replacement server through the PSF and get it configured and running within a couple of days, but this new server couldn't access the nntp server at xs4all. With the kind assistance of members of the community we were able to get access to a news server at the Free University of Berlin which is now our gateway to Usenet. This server undoubtedly has different policies and behaviors from the prior server at xs4all. I'm not sure what mail or news server is responsible for munging the IDs as above, but it could be our new Usenet gateway. All I know for sure is that Mailman doesn't do that specific munging. What Mailman does do as noted by Random832 is replace the Message-ID: header value in posts gated to Usenet with a list specific, Mailman generated unique value. There is a reason for this, and that reason is if a message is cross-posted to two lists which both gateway to Usenet, and Mailman didn't make the Message-IDs unique, the news server would discard one of the two posts as a duplicate and the post would be missing from one of the recipient Usenet groups. Granted that this is bad and breaks threading, but avoiding message loss is a more important goal. I understand I'm not providing any solutions here, but perhaps a more complete understanding of what the issues are will ease the pain. -- Mark Sapiro The highway is for gamblers, San Francisco Bay Area, California better use your sense - B. Dylan -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 189 bytes Desc: OpenPGP digital signature URL: From random832 at fastmail.com Thu Mar 31 01:25:51 2016 From: random832 at fastmail.com (Random832) Date: Thu, 31 Mar 2016 01:25:51 -0400 Subject: Threading is foobared? In-Reply-To: <56FCACAE.3060405@msapiro.net> References: <56F7B5FA.4040002@timgolden.me.uk> <56FCACAE.3060405@msapiro.net> Message-ID: <1459401951.1771032.564341266.6995438B@webmail.messagingengine.com> On Thu, Mar 31, 2016, at 00:50, Mark Sapiro wrote: > What Mailman does do as noted by Random832 is replace the Message-ID: > header value in posts gated to Usenet with a list specific, Mailman > generated unique value. There is a reason for this, and that reason is > if a message is cross-posted to two lists which both gateway to Usenet, > and Mailman didn't make the Message-IDs unique, the news server would > discard one of the two posts as a duplicate and the post would be > missing from one of the recipient Usenet groups. > > Granted that this is bad and breaks threading, but avoiding message loss > is a more important goal. > > I understand I'm not providing any solutions here, but perhaps a more > complete understanding of what the issues are will ease the pain. Any chance that it could fix reference headers to match? Actually, merely prepending the original Message-ID itself to the references header might be enough to change the reply's situation from "nephew" ("reply to [missing] sibling") to "grandchild" ("reply to [missing] reply"), which might be good enough to make threading work right on most clients, and would be *easy* (whereas maintaining an ongoing reversible mapping may not be). And if it's not too much additional work, maybe throw in an X-Mailman-Original-Message-ID (and -References if anything is done with that) field, so that the original state can be recovered. Rather than exclusively rewriting for usenet, maybe the rewritten headers could also be included in outgoing emails and the archive? Putting it in outgoing emails would solve the problem entirely, though it would mean people get duplicates if they're subscribed to multiple lists to which something is posted or get CC'd. The archive wouldn't have this issue. From mssiddiq9 at gmail.com Thu Mar 31 01:27:27 2016 From: mssiddiq9 at gmail.com (muhammed siddiq) Date: Thu, 31 Mar 2016 10:57:27 +0530 Subject: Interpreter not selected Message-ID: Hello Team, I have installed Python 3.5.1 and now trying to install pycharm, but its not selecting the interpreter and getting the below error all the time. [image: Inline image 1] Quick help will be really appreciated. -- Thanks & Regards Siddiq From random832 at fastmail.com Thu Mar 31 01:30:04 2016 From: random832 at fastmail.com (Random832) Date: Thu, 31 Mar 2016 01:30:04 -0400 Subject: Threading is foobared? In-Reply-To: <1459401951.1771032.564341266.6995438B@webmail.messagingengine.com> References: <56F7B5FA.4040002@timgolden.me.uk> <56FCACAE.3060405@msapiro.net> <1459401951.1771032.564341266.6995438B@webmail.messagingengine.com> Message-ID: <1459402204.1771438.564347074.6B36AF7F@webmail.messagingengine.com> On Thu, Mar 31, 2016, at 01:25, Random832 wrote: > > if a message is cross-posted to two lists which both gateway to Usenet, > > and Mailman didn't make the Message-IDs unique, the news server would > > discard one of the two posts as a duplicate and the post would be > > missing from one of the recipient Usenet groups. One additional thing that would be nice and would solve most of the duplicate problem with hypothetically including the rewritten Message-IDs in outgoing emails, would be to detect crossposts to multiple lists in the same Mailman instance, and to send them to Usenet (and to subscribers) as a single message, with appropriate headers for a crosspost. From random832 at fastmail.com Thu Mar 31 01:31:37 2016 From: random832 at fastmail.com (Random832) Date: Thu, 31 Mar 2016 01:31:37 -0400 Subject: Threading is foobared? In-Reply-To: <1459401951.1771032.564341266.6995438B@webmail.messagingengine.com> References: <56F7B5FA.4040002@timgolden.me.uk> <56FCACAE.3060405@msapiro.net> <1459401951.1771032.564341266.6995438B@webmail.messagingengine.com> Message-ID: <1459402297.1771995.564348234.153D57E9@webmail.messagingengine.com> On Thu, Mar 31, 2016, at 01:25, Random832 wrote: > Actually, merely prepending the original Message-ID itself append, not prepend... I'd misremembered the order that References go in. From tdsperth at gmail.com Thu Mar 31 01:34:07 2016 From: tdsperth at gmail.com (tdsperth at gmail.com) Date: Wed, 30 Mar 2016 22:34:07 -0700 (PDT) Subject: Python Array Message-ID: <0140ae7c-ebe6-4a9b-8db6-1d0a5470545a@googlegroups.com> I am creating the following aData = [] # get my data from database for row in rows: aData.append({row["tierid"]:"name":row["tiername"],"description":row["tierdesc"],"option":row["tieroption"],"price":str(row["tierprice"])}}) when I display the output the order the data was entered is not what is displayed {'BBS': {'option': 'Small', 'description': 'Broadband Bundle', 'name': 'Broadband', 'price': '179.00 {'BBM': {'option': 'Medium', 'description': 'Broadband Bundle', 'name': 'Broadband', 'price': '215.0 {'BBL': {'option': 'Large', 'description': 'Broadband Bundle', 'name': 'Broadband', 'price': '295.00 as you can see the option element was added third but is the first one displayed. Is this just standard - I am using Python 3.5 Regards Colin From rosuav at gmail.com Thu Mar 31 01:43:43 2016 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 31 Mar 2016 16:43:43 +1100 Subject: Python Array In-Reply-To: <0140ae7c-ebe6-4a9b-8db6-1d0a5470545a@googlegroups.com> References: <0140ae7c-ebe6-4a9b-8db6-1d0a5470545a@googlegroups.com> Message-ID: On Thu, Mar 31, 2016 at 4:34 PM, wrote: > as you can see the option element was added third but is the first one displayed. > Dictionaries don't have any order to them, so yes, this is something you'll have to accept. ChrisA From me+python at ixokai.io Thu Mar 31 01:53:11 2016 From: me+python at ixokai.io (Stephen Hansen) Date: Wed, 30 Mar 2016 22:53:11 -0700 Subject: Python Array In-Reply-To: <0140ae7c-ebe6-4a9b-8db6-1d0a5470545a@googlegroups.com> References: <0140ae7c-ebe6-4a9b-8db6-1d0a5470545a@googlegroups.com> Message-ID: <1459403591.3457486.564357850.0C040CAF@webmail.messagingengine.com> On Wed, Mar 30, 2016, at 10:34 PM, tdsperth at gmail.com wrote: > as you can see the option element was added third but is the first one > displayed. > > Is this just standard - I am using Python 3.5 The order of items in dictionaries is based on the hash value -- which while stable, should be considered random and not reliable. If you want to maintain insertion order, consider using an OrderedDict: https://docs.python.org/3.5/library/collections.html#collections.OrderedDict From breamoreboy at yahoo.co.uk Thu Mar 31 01:56:36 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 31 Mar 2016 06:56:36 +0100 Subject: Python Array In-Reply-To: <0140ae7c-ebe6-4a9b-8db6-1d0a5470545a@googlegroups.com> References: <0140ae7c-ebe6-4a9b-8db6-1d0a5470545a@googlegroups.com> Message-ID: On 31/03/2016 06:34, tdsperth at gmail.com wrote: > I am creating the following > > aData = [] This is a Python list, not an array as the subject gives. > > # get my data from database > > for row in rows: > aData.append({row["tierid"]:"name":row["tiername"],"description":row["tierdesc"],"option":row["tieroption"],"price":str(row["tierprice"])}}) Please cut and paste your code, don't try to type it in. The above gives a syntax error at the second colon, which should presumably be a comma. > > when I display the output the order the data was entered is not what is displayed > > {'BBS': {'option': 'Small', 'description': 'Broadband Bundle', 'name': 'Broadband', 'price': '179.00 > {'BBM': {'option': 'Medium', 'description': 'Broadband Bundle', 'name': 'Broadband', 'price': '215.0 > {'BBL': {'option': 'Large', 'description': 'Broadband Bundle', 'name': 'Broadband', 'price': '295.00 > > as you can see the option element was added third but is the first one displayed. > > Is this just standard - I am using Python 3.5 Yes, as you are using a standard dict within the list. There is https://docs.python.org/3/library/collections.html#collections.OrderedDict which retains the insertion order. > > Regards > > Colin > -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From jussi.piitulainen at helsinki.fi Thu Mar 31 01:57:44 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Thu, 31 Mar 2016 08:57:44 +0300 Subject: Python Array References: <0140ae7c-ebe6-4a9b-8db6-1d0a5470545a@googlegroups.com> Message-ID: Stephen Hansen writes: > On Wed, Mar 30, 2016, at 10:34 PM, tdsperth at gmail.com wrote: >> as you can see the option element was added third but is the first one >> displayed. >> >> Is this just standard - I am using Python 3.5 > > The order of items in dictionaries is based on the hash value -- which > while stable, should be considered random and not reliable. If you want > to maintain insertion order, consider using an OrderedDict: > > https://docs.python.org/3.5/library/collections.html#collections.OrderedDict Possibly collections.namedtuple for database records. From steve+comp.lang.python at pearwood.info Thu Mar 31 02:31:31 2016 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 31 Mar 2016 17:31:31 +1100 Subject: Threading is foobared? References: <56F7B5FA.4040002@timgolden.me.uk> Message-ID: <56fcc445$0$1590$c3e8da3$5496439d@news.astraweb.com> On Thursday 31 March 2016 15:50, Mark Sapiro wrote: > Hi all, > > I'm jumping in on this thread because Tim asked. [...] Thanks for the explanation! -- Steve From cs at zip.com.au Thu Mar 31 02:41:15 2016 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 31 Mar 2016 17:41:15 +1100 Subject: Python Array In-Reply-To: <1459403591.3457486.564357850.0C040CAF@webmail.messagingengine.com> References: <1459403591.3457486.564357850.0C040CAF@webmail.messagingengine.com> Message-ID: <20160331064115.GA42668@cskk.homeip.net> On 30Mar2016 22:53, Stephen Hansen wrote: >On Wed, Mar 30, 2016, at 10:34 PM, tdsperth at gmail.com wrote: >> as you can see the option element was added third but is the first one >> displayed. >> >> Is this just standard - I am using Python 3.5 > >The order of items in dictionaries is based on the hash value -- which >while stable, should be considered random and not reliable. If you want >to maintain insertion order, consider using an OrderedDict: > >https://docs.python.org/3.5/library/collections.html#collections.OrderedDict Alternatively, you can decide to not care, and to present the dictionary keys in some arbitrary order of your chosing when printing output (commonest example is probably lexically sorted). On the other hand, if you really do want the insertion order then OrderedDict is the way to do, as several others have mentioned. Cheers, Cameron Simpson From steve+comp.lang.python at pearwood.info Thu Mar 31 02:45:30 2016 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 31 Mar 2016 17:45:30 +1100 Subject: Suggestion: make sequence and map interfaces more similar References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <874mbntleh.fsf@nightsong.com> Message-ID: <56fcc78e$0$1532$c3e8da3$5496439d@news.astraweb.com> On Thursday 31 March 2016 13:45, Paul Rubin wrote: > Steven D'Aprano writes: >> I want to see an actual application where adding a new key to a .................^^^^^^^^^^^^^^^^^^^^^ >> mapping is expected to change the other keys. > directory["mary.roommate"] = "bob" > directory["mary.address"] = None # unknown address > ... > directory["bob.address"] = "132 Elm Street" > > Since Bob and Mary are roommates, they have the same address, so the > application might want to update both addresses once it learns one of > them. I think I've used that application! It was a nightmare... I had to move house seven times before I stopped getting my ex-roomate Stinky Joe's electricity bill sent to me. Nah, only kidding. I've never seen such an application, and I don't believe it exists. By your use of the word "might", I'm guessing that you've made it up. But even if you didn't, it's still a lousy design. Just because Mary and Bob are roommates *now* doesn't mean that they are joined at the hips like Siamese twins and are roommates forever. If Mary relocates, the application shouldn't automatically relocate Bob as well. And even if the application does, for some strange reason, this logic should be built into the *application itself*, not into dict. By all means subclass dict and make your own fancy mapping type that has all sorts of application- specific smarts (or dumbs, as the case may be). Just don't expect it in the standard dict. -- Steve From priisdk at gmail.com Thu Mar 31 02:51:06 2016 From: priisdk at gmail.com (Poul Riis) Date: Wed, 30 Mar 2016 23:51:06 -0700 (PDT) Subject: sympy In-Reply-To: References: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> <56fbcd01$0$1599$c3e8da3$5496439d@news.astraweb.com> <99b7cf43-50ff-4de7-8de0-e324658682bf@googlegroups.com> <56fbf7e7$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: <98f57610-bd25-4d00-b095-703360a79fa1@googlegroups.com> Den torsdag den 31. marts 2016 kl. 06.49.34 UTC+2 skrev Gregory Ewing: > Steven D'Aprano wrote: > > On Thu, 31 Mar 2016 02:23 am, Poul Riis wrote: > > > >>What I intend to do is to let sympy find the derivative of some > >>welldefined function and next define the foundation derivative as a normal > >>function > > > > py> ftext.evalf(subs={x:3}) > > -0.0600000000000000 > > Given all that, it looks like you want > > def f(t): > return ftext.evalf(subs={x:t}) > > -- > Greg Oh, yes, that works! Thank you! Poul Riis From antoon.pardon at rece.vub.ac.be Thu Mar 31 03:52:10 2016 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Thu, 31 Mar 2016 09:52:10 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56FCD72A.4080705@rece.vub.ac.be> Op 31-03-16 om 04:40 schreef Steven D'Aprano: > On Thu, 31 Mar 2016 06:07 am, Antoon Pardon wrote: > >>> Because fundamentally, it doesn't matter whether dicts are surjections or >>> not. They're still many-to-one mappings, and those mappings between keys >>> and values should not change due to the insertion or deletion of >>> unrelated keys. >> Repeating your opion without further arguments doesn't lend any support >> to that opinion. If within the problem space you are working on, such a >> change would make sense as a step to generate the next mapping from the >> previous one, i don't see what the problem is if one could make use of >> this. > > Enough of the hypothetical arguments about what one could do or might do. > Let's see a concrete example of actual real world code used in production, > not a mickey-mouse toy program, where it is desirable that adding or > deleting one key will modify the rest of the keys in the mapping. I am not going to humour your petitio principii. If you want to argue against such a adjustment on the ground of some characteristics mappings should have, you have to make your case yourself and not try to shift the burden onto the person who has his doubt about your argument. If you continously stress the adaption will loose the stability of mappings and so suggest this is somehow a problem it is your burden to argue that problem. > Arguing for the sake of arguing about what somebody might want is not > productive. Let's see some actual concrete use cases where you have a > database or mapping between keys and values, say something like this: Arguing by just calling attention to a specific characteristic but not giving any reason why it would be bad if people were allowed to use a mapping in a way that violated this characteristic, is not productive either. If you try to argue a principle problem with the proposal, you have to support that and not try to shift the attention to there being no use case for the moment. -- Antoon Pardon. From antoon.pardon at rece.vub.ac.be Thu Mar 31 04:04:04 2016 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Thu, 31 Mar 2016 10:04:04 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56fc8f20$0$1600$c3e8da3$5496439d@news.astraweb.com> References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fbf879$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8f20$0$1600$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56FCD9F4.2040005@rece.vub.ac.be> Op 31-03-16 om 04:44 schreef Steven D'Aprano: > On Thu, 31 Mar 2016 03:52 am, Random832 wrote: > >> Like, these are common patterns: >> >> for i, x in enumerate(l): >> # do some stuff, sometimes assign l[i] >> >> for k, v in d.items(): >> # do some stuff, sometimes assign d[k] > > for a, b in zip(spam, eggs): > # do some stuff, sometimes assign x[a] or b[a] or who knows what? > > > Does this mean that "lists, dicts and zip" should all support the same > interface? > > Not every coincidental and trivial piece of similar code is actually > related. But your addition shows that the similarities between lists and dicts are greater than with zip. In the above two examples the assignment was specific to elements of the list or dict over which was iterated. Your x[a] and b[a] have no such relationship with the rest of your example. This is further illustrated by the fact that your solution doesn't provide a zip branch. >> A way to apply that pattern generically to an object which may be either >> a sequence or a mapping might be nice. > Nice, and easy. > > # Duck-typing version. > def iterpairs(obj): > if hasattr(obj, 'items'): > it = obj.items > else: > it = enum(obj) > yield from it > > > # Type-checking version. > def iterpairs(obj): > if isinstance(obj, collections.abc.Mapping): > it = obj.items > elif isinstance(obj, collections.abc.Sequence): > it = enum(obj) > else: > raise TypeError('not a sequence or a mapping') > yield from it > > > Pick which one you prefer, stick it in your own personal toolbox of useful > utilities functions, and off you go. > > > > From ben+python at benfinney.id.au Thu Mar 31 04:12:01 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 31 Mar 2016 19:12:01 +1100 Subject: Interpreter not selected References: Message-ID: <858u0z9icu.fsf@benfinney.id.au> muhammed siddiq writes: > Hello Team, Welcome! We are less a team and more a community of Python enthusiasts. You are welcome to ask about Python here. If you need help specifically with PyCharm you will probably need to find its specific support community. > I have installed Python 3.5.1 and now trying to install pycharm, but > its not selecting the interpreter and getting the below error all the > time. Image (and other attachments) do not travel well in a distributed message forum. Please insert the text of the error, directly in the message. -- \ ?The fact of your own existence is the most astonishing fact | `\ you'll ever have to confront. Don't dare ever see your life as | _o__) boring, monotonous, or joyless.? ?Richard Dawkins, 2010-03-10 | Ben Finney From davidgshi at yahoo.co.uk Thu Mar 31 05:37:43 2016 From: davidgshi at yahoo.co.uk (David Shi) Date: Thu, 31 Mar 2016 09:37:43 +0000 (UTC) Subject: Which plugin allows quick creation of secure REST services? References: <443415735.274628.1459417063627.JavaMail.yahoo.ref@mail.yahoo.com> Message-ID: <443415735.274628.1459417063627.JavaMail.yahoo@mail.yahoo.com> Hello,? Which plugin allows quick creation of secure REST services? ?so that Python scripts can be attached to it. Regards. David From steve at pearwood.info Thu Mar 31 06:36:53 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 31 Mar 2016 21:36:53 +1100 Subject: Suggestion: make sequence and map interfaces more similar References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> On Thu, 31 Mar 2016 06:52 pm, Antoon Pardon wrote: > it is your burden to argue that problem. No it isn't. I don't have to do a thing. All I need to do is sit back and wait as this discussion peters off into nothing. The burden isn't on me to justify the status quo. The burden is on those who want to make this change to justify the change, because if you don't, the status quo stays exactly the same. And if you're brave enough to take to this Python-Ideas, let alone Python-Dev, the first question they'll ask is "What's your use-case?". And since you don't have one, this discussion will go nowhere. Oh, there might be a few hundred posts on the topic, from people bike-shedding it, but unless you convince the core developers, all the chattering in the world won't get you one nanometre closer to changing the behaviour of lists and dicts. So, Antoon, no, I don't have to justify a single thing. If you want this change, you have to justify why it should be done. Good luck with that. -- Steven From antoon.pardon at rece.vub.ac.be Thu Mar 31 06:51:04 2016 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Thu, 31 Mar 2016 12:51:04 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56FD0118.6080201@rece.vub.ac.be> Op 31-03-16 om 12:36 schreef Steven D'Aprano: > On Thu, 31 Mar 2016 06:52 pm, Antoon Pardon wrote: > >> it is your burden to argue that problem. > No it isn't. I don't have to do a thing. If that is how you think about this, why do you contribute? I completly understand if you are of the opinion that other priorities are more important > All I need to do is sit back and > wait as this discussion peters off into nothing. The burden isn't on me to > justify the status quo. The burden is on those who want to make this change > to justify the change, because if you don't, the status quo stays exactly > the same. > > And if you're brave enough to take to this Python-Ideas, let alone > Python-Dev, the first question they'll ask is "What's your use-case?". And > since you don't have one, this discussion will go nowhere. > > Oh, there might be a few hundred posts on the topic, from people > bike-shedding it, but unless you convince the core developers, all the > chattering in the world won't get you one nanometre closer to changing the > behaviour of lists and dicts. > > So, Antoon, no, I don't have to justify a single thing. If you want this > change, you have to justify why it should be done. > > Good luck with that. > > > > From priisdk at gmail.com Thu Mar 31 06:57:10 2016 From: priisdk at gmail.com (Poul Riis) Date: Thu, 31 Mar 2016 03:57:10 -0700 (PDT) Subject: sympy In-Reply-To: <56fbf7e7$0$1591$c3e8da3$5496439d@news.astraweb.com> References: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> <56fbcd01$0$1599$c3e8da3$5496439d@news.astraweb.com> <99b7cf43-50ff-4de7-8de0-e324658682bf@googlegroups.com> <56fbf7e7$0$1591$c3e8da3$5496439d@news.astraweb.com> Message-ID: <244e1277-e105-4419-a449-7f2012c6d78e@googlegroups.com> Den onsdag den 30. marts 2016 kl. 17.59.49 UTC+2 skrev Steven D'Aprano: > On Thu, 31 Mar 2016 02:23 am, Poul Riis wrote: > > > What I intend to do is to let sympy find the derivative of some > > welldefined function and next define the foundation derivative as a normal > > function so that I can calculate numerical values or even make a graph. > > > I'm glad you explained what you *actually* wanted, because I was going to > guess that you wanted to evaluate the derivative at x = 3: > > > py> ftext.evalf(subs={x:3}) > -0.0600000000000000 > > > > -- > Steven ... However, the sympy way seems to be about 70 times slower than using the derivative calculated 'by hand' (try the example below). Can it be done in a more efficient way? Poul Riis from sympy import * from time import * x=Symbol('x') ftext=diff(sin(x),x) def fmsympy(t): return ftext.evalf(subs={x:t}) def fm(t): return cos(t) nloop=10000 tstart=time() # nloop evaluations with sympy for i in range(0,nloop): a=fmsympy(1) dt1=time()-tstart # nloop evaluations without sympy tstart=time() for i in range(0,nloop): a=fm(1) dt2=time()-tstart print(nloop,' evaluations with sympy : dt1 =',dt1) print(nloop,' evaluations without sympy: dt2 =',dt2) From antoon.pardon at rece.vub.ac.be Thu Mar 31 07:22:23 2016 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Thu, 31 Mar 2016 13:22:23 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56FD086F.2090301@rece.vub.ac.be> Op 31-03-16 om 12:36 schreef Steven D'Aprano: > On Thu, 31 Mar 2016 06:52 pm, Antoon Pardon wrote: > >> it is your burden to argue that problem. > No it isn't. I don't have to do a thing. All I need to do is sit back and > wait as this discussion peters off into nothing. The burden isn't on me to > justify the status quo. The burden is on those who want to make this change > to justify the change, because if you don't, the status quo stays exactly > the same. Sure that is all very well if you stay out of the discussion, or limit your contribution to mentioning that in your opinion that this is a very low priority. I have no problem with that. But if you begin to argue that the proposal has flaws and you argue against it then it is your intellectual responsibility to support your arguments. There is a difference between, (1) this proposal is flawed and (2)I don't think this is important enough. Starting with the first and then when pressed to support it, retreating to the second is not fair. > And if you're brave enough to take to this Python-Ideas, let alone > Python-Dev, the first question they'll ask is "What's your use-case?". And > since you don't have one, this discussion will go nowhere. So? That doesn't relieve you of your responsibility when you somehow argue that the proposal is flawed, beyond there being no use case. > Oh, there might be a few hundred posts on the topic, from people > bike-shedding it, but unless you convince the core developers, all the > chattering in the world won't get you one nanometre closer to changing the > behaviour of lists and dicts. I have no interest in convincing the core developers. That doesn't mean I can't respond here to arguments against a proposal that are IMO bogus. A bogus argument against a proposal doesn't become a good argument against because there is no use case. > So, Antoon, no, I don't have to justify a single thing. If you want this > change, you have to justify why it should be done. Indeed you don't have to argue against any proposal. You can just sit back and ask for use cases and ask do be convinced this proposal is important enough for the core developers to invest time in. But once you do argue against a proposal, as you did here, you have loaded yourself with the burden to support your argument. Because then your position is that even with an import use case, this is still a bad idea. And if you can't support that position it isn't fair IMO to then retreat to the "no use case" position as if that somehow is a defence of your argued position. -- Antoon. From rosuav at gmail.com Thu Mar 31 07:57:40 2016 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 31 Mar 2016 22:57:40 +1100 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56FD086F.2090301@rece.vub.ac.be> References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> <56FD086F.2090301@rece.vub.ac.be> Message-ID: On Thu, Mar 31, 2016 at 10:22 PM, Antoon Pardon wrote: > Op 31-03-16 om 12:36 schreef Steven D'Aprano: >> On Thu, 31 Mar 2016 06:52 pm, Antoon Pardon wrote: >> >>> it is your burden to argue that problem. >> No it isn't. I don't have to do a thing. All I need to do is sit back and >> wait as this discussion peters off into nothing. The burden isn't on me to >> justify the status quo. The burden is on those who want to make this change >> to justify the change, because if you don't, the status quo stays exactly >> the same. > > Sure that is all very well if you stay out of the discussion, or limit > your contribution to mentioning that in your opinion that this is a > very low priority. I have no problem with that. But if you begin to > argue that the proposal has flaws and you argue against it then it > is your intellectual responsibility to support your arguments. > > There is a difference between, (1) this proposal is flawed and (2)I > don't think this is important enough. Starting with the first and then > when pressed to support it, retreating to the second is not fair. > Okay. I'll put a slightly different position: Prove that your proposal is worth discussing by actually giving us an example that we can discuss. So far, this thread has had nothing but toy examples (and bogoexamples that prove nothing beyond that the author knows how to mess with Python - fun, but not a strong argument on either side). Give us some real meat to work with, instead of these drips of tantalizing blood. ChrisA From mail.python.org at marco.sulla.e4ward.com Thu Mar 31 07:58:28 2016 From: mail.python.org at marco.sulla.e4ward.com (Marco Sulla) Date: Thu, 31 Mar 2016 13:58:28 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56fc8f20$0$1600$c3e8da3$5496439d@news.astraweb.com> References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fbf879$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8f20$0$1600$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 31 March 2016 at 04:40, Steven D'Aprano wrote: > Enough of the hypothetical arguments about what one could do or might do. > Let's see a concrete example of actual real world code used in production, > not a mickey-mouse toy program, where it is desirable that adding or > deleting one key will modify the rest of the keys in the mapping. 1. the example was for confuting your assertion that an implementation of sequences as extended classes of maps violate the map contract. 2. I already linked a real-world example previously. Google it and you can find tons of examples like that. On 31 March 2016 at 04:44, Steven D'Aprano wrote: > for a, b in zip(spam, eggs): > # do some stuff, sometimes assign x[a] or b[a] or who knows what? > > > Does this mean that "lists, dicts and zip" should all support the same > interface? I do not understand what you mean with this example. A zip object is not a sequence nor a map. My definition of sequences as "ordered maps with integer keys that start from zero and have no gaps" is perfectly valid as I demonstrated to you, while zip objects have nothing in common with sequences and maps, apart the fact they are all iterables. From breamoreboy at yahoo.co.uk Thu Mar 31 08:30:29 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 31 Mar 2016 13:30:29 +0100 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fbf879$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8f20$0$1600$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 31/03/2016 12:58, Marco Sulla via Python-list wrote: > On 31 March 2016 at 04:40, Steven D'Aprano wrote: >> Enough of the hypothetical arguments about what one could do or might do. >> Let's see a concrete example of actual real world code used in production, >> not a mickey-mouse toy program, where it is desirable that adding or >> deleting one key will modify the rest of the keys in the mapping. > > > 1. the example was for confuting your assertion that an implementation > of sequences as extended classes of maps violate the map contract. > 2. I already linked a real-world example previously. Google it and you > can find tons of examples like that. > > > On 31 March 2016 at 04:44, Steven D'Aprano wrote: >> for a, b in zip(spam, eggs): >> # do some stuff, sometimes assign x[a] or b[a] or who knows what? >> >> >> Does this mean that "lists, dicts and zip" should all support the same >> interface? > > I do not understand what you mean with this example. A zip object is > not a sequence nor a map. My definition of sequences as "ordered maps > with integer keys that start from zero and have no gaps" is perfectly > valid as I demonstrated to you, while zip objects have nothing in > common with sequences and maps, apart the fact they are all iterables. > The definition of sequence is given here https://docs.python.org/3/glossary.html#term-sequence. An iterable which supports efficient element access using integer indices via the __getitem__() special method and defines a __len__() method that returns the length of the sequence. Some built-in sequence types are list, str, tuple, and bytes. Note that dict also supports __getitem__() and __len__(), but is considered a mapping rather than a sequence because the lookups use arbitrary immutable keys rather than integers. The collections.abc.Sequence abstract base class defines a much richer interface that goes beyond just __getitem__() and __len__(), adding count(), index(), __contains__(), and __reversed__(). Types that implement this expanded interface can be registered explicitly using register(). As this is a Python list the above definition clearly takes priority over your definition, so can you please take this discussion offline, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From marko at pacujo.net Thu Mar 31 08:36:24 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 31 Mar 2016 15:36:24 +0300 Subject: Suggestion: make sequence and map interfaces more similar References: <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> <56FD086F.2090301@rece.vub.ac.be> Message-ID: <87poualt87.fsf@elektro.pacujo.net> Chris Angelico : > On Thu, Mar 31, 2016 at 10:22 PM, Antoon Pardon > wrote: > Okay. I'll put a slightly different position: Prove that your proposal > is worth discussing by actually giving us an example that we can > discuss. Sorry for missing most of the arguments here, but if you are talking about treating lists as special cases of dicts, I have occasionally instinctively wanted something like this: >>> fields = [ "x", "y", "z" ] >>> selector = (1, 1, 0) >>> list(map(fields.get, selector)) Traceback (most recent call last): File "", line 1, in AttributeError: 'list' object has no attribute 'get' analogously with: >>> field_dict = { 0: "x", 1: "y", 2: "z" } >>> list(map(field_dict.get, selector)) ['y', 'y', 'x'] Or course, I could: >>> list(map(fields.__getitem__, selector)) ['y', 'y', 'x'] but that would abuse a dunder method. So I will need to: >>> list(map(lambda i: fields[i], selector)) ['y', 'y', 'x'] or (most likely): >>> new_fields = [] >>> for i in selector: ... new_fields.append(fields[i]) ... >>> new_fields ['y', 'y', 'x'] This tiny problem of mine could be remedied by adding a get method to lists. Marko From rosuav at gmail.com Thu Mar 31 08:48:48 2016 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 31 Mar 2016 23:48:48 +1100 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <87poualt87.fsf@elektro.pacujo.net> References: <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> <56FD086F.2090301@rece.vub.ac.be> <87poualt87.fsf@elektro.pacujo.net> Message-ID: On Thu, Mar 31, 2016 at 11:36 PM, Marko Rauhamaa wrote: > Chris Angelico : > >> On Thu, Mar 31, 2016 at 10:22 PM, Antoon Pardon >> wrote: >> Okay. I'll put a slightly different position: Prove that your proposal >> is worth discussing by actually giving us an example that we can >> discuss. > > Sorry for missing most of the arguments here, but if you are talking > about treating lists as special cases of dicts, I have occasionally > instinctively wanted something like this: > > >>> fields = [ "x", "y", "z" ] > >>> selector = (1, 1, 0) > >>> list(map(fields.get, selector)) > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'list' object has no attribute 'get' > > Or course, I could: > > >>> list(map(fields.__getitem__, selector)) > ['y', 'y', 'x'] > > but that would abuse a dunder method. So I will need to: > > >>> list(map(lambda i: fields[i], selector)) > ['y', 'y', 'x'] > > or (most likely): > > >>> new_fields = [] > >>> for i in selector: > ... new_fields.append(fields[i]) > ... > >>> new_fields > ['y', 'y', 'x'] > > > This tiny problem of mine could be remedied by adding a get method to > lists. Or, even more likely and even more Pythonic: >>> [fields[i] for i in selector] ['y', 'y', 'x'] As soon as you get past the easy and obvious case of an existing function, filter and map quickly fall behind comprehensions in utility and readability. ChrisA From mail.python.org at marco.sulla.e4ward.com Thu Mar 31 08:49:51 2016 From: mail.python.org at marco.sulla.e4ward.com (Marco Sulla) Date: Thu, 31 Mar 2016 14:49:51 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fbf879$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8f20$0$1600$c3e8da3$5496439d@news.astraweb.com> Message-ID: I want also to add that we are focusing on sequences, but my proposal is also to make map interface more similar, introducing a vdict type that iterates over values, and this will be for me really more practical. PEP 234 ( http://legacy.python.org/dev/peps/pep-0234/ ) never convinced me. Van Rossum said: > The symmetry between "if x in y" and "for x in y" > suggests that it should iterate over keys. This symmetry has been > observed by many independently and has even been used to "explain" > one using the other. This is because for sequences, "if x in y" > iterates over y comparing the iterated values to x. This argument will never convinced me. It's a lot more practical (as Van Rossum admitted further) to iterate over values by default on maps. Furthermore I see much more symmetry between keys of maps and indexes of sequences, so it's much more natural to make map iteration over values by default, as for sequences. This is why I proposed a vdict. On 31 March 2016 at 14:30, Mark Lawrence via Python-list wrote: > Note that dict also supports > __getitem__() and __len__(), but is considered a mapping rather than a > sequence because the lookups use arbitrary immutable keys rather than > integers. Thank you for confirming for what I already wrote and quoted, but I suppose you missed some of my previous messages, my dear friend. From jussi.piitulainen at helsinki.fi Thu Mar 31 08:55:37 2016 From: jussi.piitulainen at helsinki.fi (Jussi Piitulainen) Date: Thu, 31 Mar 2016 15:55:37 +0300 Subject: Suggestion: make sequence and map interfaces more similar References: <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> <56FD086F.2090301@rece.vub.ac.be> <87poualt87.fsf@elektro.pacujo.net> Message-ID: Marko Rauhamaa writes: > Chris Angelico wrote: > >> Okay. I'll put a slightly different position: Prove that your >> proposal is worth discussing by actually giving us an example that we >> can discuss. > > Sorry for missing most of the arguments here, but if you are talking > about treating lists as special cases of dicts, I have occasionally > instinctively wanted something like this: > > >>> fields = [ "x", "y", "z" ] > >>> selector = (1, 1, 0) > >>> list(map(fields.get, selector)) > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'list' object has no attribute 'get' operator.itemgetter(*selector)(fields) # ==> ('y', 'y', 'x') > analogously with: > > >>> field_dict = { 0: "x", 1: "y", 2: "z" } > >>> list(map(field_dict.get, selector)) > ['y', 'y', 'x'] operator.itemgetter(*selector)(field_dict) # ==> ('y', 'y', 'x') It's not quite the same but it's close and it works the same for strings, lists, dicts, ... From antoon.pardon at rece.vub.ac.be Thu Mar 31 09:08:40 2016 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Thu, 31 Mar 2016 15:08:40 +0200 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> <56FD086F.2090301@rece.vub.ac.be> Message-ID: <56FD2158.2050406@rece.vub.ac.be> Op 31-03-16 om 13:57 schreef Chris Angelico: > Okay. I'll put a slightly different position: Prove that your proposal > is worth discussing by actually giving us an example that we can > discuss. So far, this thread has had nothing but toy examples (and > bogoexamples that prove nothing beyond that the author knows how to > mess with Python - fun, but not a strong argument on either side). > Give us some real meat to work with, instead of these drips of > tantalizing blood. What a strange request. Whether or not something is worth discussing is a personal judgement. So there can be no proof of such a thing. I would say: judge for yourself and act accordingly. -- Antoon From rosuav at gmail.com Thu Mar 31 09:11:49 2016 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 1 Apr 2016 00:11:49 +1100 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56FD2158.2050406@rece.vub.ac.be> References: <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> <56FD086F.2090301@rece.vub.ac.be> <56FD2158.2050406@rece.vub.ac.be> Message-ID: On Fri, Apr 1, 2016 at 12:08 AM, Antoon Pardon wrote: > Op 31-03-16 om 13:57 schreef Chris Angelico: >> Okay. I'll put a slightly different position: Prove that your proposal >> is worth discussing by actually giving us an example that we can >> discuss. So far, this thread has had nothing but toy examples (and >> bogoexamples that prove nothing beyond that the author knows how to >> mess with Python - fun, but not a strong argument on either side). >> Give us some real meat to work with, instead of these drips of >> tantalizing blood. > > What a strange request. Whether or not something is worth discussing > is a personal judgement. So there can be no proof of such a thing. > I would say: judge for yourself and act accordingly. Plonk. ChrisA From breamoreboy at yahoo.co.uk Thu Mar 31 09:14:24 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 31 Mar 2016 14:14:24 +0100 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: <56f8836b$0$1602$c3e8da3$5496439d@news.astraweb.com> <56FA8C71.4050306@rece.vub.ac.be> <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fbf879$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8f20$0$1600$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 31/03/2016 13:49, Marco Sulla via Python-list wrote: > > On 31 March 2016 at 14:30, Mark Lawrence via Python-list > wrote: >> Note that dict also supports >> __getitem__() and __len__(), but is considered a mapping rather than a >> sequence because the lookups use arbitrary immutable keys rather than >> integers. > > Thank you for confirming for what I already wrote and quoted, but I suppose you > missed some of my previous messages, my dear friend. > Thanks for misquoting me by deliberately snipping the bit about taking this completely useless discussion offline. Please do not "dear friend" me as I don't take kindly to people who go out of their way to waste time and effort on this list. This just isn't going to happen, so please drop it, or do you not realise when you're fighting a losing battle, and it's time to retreat? There are of course other options, you could join in the effort to produce Python 2.8 or RickedPython. I'm sure that they'd welcome some additional help and your patch for your absolutely awesome suggestion. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at yahoo.co.uk Thu Mar 31 09:17:21 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 31 Mar 2016 14:17:21 +0100 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <56FD2158.2050406@rece.vub.ac.be> References: <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> <56FD086F.2090301@rece.vub.ac.be> <56FD2158.2050406@rece.vub.ac.be> Message-ID: On 31/03/2016 14:08, Antoon Pardon wrote: > Op 31-03-16 om 13:57 schreef Chris Angelico: >> Okay. I'll put a slightly different position: Prove that your proposal >> is worth discussing by actually giving us an example that we can >> discuss. So far, this thread has had nothing but toy examples (and >> bogoexamples that prove nothing beyond that the author knows how to >> mess with Python - fun, but not a strong argument on either side). >> Give us some real meat to work with, instead of these drips of >> tantalizing blood. > > What a strange request. Whether or not something is worth discussing > is a personal judgement. So there can be no proof of such a thing. > I would say: judge for yourself and act accordingly. > Drivel. This is comp.lang.python, where "Practicality beats purity" every time, not comp.theoretical.claptrap. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From random832 at fastmail.com Thu Mar 31 09:27:53 2016 From: random832 at fastmail.com (Random832) Date: Thu, 31 Mar 2016 09:27:53 -0400 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> <56FD086F.2090301@rece.vub.ac.be> <56FD2158.2050406@rece.vub.ac.be> Message-ID: <1459430873.2282305.564680498.6FEA3042@webmail.messagingengine.com> On Thu, Mar 31, 2016, at 09:17, Mark Lawrence via Python-list wrote: > On 31/03/2016 14:08, Antoon Pardon wrote: > > Op 31-03-16 om 13:57 schreef Chris Angelico: > >> Okay. I'll put a slightly different position: Prove that your proposal > >> is worth discussing by actually giving us an example that we can > >> discuss. So far, this thread has had nothing but toy examples (and > >> bogoexamples that prove nothing beyond that the author knows how to > >> mess with Python - fun, but not a strong argument on either side). > >> Give us some real meat to work with, instead of these drips of > >> tantalizing blood. > > > > What a strange request. Whether or not something is worth discussing > > is a personal judgement. So there can be no proof of such a thing. > > I would say: judge for yourself and act accordingly. > > Drivel. This is comp.lang.python, where "Practicality beats purity" > every time, not comp.theoretical.claptrap. So can we discuss how a unified method to get a set of all valid subscripts (and/or subscript-value pairs) on an object would be a useful thing to have without getting bogged down in theoretical claptrap about the meaning of the mapping contract? From rustompmody at gmail.com Thu Mar 31 09:42:42 2016 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 31 Mar 2016 06:42:42 -0700 (PDT) Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: References: <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> <56FD086F.2090301@rece.vub.ac.be> Message-ID: On Thursday, March 31, 2016 at 6:38:56 PM UTC+5:30, Antoon Pardon wrote: > Op 31-03-16 om 13:57 schreef Chris Angelico: > > Okay. I'll put a slightly different position: Prove that your proposal > > is worth discussing by actually giving us an example that we can > > discuss. So far, this thread has had nothing but toy examples (and > > bogoexamples that prove nothing beyond that the author knows how to > > mess with Python - fun, but not a strong argument on either side). > > Give us some real meat to work with, instead of these drips of > > tantalizing blood. > > What a strange request. Whether or not something is worth discussing > is a personal judgement. So there can be no proof of such a thing. > I would say: judge for yourself and act accordingly. Not been following this thread much And not much interest in the suggestion/request Just thought I'd give a take on what may be the motivation for this There is the allure of One-Fundamental-Data-structure Lisp calls that 'list' [40 years after with more fanfare and less clarity replicated as XML] Math calls that 'function' Even more fundamental in CS than in math That maps are same as functions is standard math. In python one interconverts data?code by going from dict d to d.get code?data by memoization/caching How about a Grand Unified Theory? [Just to be clear -- not my interest or wish] From martinsr1988 at gmail.com Thu Mar 31 09:45:13 2016 From: martinsr1988 at gmail.com (Simon Martin) Date: Thu, 31 Mar 2016 15:45:13 +0200 Subject: Pyscripter Issues Message-ID: <56fd29e7.13821c0a.a7261.0f02@mx.google.com> Hi I have been having issues trying to run python 3.5.1 and pyscripter 2.6. Giving the error message that it cannot initialize python. I have tried to re-install multiple versions of both python and pyscripter to no avail. Any advice? Thanks Simon Sent from Mail for Windows 10 From marko at pacujo.net Thu Mar 31 10:02:30 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 31 Mar 2016 17:02:30 +0300 Subject: Suggestion: make sequence and map interfaces more similar References: <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> <56FD086F.2090301@rece.vub.ac.be> <87poualt87.fsf@elektro.pacujo.net> Message-ID: <87lh4ylp8p.fsf@elektro.pacujo.net> Chris Angelico : > Or, even more likely and even more Pythonic: > >>>> [fields[i] for i in selector] > ['y', 'y', 'x'] > > As soon as you get past the easy and obvious case of an existing > function, filter and map quickly fall behind comprehensions in utility > and readability. The general need is contexts where you need fields[?] act as a function. Of course, lambda i: fields[i] does it. However, weirdly, dicts have get but lists don't. Ok, dict.get() provides for a default value, but couldn't that come in handy for lists as well? Again, lambda would do it for both dicts and lists: lambda i: fields[i] if i >= 0 and i < len(fields) else default lambda key: fields[key] if key in fields else default Marko From breamoreboy at yahoo.co.uk Thu Mar 31 10:12:46 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 31 Mar 2016 15:12:46 +0100 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <1459430873.2282305.564680498.6FEA3042@webmail.messagingengine.com> References: <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> <56FD086F.2090301@rece.vub.ac.be> <56FD2158.2050406@rece.vub.ac.be> <1459430873.2282305.564680498.6FEA3042@webmail.messagingengine.com> Message-ID: On 31/03/2016 14:27, Random832 wrote: > On Thu, Mar 31, 2016, at 09:17, Mark Lawrence via Python-list wrote: >> On 31/03/2016 14:08, Antoon Pardon wrote: >>> Op 31-03-16 om 13:57 schreef Chris Angelico: >>>> Okay. I'll put a slightly different position: Prove that your proposal >>>> is worth discussing by actually giving us an example that we can >>>> discuss. So far, this thread has had nothing but toy examples (and >>>> bogoexamples that prove nothing beyond that the author knows how to >>>> mess with Python - fun, but not a strong argument on either side). >>>> Give us some real meat to work with, instead of these drips of >>>> tantalizing blood. >>> >>> What a strange request. Whether or not something is worth discussing >>> is a personal judgement. So there can be no proof of such a thing. >>> I would say: judge for yourself and act accordingly. >> >> Drivel. This is comp.lang.python, where "Practicality beats purity" >> every time, not comp.theoretical.claptrap. > > So can we discuss how a unified method to get a set of all valid > subscripts (and/or subscript-value pairs) on an object would be a useful > thing to have without getting bogged down in theoretical claptrap about > the meaning of the mapping contract? > We can discuss anything here until the cows come home, but it's a complete waste of time if the powers that be over on python-ideas and/or python-dev don't agree. This was suggested a day or two back but seems to have gone completely over people's heads. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From marko at pacujo.net Thu Mar 31 10:13:00 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 31 Mar 2016 17:13:00 +0300 Subject: Suggestion: make sequence and map interfaces more similar References: <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> <56FD086F.2090301@rece.vub.ac.be> <56FD2158.2050406@rece.vub.ac.be> Message-ID: <87h9fmlor7.fsf@elektro.pacujo.net> Random832 : > So can we discuss how a unified method to get a set of all valid > subscripts (and/or subscript-value pairs) on an object would be a > useful thing to have without getting bogged down in theoretical > claptrap about the meaning of the mapping contract? One could compose a table of correspondences: ------------------------------------------- list (L) dict (D) ------------------------------------------- L[key] = value D[key] = value del L[key] (*) del L[key] key >= 0 and key < len(L) key in D range(len(L)) iter(D) L.clear D.clear L.copy D.copy lambda key: L[key] D.get lambda: enumerate(L) D.items lambda: range(len(L)) D.keys ... ... ------------------------------------------- (*) reassigns all keys Marko From marko at pacujo.net Thu Mar 31 10:19:33 2016 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 31 Mar 2016 17:19:33 +0300 Subject: Suggestion: make sequence and map interfaces more similar References: <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> <56FD086F.2090301@rece.vub.ac.be> <87poualt87.fsf@elektro.pacujo.net> Message-ID: <878u0yloga.fsf@elektro.pacujo.net> Jussi Piitulainen : > operator.itemgetter(*selector)(fields) # ==> ('y', 'y', 'x') > > [...] > > operator.itemgetter(*selector)(field_dict) # ==> ('y', 'y', 'x') > > It's not quite the same but it's close and it works the same for > strings, lists, dicts, ... Not quite the same, but nicely found anyway. Marko From __peter__ at web.de Thu Mar 31 10:55:58 2016 From: __peter__ at web.de (Peter Otten) Date: Thu, 31 Mar 2016 16:55:58 +0200 Subject: sympy References: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> <56fbcd01$0$1599$c3e8da3$5496439d@news.astraweb.com> <99b7cf43-50ff-4de7-8de0-e324658682bf@googlegroups.com> <56fbf7e7$0$1591$c3e8da3$5496439d@news.astraweb.com> <244e1277-e105-4419-a449-7f2012c6d78e@googlegroups.com> Message-ID: Poul Riis wrote: > Den onsdag den 30. marts 2016 kl. 17.59.49 UTC+2 skrev Steven D'Aprano: >> On Thu, 31 Mar 2016 02:23 am, Poul Riis wrote: >> >> > What I intend to do is to let sympy find the derivative of some >> > welldefined function and next define the foundation derivative as a >> > normal function so that I can calculate numerical values or even make a >> > graph. >> >> >> I'm glad you explained what you *actually* wanted, because I was going to >> guess that you wanted to evaluate the derivative at x = 3: >> >> >> py> ftext.evalf(subs={x:3}) >> -0.0600000000000000 >> >> >> >> -- >> Steven > > ... However, the sympy way seems to be about 70 times slower than using > the derivative calculated 'by hand' (try the example below). Can it be > done in a more efficient way? Hm, the two functions fmsympy() and fm() do not return the same value: $ python -i sympy_diff.py 10000 evaluations with sympy : dt1 = 0.7178411483764648 10000 evaluations without sympy: dt2 = 0.10177111625671387 >>> fm(42) cos(42) >>> fmsympy(42) -0.399985314988351 What's the point of that benchmark? > Poul Riis > > > > from sympy import * > from time import * > x=Symbol('x') > ftext=diff(sin(x),x) > > def fmsympy(t): > return ftext.evalf(subs={x:t}) > > def fm(t): > return cos(t) > > nloop=10000 > tstart=time() > # nloop evaluations with sympy > for i in range(0,nloop): > a=fmsympy(1) > dt1=time()-tstart > > # nloop evaluations without sympy > tstart=time() > for i in range(0,nloop): > a=fm(1) > dt2=time()-tstart > > print(nloop,' evaluations with sympy : dt1 =',dt1) > print(nloop,' evaluations without sympy: dt2 =',dt2) From steve at pearwood.info Thu Mar 31 10:59:02 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Apr 2016 01:59:02 +1100 Subject: Pyscripter Issues References: Message-ID: <56fd3b37$0$1600$c3e8da3$5496439d@news.astraweb.com> On Fri, 1 Apr 2016 12:45 am, Simon Martin wrote: > Hi > > I have been having issues trying to run python 3.5.1 and pyscripter 2.6. > Giving the error message that it cannot initialize python. > > I have tried to re-install multiple versions of both python and pyscripter > to no avail. Any advice? Yes: start by copying and pasting the full error message here, so we can read it, rather than summarising it. Generally speaking, re-installing Python should be your last resort. At the very least, there's no point in re-installing until you can be sure that Python itself is broken. What happens if you run "python3" from the command prompt? I've barely touched Windows for probably eight years, and I have no idea how to get a command prompt in Windows 10, but if you can get command.com or cmd.exe (whichever it is) and try running Python from that, you'll soon find out whether Python itself is working. -- Steven From steve at pearwood.info Thu Mar 31 11:07:02 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Apr 2016 02:07:02 +1100 Subject: Slice equivalent to dict.get Message-ID: <56fd3d17$0$1606$c3e8da3$5496439d@news.astraweb.com> Sometimes people look for a method which is equivalent to dict.get, where they can set a default value for when the key isn't found: py> d = {1: 'a', 2: 'b'} py> d.get(999, '?') '?' The equivalent for sequences such as lists and tuples is a slice. If the slice is out of range, Python returns a empty sequence: py> L = [2, 4, 8, 16] py> L[5] # out of range, raises IndexError Traceback (most recent call last): File "", line 1, in IndexError: list index out of range py> L[5:6] # out of range slice return empty list [] To get a default: py> L[5:6] or -1 -1 This is short and simple enough to use in place, but we can also wrap this into a convenient helper function: def get(seq, index, default=None): return (seq[index:index+1] or [default])[0] py> get(L, 2, -1) 8 py> get(L, 200, -1) -1 -- Steven From __peter__ at web.de Thu Mar 31 11:24:50 2016 From: __peter__ at web.de (Peter Otten) Date: Thu, 31 Mar 2016 17:24:50 +0200 Subject: Slice equivalent to dict.get References: <56fd3d17$0$1606$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Sometimes people look for a method which is equivalent to dict.get, where > they can set a default value for when the key isn't found: > > > py> d = {1: 'a', 2: 'b'} > py> d.get(999, '?') > '?' > > > The equivalent for sequences such as lists and tuples is a slice. If the > slice is out of range, Python returns a empty sequence: > > py> L = [2, 4, 8, 16] > py> L[5] # out of range, raises IndexError > Traceback (most recent call last): > File "", line 1, in > IndexError: list index out of range > py> L[5:6] # out of range slice return empty list > [] > > To get a default: > > py> L[5:6] or -1 > -1 > > > This is short and simple enough to use in place, but we can also wrap this > into a convenient helper function: > > def get(seq, index, default=None): > return (seq[index:index+1] or [default])[0] > > > > py> get(L, 2, -1) > 8 > py> get(L, 200, -1) > -1 But note: >>> def get(seq, index, default=None): ... return (seq[index:index+1] or [default])[0] ... >>> get("abc", -1, "default") 'default' God old try...except to the rescue: >>> def get(seq, index, default=None): ... try: return seq[index] ... except IndexError: return default ... >>> get("abc", -1, "default") 'c' From gordon at panix.com Thu Mar 31 11:28:33 2016 From: gordon at panix.com (John Gordon) Date: Thu, 31 Mar 2016 15:28:33 +0000 (UTC) Subject: Pyscripter Issues References: Message-ID: In Simon Martin writes: > I have been having issues trying to run python 3.5.1 and pyscripter 2.6. > Giving the error message that it cannot initialize python. Which version of Python did you get: 32-bit or 64-bit? I vaguely recall that PyScripter won't work with the 64-bit version. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From zachary.ware+pylist at gmail.com Thu Mar 31 11:29:23 2016 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Thu, 31 Mar 2016 10:29:23 -0500 Subject: Pyscripter Issues In-Reply-To: <56fd29e7.13821c0a.a7261.0f02@mx.google.com> References: <56fd29e7.13821c0a.a7261.0f02@mx.google.com> Message-ID: On Thursday, March 31, 2016, Simon Martin wrote: > > Hi > > I have been having issues trying to run python 3.5.1 and pyscripter 2.6. Giving the error message that it cannot initialize python. > > I have tried to re-install multiple versions of both python and pyscripter to no avail. Any advice? Use PyCharm. Less bluntly, I used to be a heavy PyScripter user, but after it took forever for PyScripter to support Python 3.4 (I wasn't even sure if it did yet, but it apparently does as of a year ago, added one year after 3.4 was released), I moved on. PyScripter also has the big disadvantage of being strictly single-platform, unlike Python itself, so if you were to try to develop on another platform you would have to learn a new IDE/editor anyway. I have found PyCharm to be very nice, and very consistent cross-platform--I use it regularly on OSX and Windows, and have also used it on Linux. I'm also becoming rather partial to vim, which is also nicely cross-platform: if you have Git on Windows, you have vim available already. Vim does have a somewhat steeper learning curve, though. Looking a bit deeper into what your problem might actually be, PyScripter does not support Python 3.5. Support for each new Python version has to be added explicitly, and it has not been done for 3.5. If you still want to use PyScripter, you should use the latest release of Python 3.4. Keep in mind that you must match use 32-bit Python with 32-bit PyScripter, and 64-bit Python with 64-bit PyScripter, you cannot mix and match. But seriously, you'll be much happier with PyCharm. -- Zach From ian.g.kelly at gmail.com Thu Mar 31 11:43:50 2016 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 31 Mar 2016 09:43:50 -0600 Subject: Slice equivalent to dict.get In-Reply-To: References: <56fd3d17$0$1606$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Mar 31, 2016 at 9:24 AM, Peter Otten <__peter__ at web.de> wrote: > But note: > >>>> def get(seq, index, default=None): > ... return (seq[index:index+1] or [default])[0] > ... >>>> get("abc", -1, "default") > 'default' The discontinuity between -1 and 0 in indexing is a pain in the rear. Negative indexes are one of those things that may seem like a good idea at first, but I think in the end it causes more trouble than it's worth. There's nothing you can do with L[-x] that you can't do more explicitly with L[len(L) - x]. From srkunze at mail.de Thu Mar 31 12:05:44 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Thu, 31 Mar 2016 18:05:44 +0200 Subject: Slice equivalent to dict.get In-Reply-To: <56fd3d17$0$1606$c3e8da3$5496439d@news.astraweb.com> References: <56fd3d17$0$1606$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56FD4AD8.9080405@mail.de> On 31.03.2016 17:07, Steven D'Aprano wrote: > Sometimes people look for a method which is equivalent to dict.get, where > they can set a default value for when the key isn't found: > > > py> d = {1: 'a', 2: 'b'} > py> d.get(999, '?') > '?' > > > The equivalent for sequences such as lists and tuples is a slice. If the > slice is out of range, Python returns a empty sequence: I see what you are trying to achieve here. What do you think about this? [1, 2, 3].get(999, '?') Best, Sven From travisgriggs at gmail.com Thu Mar 31 12:30:59 2016 From: travisgriggs at gmail.com (Travis Griggs) Date: Thu, 31 Mar 2016 09:30:59 -0700 Subject: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA00EC.80909@gmail.com> <56FA537F.9090506@mail.de> <56FB0FF6.3000305@harvee.org> <56FBA577.6070607@mail.de> Message-ID: <587D892E-8ED0-4B41-AAC9-E40A89477B91@gmail.com> > On Mar 30, 2016, at 2:36 PM, Gregory Ewing wrote: > > Tim Golden wrote: > >> (I don't know how other English-speaking groups say the word, but in >> England the first syllable is stressed and the second is the >> conventional short "uh" sound). > > I can attest that New Zealand follows the UK on this. I was > surprised when I first heard an American pronounce it too. > > The curious can hear the difference on these pages: > > British: http://www.oxforddictionaries.com/definition/english/python > American: http://www.dictionary.com/browse/python?s=t That does it. If I ever make some sort of open source module for pythun/pythawn I?ll be sure to call it either tuhmayto/tomawto. Or maybe I?ll call it puhtayto/potawto. From ian.g.kelly at gmail.com Thu Mar 31 12:34:04 2016 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 31 Mar 2016 10:34:04 -0600 Subject: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: <587D892E-8ED0-4B41-AAC9-E40A89477B91@gmail.com> References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA00EC.80909@gmail.com> <56FA537F.9090506@mail.de> <56FB0FF6.3000305@harvee.org> <56FBA577.6070607@mail.de> <587D892E-8ED0-4B41-AAC9-E40A89477B91@gmail.com> Message-ID: On Thu, Mar 31, 2016 at 10:30 AM, Travis Griggs wrote: > >> On Mar 30, 2016, at 2:36 PM, Gregory Ewing wrote: >> >> Tim Golden wrote: >> >>> (I don't know how other English-speaking groups say the word, but in >>> England the first syllable is stressed and the second is the >>> conventional short "uh" sound). >> >> I can attest that New Zealand follows the UK on this. I was >> surprised when I first heard an American pronounce it too. >> >> The curious can hear the difference on these pages: >> >> British: http://www.oxforddictionaries.com/definition/english/python >> American: http://www.dictionary.com/browse/python?s=t > > That does it. If I ever make some sort of open source module for pythun/pythawn I?ll be sure to call it either tuhmayto/tomawto. Or maybe I?ll call it puhtayto/potawto. Pytato? From srkunze at mail.de Thu Mar 31 12:44:22 2016 From: srkunze at mail.de (Sven R. Kunze) Date: Thu, 31 Mar 2016 18:44:22 +0200 Subject: Learning Python (or Haskell) makes you a worse programmer In-Reply-To: <587D892E-8ED0-4B41-AAC9-E40A89477B91@gmail.com> References: <56f9cffb$0$1614$c3e8da3$5496439d@news.astraweb.com> <56FA00EC.80909@gmail.com> <56FA537F.9090506@mail.de> <56FB0FF6.3000305@harvee.org> <56FBA577.6070607@mail.de> <587D892E-8ED0-4B41-AAC9-E40A89477B91@gmail.com> Message-ID: <56FD53E6.3000400@mail.de> On 31.03.2016 18:30, Travis Griggs wrote: > >> British: http://www.oxforddictionaries.com/definition/english/python >> American: http://www.dictionary.com/browse/python?s=t > That does it. If I ever make some sort of open source module for pythun/pythawn I?ll be sure to call it either tuhmayto/tomawto. Or maybe I?ll call it puhtayto/potawto. Isn't it more like "Pythn"? From rosuav at gmail.com Thu Mar 31 13:05:01 2016 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 1 Apr 2016 04:05:01 +1100 Subject: sympy In-Reply-To: References: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> <56fbcd01$0$1599$c3e8da3$5496439d@news.astraweb.com> <99b7cf43-50ff-4de7-8de0-e324658682bf@googlegroups.com> <56fbf7e7$0$1591$c3e8da3$5496439d@news.astraweb.com> <244e1277-e105-4419-a449-7f2012c6d78e@googlegroups.com> Message-ID: On Fri, Apr 1, 2016 at 1:55 AM, Peter Otten <__peter__ at web.de> wrote: > Hm, the two functions fmsympy() and fm() do not return the same value: > > $ python -i sympy_diff.py > 10000 evaluations with sympy : dt1 = 0.7178411483764648 > 10000 evaluations without sympy: dt2 = 0.10177111625671387 >>>> fm(42) > cos(42) >>>> fmsympy(42) > -0.399985314988351 > Maybe not, but that's simply because one of them is completely evaluated. The cosine of 42 radians is indeed -0.4ish. >>> math.cos(42) -0.39998531498835127 ChrisA From tjreedy at udel.edu Thu Mar 31 13:41:19 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 31 Mar 2016 13:41:19 -0400 Subject: Suggestion: make sequence and map interfaces more similar In-Reply-To: <87h9fmlor7.fsf@elektro.pacujo.net> References: <56fb677f$0$11121$c3e8da3@news.astraweb.com> <56fba7d3$0$1616$c3e8da3$5496439d@news.astraweb.com> <56fbc518$0$1593$c3e8da3$5496439d@news.astraweb.com> <56fbf73d$0$1591$c3e8da3$5496439d@news.astraweb.com> <56fc8e09$0$1600$c3e8da3$5496439d@news.astraweb.com> <56fcfdc6$0$1612$c3e8da3$5496439d@news.astraweb.com> <56FD086F.2090301@rece.vub.ac.be> <56FD2158.2050406@rece.vub.ac.be> <87h9fmlor7.fsf@elektro.pacujo.net> Message-ID: On 3/31/2016 10:13 AM, Marko Rauhamaa wrote: > One could compose a table of correspondences: with some corrections > ------------------------------------------- > list (L) dict (D) > ------------------------------------------- > L[key] = value D[key] = value > del L[key] (*) del L[key] > (*) reassigns all keys > key >= 0 and key < len(L) key in D '-len(L) <= key < len(L)' or 'key in range(-len(L), len(L)' Lists, tuples, and ranges have 2 keys for each value, though that is not guaranteed for sequences in general. key in D == key in D.keys() > range(len(L)) iter(D) iter(range(Len(L)) == iter(D.keys()) > L.clear D.clear > L.copy D.copy > lambda key: L[key] D.get The purpose of D.get() is to supply a default instead of raising KeyError when key not in D. The lambda function above does not do that. Turning subscripting into a function is a side-effect of D.get. A generic get function: def get(subscriptable, key, default=None): try: return subscriptable[key] except (IndexError, KeyError): return default > lambda: enumerate(L) D.items As I pointed out a couple days ago, an enumerate iterator is quite different from a set-like dynamic view. An actual correspondence: enumerate(L) iter(D.items()) Writing a set-like dynamic view of lists corresponding to D.values() or D.items() would be an interesting project. > lambda: range(len(L)) D.keys iter(range(len(L)) iter(D.keys()) Already given above. Iterating indexes is now much rarer than iterating dict keys. -- Terry Jan Reedy From tjreedy at udel.edu Thu Mar 31 13:51:24 2016 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 31 Mar 2016 13:51:24 -0400 Subject: Slice equivalent to dict.get In-Reply-To: References: <56fd3d17$0$1606$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 3/31/2016 11:24 AM, Peter Otten wrote: > Steven D'Aprano wrote: > >> Sometimes people look for a method which is equivalent to dict.get, where >> they can set a default value for when the key isn't found: >> >> >> py> d = {1: 'a', 2: 'b'} >> py> d.get(999, '?') >> '?' >> >> >> The equivalent for sequences such as lists and tuples is a slice. If the >> slice is out of range, Python returns a empty sequence: >> >> py> L = [2, 4, 8, 16] >> py> L[5] # out of range, raises IndexError >> Traceback (most recent call last): >> File "", line 1, in >> IndexError: list index out of range >> py> L[5:6] # out of range slice return empty list >> [] >> >> To get a default: >> >> py> L[5:6] or -1 >> -1 >> >> >> This is short and simple enough to use in place, but we can also wrap this >> into a convenient helper function: >> >> def get(seq, index, default=None): >> return (seq[index:index+1] or [default])[0] >> >> >> >> py> get(L, 2, -1) >> 8 >> py> get(L, 200, -1) >> -1 > > But note: > >>>> def get(seq, index, default=None): > ... return (seq[index:index+1] or [default])[0] > ... >>>> get("abc", -1, "default") > 'default' > > God old try...except to the rescue: > >>>> def get(seq, index, default=None): > ... try: return seq[index] > ... except IndexError: return default Replace IndexError with (IndexError, KeyError) and the functions works with any subscriptable that raises either exception. > ... >>>> get("abc", -1, "default") > 'c' > > -- Terry Jan Reedy From __peter__ at web.de Thu Mar 31 13:51:55 2016 From: __peter__ at web.de (Peter Otten) Date: Thu, 31 Mar 2016 19:51:55 +0200 Subject: sympy References: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> <56fbcd01$0$1599$c3e8da3$5496439d@news.astraweb.com> <99b7cf43-50ff-4de7-8de0-e324658682bf@googlegroups.com> <56fbf7e7$0$1591$c3e8da3$5496439d@news.astraweb.com> <244e1277-e105-4419-a449-7f2012c6d78e@googlegroups.com> Message-ID: Chris Angelico wrote: > On Fri, Apr 1, 2016 at 1:55 AM, Peter Otten <__peter__ at web.de> wrote: >> Hm, the two functions fmsympy() and fm() do not return the same value: >> >> $ python -i sympy_diff.py >> 10000 evaluations with sympy : dt1 = 0.7178411483764648 >> 10000 evaluations without sympy: dt2 = 0.10177111625671387 >>>>> fm(42) >> cos(42) >>>>> fmsympy(42) >> -0.399985314988351 >> > > Maybe not, but that's simply because one of them is completely > evaluated. The cosine of 42 radians is indeed -0.4ish. > >>>> math.cos(42) > -0.39998531498835127 My guess was that the OP fell into the trap that he himself carefully set up with the star import, and accidentally used sympy.cos() where he wanted to invoke math.cos(). The fix would actually increase the speed difference -- but first make it right, then, maybe, fast. Adding another storey to the tower of guesses, Robert Kern has probably already provided the answer ;) From oscar.j.benjamin at gmail.com Thu Mar 31 14:59:31 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 31 Mar 2016 19:59:31 +0100 Subject: sympy In-Reply-To: <244e1277-e105-4419-a449-7f2012c6d78e@googlegroups.com> References: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> <56fbcd01$0$1599$c3e8da3$5496439d@news.astraweb.com> <99b7cf43-50ff-4de7-8de0-e324658682bf@googlegroups.com> <56fbf7e7$0$1591$c3e8da3$5496439d@news.astraweb.com> <244e1277-e105-4419-a449-7f2012c6d78e@googlegroups.com> Message-ID: On 31 March 2016 at 11:57, Poul Riis wrote: > > ... However, the sympy way seems to be about 70 times slower than using the derivative calculated 'by hand' (try the example below). > Can it be done in a more efficient way? > > Poul Riis > > > > from sympy import * > from time import * > x=Symbol('x') > ftext=diff(sin(x),x) > > def fmsympy(t): > return ftext.evalf(subs={x:t}) > > def fm(t): > return cos(t) I think you have misunderstood what is going on here. Let's actually try those two methods out: $ isympy IPython console for SymPy 0.7.5 (Python 2.7.9-64-bit) (ground types: gmpy) These commands were executed: >>> from __future__ import division >>> from sympy import * >>> x, y, z, t = symbols('x y z t') >>> k, m, n = symbols('k m n', integer=True) >>> f, g, h = symbols('f g h', cls=Function) Documentation can be found at http://www.sympy.org In [1]: ftext = diff(sin(x), x) In [2]: ftext Out[2]: cos(x) In [3]: ftext.evalf(subs={x:1}) Out[3]: 0.540302305868140 In [4]: cos(1) Out[4]: cos(1) So the first version (your fmsympy) takes the symbolic expression cos(x) represented as a sympy expression tree and substitutes 1 for x (which requires walking the tree to look fo all occurrences of x). Then it evaluates the result to 15 decimal digits of precision using the pure Python mpmath multiprecision math library. To prove that it's not really a float calculation let's increase the precision: In [5]: ftext.evalf(subs={x:1}, n=100) Out[5]: 0.5403023058681397174009366074429766037323104206179222276700972553811003947744717645179518560871830893 Your second version (fm) makes a sympy expression using the cos function from sympy and the argument 1. This creates a symbolic sympy expression cos(1) and returns that. It doesn't do any evaluation of the expression to get the digits of the actual numeric answer. So I'm not surprised that the two operations take different amounts of time. One doesn't evaluate the expression and the other does using a slow multiprecision library. Also note though that sympy uses a cache to accelerate repeated calculations so if you time it doing the exact same thing repeatedly in a loop then you may just be measuring cache-hit performance for two different inputs rather than actual evaluation time. If you want to see one that's a lot faster use the cos function from the math module: In [9]: from math import cos In [10]: cos(1) Out[10]: 0.540302305868 This calculates cos(1) using IEEE 64-bit binary floating point (Python's float type) with hardware acceleration from your processor's FPU instructions. This should be a lot faster then either substituting into symbolic expressions in sympy or evaluating trignometric functions with mpmath. Generally I would use sympy in order to derive the mathematical expressions that I want to compute. However if I then want to evaluate the expressions many times in a loop with different input numbers for example then I would rewrite the expression without using sympy. Sympy has code generation capabilities to automate this but you seemed to be confused about basic sympy usage right now so I wouldn't recommend them without knowing more about what you're trying to do. -- Oscar From zachary.ware+pylist at gmail.com Thu Mar 31 15:28:47 2016 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Thu, 31 Mar 2016 14:28:47 -0500 Subject: Slice equivalent to dict.get In-Reply-To: References: <56fd3d17$0$1606$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Mar 31, 2016 at 12:51 PM, Terry Reedy wrote: > On 3/31/2016 11:24 AM, Peter Otten wrote: >> try...except to the rescue: >> >>>>> def get(seq, index, default=None): >> >> ... try: return seq[index] >> ... except IndexError: return default > > > Replace IndexError with (IndexError, KeyError) and the functions works with > any subscriptable that raises either exception. Or use the superclass of both of those, LookupError, and also catch anything that uses that more generic name as well. -- Zach From tandrewjohnson at outlook.com Thu Mar 31 16:02:53 2016 From: tandrewjohnson at outlook.com (tjohnson) Date: Thu, 31 Mar 2016 16:02:53 -0400 Subject: Pyscripter Issues In-Reply-To: References: <56fd29e7.13821c0a.a7261.0f02@mx.google.com> Message-ID: <56FD826D.3040002@outlook.com> On 3/31/2016 11:29 AM, Zachary Ware wrote: > On Thursday, March 31, 2016, Simon Martin wrote: >> >> Hi >> >> I have been having issues trying to run python 3.5.1 and pyscripter 2.6. Giving the error message that it cannot initialize python. >> >> I have tried to re-install multiple versions of both python and pyscripter to no avail. Any advice? > > Use PyCharm. > > Less bluntly, I used to be a heavy PyScripter user, but after it took > forever for PyScripter to support Python 3.4 (I wasn't even sure if it > did yet, but it apparently does as of a year ago, added one year after > 3.4 was released), I moved on. PyScripter also has the big > disadvantage of being strictly single-platform, unlike Python itself, > so if you were to try to develop on another platform you would have to > learn a new IDE/editor anyway. I have found PyCharm to be very nice, > and very consistent cross-platform--I use it regularly on OSX and > Windows, and have also used it on Linux. I'm also becoming rather > partial to vim, which is also nicely cross-platform: if you have Git > on Windows, you have vim available already. Vim does have a somewhat > steeper learning curve, though. My situation is similar. I used to use PyScripter and liked it a lot, but when Python 3.4 support wasn't being added and I wanted a cross-platform IDE, I switched to PyDev. > > Looking a bit deeper into what your problem might actually be, > PyScripter does not support Python 3.5. Support for each new Python > version has to be added explicitly, and it has not been done for 3.5.] For the record, it doesn't work with Python 2.7.11 either. PyScripter only supports Python <= 2.7.10 and <= 3.4.x. > > But seriously, you'll be much happier with PyCharm. Or PyDev, whichever you prefer. I think PyCharm is easier to use than PyDev, but it seems too resource heavy for some computers. From tandrewjohnson at outlook.com Thu Mar 31 16:02:53 2016 From: tandrewjohnson at outlook.com (tjohnson) Date: Thu, 31 Mar 2016 16:02:53 -0400 Subject: Pyscripter Issues In-Reply-To: References: <56fd29e7.13821c0a.a7261.0f02@mx.google.com> Message-ID: On 3/31/2016 11:29 AM, Zachary Ware wrote: > On Thursday, March 31, 2016, Simon Martin wrote: >> >> Hi >> >> I have been having issues trying to run python 3.5.1 and pyscripter 2.6. Giving the error message that it cannot initialize python. >> >> I have tried to re-install multiple versions of both python and pyscripter to no avail. Any advice? > > Use PyCharm. > > Less bluntly, I used to be a heavy PyScripter user, but after it took > forever for PyScripter to support Python 3.4 (I wasn't even sure if it > did yet, but it apparently does as of a year ago, added one year after > 3.4 was released), I moved on. PyScripter also has the big > disadvantage of being strictly single-platform, unlike Python itself, > so if you were to try to develop on another platform you would have to > learn a new IDE/editor anyway. I have found PyCharm to be very nice, > and very consistent cross-platform--I use it regularly on OSX and > Windows, and have also used it on Linux. I'm also becoming rather > partial to vim, which is also nicely cross-platform: if you have Git > on Windows, you have vim available already. Vim does have a somewhat > steeper learning curve, though. My situation is similar. I used to use PyScripter and liked it a lot, but when Python 3.4 support wasn't being added and I wanted a cross-platform IDE, I switched to PyDev. > > Looking a bit deeper into what your problem might actually be, > PyScripter does not support Python 3.5. Support for each new Python > version has to be added explicitly, and it has not been done for 3.5.] For the record, it doesn't work with Python 2.7.11 either. PyScripter only supports Python <= 2.7.10 and <= 3.4.x. > > But seriously, you'll be much happier with PyCharm. Or PyDev, whichever you prefer. I think PyCharm is easier to use than PyDev, but it seems too resource heavy for some computers. From priisdk at gmail.com Thu Mar 31 17:33:16 2016 From: priisdk at gmail.com (Poul Riis) Date: Thu, 31 Mar 2016 14:33:16 -0700 (PDT) Subject: sympy In-Reply-To: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> References: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> Message-ID: <9c8497d9-f158-4f94-9a9f-39d6cb63850c@googlegroups.com> Den onsdag den 30. marts 2016 kl. 13.17.33 UTC+2 skrev Poul Riis: > Is it possible to transfer results from sympy to 'normal' python. > > In the case below I think my intention is clear enough but it does not work as intended. How can it be done? > > Poul Riis > > > > > from sympy import * > x=Symbol('x') > ftext=diff(1/(x**2+1),x) > > def f(t): > return ftext.subs(x,'t') > > print(f(3)) Well, cos(1) should have been cos(1.0) (which forces numerical evaluation, try example below). I am just trying to implement one little thing that all CAS tools can do in a few lines, namely finding the derivative of a given function followed by evalution of numerical values, something like: define(fm(x),diff(f(x),x)) fm(1.0) Sympy can find the derivative, and once that has been completed I would expect that there is some way to find numerical values just as fast as if the derivative had been given 'by hand'. But how exactly? Poul Riis from sympy import * from time import * x=Symbol('x') ftext=diff(sin(x),x) def fmsympy(t): return ftext.evalf(subs={x:t}) def fm(t): return cos(t) nloop=10000 tstart=time() for i in range(0,nloop): a=fmsympy(1) dt1=time()-tstart print(a) tstart=time() for i in range(0,nloop): a=fm(1.0) dt2=time()-tstart print(a) print(nloop,' evaluations with sympy : dt1 =',dt1) print(nloop,' evaluations without sympy: dt2 =',dt2) From victor.stinner at gmail.com Thu Mar 31 17:40:45 2016 From: victor.stinner at gmail.com (Victor Stinner) Date: Thu, 31 Mar 2016 23:40:45 +0200 Subject: The next major Python version will be Python 8 Message-ID: Hi, Python 3 becomes more and more popular and is close to a dangerous point where it can become popular that Python 2. The PSF decided that it's time to elaborate a new secret plan to ensure that Python users suffer again with a new major release breaking all their legacy code. The PSF is happy to announce that the new Python release will be Python 8! Why the version 8? It's just to be greater than Perl 6 and PHP 7, but it's also a mnemonic for PEP 8. By the way, each minor release will now multiply the version by 2. With Python 8 released in 2016 and one release every two years, we will beat Firefox 44 in 2022 (Python 64) and Windows 2003 in 2032 (Python 2048). A major release requires a major change to justify a version bump: the new killer feature is that it's no longer possible to import a module which does not respect the PEP 8. It ensures that all your code is pure. Example: $ python8 -c 'import keyword' Lib/keyword.py:16:1: E122 continuation line missing indentation or outdented Lib/keyword.py:16:1: E265 block comment should start with '# ' Lib/keyword.py:50:1: E122 continuation line missing indentation or outdented (...) ImportError: no pep8, no glory Good news: since *no* module of the current standard library of Python 3 respect the PEP 8, the standard library will be simplified to one unique module, which is new in Python 8: pep8. The standard library will move to the Python Cheeseshop (PyPI), to reply to an old and popular request. DON'T PANIC! You are still able to import your legacy code into Python 8, you just have to rename all your modules to add a "_noqa" suffix to the filename. For example, rename utils.py to utils_noqa.py. A side effect is that you have to update all imports. For example, replace "import django" with "import django_noqa". After a study of the PSF, it's a best option to split again the Python community and make sure that all users are angry. The plan is that in 10 years, at least 50% of the 77,000 packages on the Python cheeseshop will be updated to get the "_noqa" tag. After 2020, the PSF will start to sponsor trolls to harass users of the legacy Python 3 to force them to migrate to Python 8. Python 8 is a work-in-progress (it's still an alpha version), the standard library was not removed yet. Hopefully, trying to import any module of the standard library fails. Don't hesitate to propose more ideas to make Python 8 more incompatible with Python 3! Note: The change is already effective in the default branch of Python: https://hg.python.org/cpython/rev/9aedec2dbc01 Have fun, Victor From oscar.j.benjamin at gmail.com Thu Mar 31 18:26:29 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 31 Mar 2016 23:26:29 +0100 Subject: sympy In-Reply-To: <9c8497d9-f158-4f94-9a9f-39d6cb63850c@googlegroups.com> References: <733f5f0d-9b4e-4023-897b-e1f2730c39cb@googlegroups.com> <9c8497d9-f158-4f94-9a9f-39d6cb63850c@googlegroups.com> Message-ID: On 31 March 2016 at 22:33, Poul Riis wrote: > Den onsdag den 30. marts 2016 kl. 13.17.33 UTC+2 skrev Poul Riis: >> Is it possible to transfer results from sympy to 'normal' python. >> >> In the case below I think my intention is clear enough but it does not work as intended. How can it be done? >> >> Poul Riis >> >> from sympy import * >> x=Symbol('x') >> ftext=diff(1/(x**2+1),x) >> >> def f(t): >> return ftext.subs(x,'t') >> >> print(f(3)) > > Well, cos(1) should have been cos(1.0) (which forces numerical evaluation, try example below). > I am just trying to implement one little thing that all CAS tools can do in a few lines, namely finding the derivative of a given function followed by evalution of numerical values, something like: > define(fm(x),diff(f(x),x)) > fm(1.0) > > Sympy can find the derivative, and once that has been completed I would expect that there is some way to find numerical values just as fast as if the derivative had been given 'by hand'. But how exactly? I assume that you're responding to me (even though your post is a reply to yourself). Robert Kern already answered this question earlier in the thread: $ isympy IPython console for SymPy 0.7.5 (Python 2.7.9-64-bit) (ground types: gmpy) These commands were executed: >>> from __future__ import division >>> from sympy import * >>> x, y, z, t = symbols('x y z t') >>> k, m, n = symbols('k m n', integer=True) >>> f, g, h = symbols('f g h', cls=Function) Documentation can be found at http://www.sympy.org In [1]: f = lambdify(x, sin(x).diff(x)) In [2]: f Out[2]: > In [3]: f(1) Out[3]: 0.540302305868 We can pull apart this function f returned here: In [4]: import dis In [5]: dis.dis(f) 1 0 LOAD_GLOBAL 0 (cos) 3 LOAD_FAST 0 (x) 6 CALL_FUNCTION 1 9 RETURN_VALUE In [6]: f.func_globals['cos'] Out[6]: So the function f returned by lambdify uses math.cos which is the 64-bit float function I mentioned earlier (i.e. the faster one). You can pass an int in and it will be coerced to float. You should find that the performance of f is as good as lambda x: math.cos(x). So lambdify takes an expression and a sequence of symbols and generates a function whose arguments are substituted for the sequence of symbols. The return value of the function is the result of substituting the arguments for the symbols in the expression. I think this is what you asked for. -- Oscar From kpvosburgh at gmail.com Thu Mar 31 18:27:05 2016 From: kpvosburgh at gmail.com (hellofootball1 .) Date: Thu, 31 Mar 2016 18:27:05 -0400 Subject: pip.exe issue with 3.5.1 Message-ID: So i just downloaded python 3.5.1 on my laptop and my pip.exe was not working. It would almost immediately close on me after I clicked on it. So i deleted the scripts folder as all of them did the same thing and then tried the modify feature and the repair feature of your installer to try and get pip back but it has not worked. Would you just recommend that I install 3.4.4 and just use that instead? From larry.martell at gmail.com Thu Mar 31 19:56:55 2016 From: larry.martell at gmail.com (Larry Martell) Date: Thu, 31 Mar 2016 19:56:55 -0400 Subject: Convert set to list Message-ID: I feel like I've converted sets to lists before. But maybe not. Or maybe I am losing it from having worked 70 hours this week. Shouldn't this work? (Pdb) print block['relative_chart1']['vessel_names'] set([u'Common Carotid', u'External Carotid', u'Internal Carotid']) (Pdb) type(block['relative_chart1']['vessel_names']) (Pdb) list(block['relative_chart1']['vessel_names']) *** Error in argument: "(block['relative_chart1']['vessel_names'])" From rosuav at gmail.com Thu Mar 31 20:00:36 2016 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 1 Apr 2016 11:00:36 +1100 Subject: Convert set to list In-Reply-To: References: Message-ID: On Fri, Apr 1, 2016 at 10:56 AM, Larry Martell wrote: > I feel like I've converted sets to lists before. But maybe not. Or > maybe I am losing it from having worked 70 hours this week. > > Shouldn't this work? > > (Pdb) print block['relative_chart1']['vessel_names'] > set([u'Common Carotid', u'External Carotid', u'Internal Carotid']) > (Pdb) type(block['relative_chart1']['vessel_names']) > > (Pdb) list(block['relative_chart1']['vessel_names']) > *** Error in argument: "(block['relative_chart1']['vessel_names'])" What exactly does "Error in argument" mean? Normally I would agree, yes, you should be able to iterate over a set exactly like that. ChrisA From roel at roelschroeven.net Thu Mar 31 20:02:34 2016 From: roel at roelschroeven.net (Roel Schroeven) Date: Fri, 01 Apr 2016 02:02:34 +0200 Subject: The next major Python version will be Python 8 In-Reply-To: References: Message-ID: Victor Stinner schreef op 2016-03-31 23:40: > Python 3 becomes more and more popular and is close to a dangerous point > where it can become popular that Python 2. The PSF decided that it's > time to elaborate a new secret plan to ensure that Python users suffer > again with a new major release breaking all their legacy code. "2016-03-31 23:40" You're 20 minutes early :) -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From ben+python at benfinney.id.au Thu Mar 31 20:06:16 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 01 Apr 2016 11:06:16 +1100 Subject: Convert set to list References: Message-ID: <85y48y8a6f.fsf@benfinney.id.au> Larry Martell writes: > I feel like I've converted sets to lists before. But maybe not. Or > maybe I am losing it from having worked 70 hours this week. > > Shouldn't this work? In a Python interactive shell? Yes. In the PDB shell? No, because some different names are defined as commands. Such as ?list?. -- \ ?The trouble with Communism is the Communists, just as the | `\ trouble with Christianity is the Christians.? ?Henry L. Mencken | _o__) | Ben Finney From rgaddi at highlandtechnology.invalid Thu Mar 31 20:06:35 2016 From: rgaddi at highlandtechnology.invalid (Rob Gaddi) Date: Fri, 1 Apr 2016 00:06:35 -0000 (UTC) Subject: Convert set to list References: Message-ID: Larry Martell wrote: > I feel like I've converted sets to lists before. But maybe not. Or > maybe I am losing it from having worked 70 hours this week. > > Shouldn't this work? > > (Pdb) print block['relative_chart1']['vessel_names'] > set([u'Common Carotid', u'External Carotid', u'Internal Carotid']) > (Pdb) type(block['relative_chart1']['vessel_names']) > > (Pdb) list(block['relative_chart1']['vessel_names']) > *** Error in argument: "(block['relative_chart1']['vessel_names'])" Pdb takes the "list" command as a request to list source code. print list(block['relative_chart1']['vessel_names']) should work. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From darcy at Vex.Net Thu Mar 31 20:06:45 2016 From: darcy at Vex.Net (D'Arcy J.M. Cain) Date: Thu, 31 Mar 2016 20:06:45 -0400 Subject: The next major Python version will be Python 8 In-Reply-To: References: Message-ID: <20160331200645.2a91845e@imp> On Fri, 01 Apr 2016 02:02:34 +0200 Roel Schroeven wrote: > Victor Stinner schreef op 2016-03-31 23:40: > > Python 3 becomes more and more popular and is close to a dangerous > > point where it can become popular that Python 2. The PSF decided > > that it's time to elaborate a new secret plan to ensure that Python > > users suffer again with a new major release breaking all their > > legacy code. > > "2016-03-31 23:40" > You're 20 minutes early :) And too obvious. -- D'Arcy J.M. Cain System Administrator, Vex.Net http://www.Vex.Net/ IM:darcy at Vex.Net VoIP: sip:darcy at Vex.Net From larry.martell at gmail.com Thu Mar 31 20:08:55 2016 From: larry.martell at gmail.com (Larry Martell) Date: Thu, 31 Mar 2016 20:08:55 -0400 Subject: Convert set to list In-Reply-To: <85y48y8a6f.fsf@benfinney.id.au> References: <85y48y8a6f.fsf@benfinney.id.au> Message-ID: On Thursday, March 31, 2016, Ben Finney wrote: > Larry Martell > writes: > > > I feel like I've converted sets to lists before. But maybe not. Or > > maybe I am losing it from having worked 70 hours this week. > > > > Shouldn't this work? > > In a Python interactive shell? Yes. > > In the PDB shell? No, because some different names are defined as > commands. Such as ?list?. > Ahhhhhhh. Thanks. Time for a break. From ethan at stoneleaf.us Thu Mar 31 20:09:31 2016 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 31 Mar 2016 17:09:31 -0700 Subject: The next major Python version will be Python 8 In-Reply-To: References: Message-ID: <56FDBC3B.80202@stoneleaf.us> On 03/31/2016 05:02 PM, Roel Schroeven wrote: > Victor Stinner schreef op 2016-03-31 23:40: >> Python 3 becomes more and more popular and is close to a dangerous point >> where it can become popular that Python 2. The PSF decided that it's >> time to elaborate a new secret plan to ensure that Python users suffer >> again with a new major release breaking all their legacy code. > > "2016-03-31 23:40" > You're 20 minutes early :) No, that's a naive datetime. You need to travel to Victor's location to figure out what that is there. I sure hope Python 8 doesn't have that problem! -- ~Ethan~ From irmen.NOSPAM at xs4all.nl Thu Mar 31 20:12:56 2016 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 1 Apr 2016 02:12:56 +0200 Subject: pip.exe issue with 3.5.1 In-Reply-To: References: Message-ID: <56fdbd06$0$5893$e4fe514c@news.xs4all.nl> On 1-4-2016 0:27, hellofootball1 . wrote: > So i just downloaded python 3.5.1 on my laptop and my pip.exe was not > working. It would almost immediately close on me after I clicked on it. So > i deleted the scripts folder as all of them did the same thing and then > tried the modify feature and the repair feature of your installer to try > and get pip back but it has not worked. Would you just recommend that I > install 3.4.4 and just use that instead? > No. Pip works fine with python 3.5.1. What did you expect to happen? Pip is not a program that you *click* on, you operate it from the command line instead. Try typing 'pip.exe' on a cmd prompt and go from there. Irmen From rosuav at gmail.com Thu Mar 31 20:13:43 2016 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 1 Apr 2016 11:13:43 +1100 Subject: The next major Python version will be Python 8 In-Reply-To: <56FDBC3B.80202@stoneleaf.us> References: <56FDBC3B.80202@stoneleaf.us> Message-ID: On Fri, Apr 1, 2016 at 11:09 AM, Ethan Furman wrote: > On 03/31/2016 05:02 PM, Roel Schroeven wrote: >> >> Victor Stinner schreef op 2016-03-31 23:40: > > >>> Python 3 becomes more and more popular and is close to a dangerous point >>> where it can become popular that Python 2. The PSF decided that it's >>> time to elaborate a new secret plan to ensure that Python users suffer >>> again with a new major release breaking all their legacy code. >> >> >> "2016-03-31 23:40" >> You're 20 minutes early :) > > > No, that's a naive datetime. You need to travel to Victor's location to > figure out what that is there. > > I sure hope Python 8 doesn't have that problem! Now's the time to get in with the ideas. My proposal is that Python 8, in keeping with its new opinionated style, will require everyone to follow a single timezone: Europe/Amsterdam. ChrisA From roel at roelschroeven.net Thu Mar 31 20:19:54 2016 From: roel at roelschroeven.net (Roel Schroeven) Date: Fri, 01 Apr 2016 02:19:54 +0200 Subject: The next major Python version will be Python 8 In-Reply-To: <56FDBC3B.80202@stoneleaf.us> References: <56FDBC3B.80202@stoneleaf.us> Message-ID: Ethan Furman schreef op 2016-04-01 02:09: > On 03/31/2016 05:02 PM, Roel Schroeven wrote: >> Victor Stinner schreef op 2016-03-31 23:40: > >>> Python 3 becomes more and more popular and is close to a dangerous point >>> where it can become popular that Python 2. The PSF decided that it's >>> time to elaborate a new secret plan to ensure that Python users suffer >>> again with a new major release breaking all their legacy code. >> "2016-03-31 23:40" >> You're 20 minutes early :) > > No, that's a naive datetime. You need to travel to Victor's location to > figure out what that is there. I'm not sure exactly how this stuff works, but I was under the impression that that was a local datetime in Victor's timezone. I might very well be wrong about that. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From nospam at dfs.com Thu Mar 31 23:44:23 2016 From: nospam at dfs.com (DFS) Date: Thu, 31 Mar 2016 23:44:23 -0400 Subject: Use pyodbc to count and list tables, columns, indexes, etc Message-ID: ================================================================ import pyodbc dbName = "D:\test_data.mdb" conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+dbName) cursor = conn.cursor() #COUNT TABLES, LIST COLUMNS tblCount = 0 for rows in cursor.tables(): if rows.table_type == "TABLE": #LOCAL TABLES ONLY tblCount += 1 print rows.table_name for fld in cursor.columns(rows.table_name): print(fld.table_name, fld.column_name) print tblCount,"tables" ================================================================ Problem is, the 'for rows' loop executes only once if the 'for fld' loop is in place. So even if I have 50 tables, the output is like: DATA_TYPES (u'DATA_TYPES', u'FLD_TEXT', -9, u'VARCHAR') (u'DATA_TYPES', u'FLD_MEMO', -10, u'LONGCHAR') (u'DATA_TYPES', u'FLD_NBR_BYTE', -6, u'BYTE') 1 tables And no errors are thrown. If I comment out the 2 'for fld' lines, it counts and lists all 50 tables correctly. Any ideas? Thanks! From steve at pearwood.info Thu Mar 31 23:50:23 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Apr 2016 14:50:23 +1100 Subject: The next major Python version will be Python 8 References: <56FDBC3B.80202@stoneleaf.us> Message-ID: <56fdf000$0$1607$c3e8da3$5496439d@news.astraweb.com> On Fri, 1 Apr 2016 11:13 am, Chris Angelico wrote: > Now's the time to get in with the ideas. My proposal is that Python 8, > in keeping with its new opinionated style, will require everyone to > follow a single timezone: Europe/Amsterdam. Swatch Internet time: https://en.wikipedia.org/wiki/Swatch_Internet_Time -- Steven From danhehnad at hotmail.com Thu Mar 31 23:56:54 2016 From: danhehnad at hotmail.com (Daniel Ding) Date: Fri, 1 Apr 2016 03:56:54 +0000 Subject: Issue with opening a python file Message-ID: Hello, I'm relatively new to python. Recently I have been receiving errors every time I attempt to open python files. When try open them, it sends me directly to the 'Modify Setup' window. Clicking on repair or modify does not fix the problem, it simply goes through the repair or modify process and then closes, whilst the problem still persists. Is there any possible fix for this? Thank you