From ian.g.kelly at gmail.com Sat Nov 1 02:12:53 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 1 Nov 2014 00:12:53 -0600 Subject: Classes In-Reply-To: <54543231$0$13000$c3e8da3$5496439d@news.astraweb.com> References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <54543231$0$13000$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Oct 31, 2014 at 7:06 PM, Steven D'Aprano wrote: > And there are times when using getters and setters is the right choice. > Properties should only be used for quite lightweight calculations, because > attribute access is supposed to be fast. If your calculation is complex, > time-consuming or might fail, using a property is a bad idea and you should > use an explicit getter method, possibly with a setter if needed. I agree except that in this scenario you should probably use a verb other than "get", since getters should also be fast. From rosuav at gmail.com Sat Nov 1 02:32:09 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Nov 2014 17:32:09 +1100 Subject: Classes In-Reply-To: References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <54543231$0$13000$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Nov 1, 2014 at 5:12 PM, Ian Kelly wrote: > On Fri, Oct 31, 2014 at 7:06 PM, Steven D'Aprano > wrote: >> And there are times when using getters and setters is the right choice. >> Properties should only be used for quite lightweight calculations, because >> attribute access is supposed to be fast. If your calculation is complex, >> time-consuming or might fail, using a property is a bad idea and you should >> use an explicit getter method, possibly with a setter if needed. > > I agree except that in this scenario you should probably use a verb > other than "get", since getters should also be fast. Maybe. "get_track_length()" might be a reasonable method name for something that opens an audio file, reads its header, and returns its length in seconds. It should be a method rather than a property (attribute access should be fast), but "get" makes sense here, as it's not calculating or anything, it's just retrieving information. But yes, if it's a calculation, "calc" would be more common. ChrisA From auriocus at gmx.de Sat Nov 1 04:02:12 2014 From: auriocus at gmx.de (Christian Gollwitzer) Date: Sat, 01 Nov 2014 09:02:12 +0100 Subject: Challenge: optimizing isqrt In-Reply-To: <54543787$0$13005$c3e8da3$5496439d@news.astraweb.com> References: <54543787$0$13005$c3e8da3$5496439d@news.astraweb.com> Message-ID: Hi Steven, let me start by answering from reverse: > Q3: What is the largest value of n beyond which you can never use the float > optimization? > A3: There is no such value, besides the upper limit of floats (DBL_MAX~ 10^308) P3: If you feed a perfect square into the floating point square root algorithm, with a mantissa of the root of length smaller than the bitwidth of your float, it will always come out perfectly. I.e., computing sqrt(25) in FP math is no different from sqrt(25*2**200): >>> 25*2**200 40173451106474756888549052308529065063055074844569820882534400L >>> x=int(math.sqrt(25*2**200)) >>> x 6338253001141147007483516026880L >>> x*x 40173451106474756888549052308529065063055074844569820882534400L >>> Am 01.11.14 02:29, schrieb Steven D'Aprano: > There is an algorithm for calculating the integer square root of any > positive integer using only integer operations: > > def isqrt(n): > if n < 0: raise ValueError > if n == 0: > return 0 > bits = n.bit_length() > a, b = divmod(bits, 2) > x = 2**(a+b) > while True: > y = (x + n//x)//2 > if y >= x: > return x > x = y > Q2: For values above M, is there a way of identifying which values of n are > okay to use the optimized version? A2: Do it in a different way. Your above algorithm is obviously doing Heron- or Newton-Raphson iterations, so the same as with floating point math. The first line before the while loop computes some approximation to sqrt(n). Instead of doing bit shuffling, you could compute this by FP math and get closer to the desired result, unless the integer is too large to be represented by FP. Now, the terminating condition seems to rely on the fact that the initial estimate x>=sqrt(n), but I don't really understand it. My guess is that if you do x=int(sqrt(n)), then do the first iteration, then swap x and y such that x>y, then enter the loop, you would simply start with a better estimate in case that the significant bits can be represented by the float. So this is my try, but not thoroughly tested: def isqrt(n): if n < 0: raise ValueError if n == 0: return 0 bits = n.bit_length() # the highest exponent in 64bit IEEE is 1023 if n>2**1022: a, b = divmod(bits, 2) x = 2**(a+b) else: x=int(math.sqrt(n)) y=n//x if x= x: return x x = y Christian From auriocus at gmx.de Sat Nov 1 04:09:26 2014 From: auriocus at gmx.de (Christian Gollwitzer) Date: Sat, 01 Nov 2014 09:09:26 +0100 Subject: Challenge: optimizing isqrt In-Reply-To: References: <54543787$0$13005$c3e8da3$5496439d@news.astraweb.com> Message-ID: Addendum: If my method below works, you can also use it to speed up computations for n>2*1022, by splitting off an even power of two from the integer and computing the FP sqrt of the mantissa for the seed, i.e. doing the FP manually. Am 01.11.14 09:02, schrieb Christian Gollwitzer: > Hi Steven, > > let me start by answering from reverse: > > Q3: What is the largest value of n beyond which you can never use the > float > > optimization? > > > > A3: There is no such value, besides the upper limit of floats (DBL_MAX~ > 10^308) > > P3: If you feed a perfect square into the floating point square root > algorithm, with a mantissa of the root of length smaller than the > bitwidth of your float, it will always come out perfectly. I.e., > computing sqrt(25) in FP math is no different from sqrt(25*2**200): > > >>> 25*2**200 > 40173451106474756888549052308529065063055074844569820882534400L > >>> x=int(math.sqrt(25*2**200)) > >>> x > 6338253001141147007483516026880L > >>> x*x > 40173451106474756888549052308529065063055074844569820882534400L > >>> > > > > Am 01.11.14 02:29, schrieb Steven D'Aprano: >> There is an algorithm for calculating the integer square root of any >> positive integer using only integer operations: >> >> def isqrt(n): >> if n < 0: raise ValueError >> if n == 0: >> return 0 >> bits = n.bit_length() >> a, b = divmod(bits, 2) >> x = 2**(a+b) >> while True: >> y = (x + n//x)//2 >> if y >= x: >> return x >> x = y > >> Q2: For values above M, is there a way of identifying which values of >> n are >> okay to use the optimized version? > > A2: Do it in a different way. > > Your above algorithm is obviously doing Heron- or Newton-Raphson > iterations, so the same as with floating point math. The first line > before the while loop computes some approximation to sqrt(n). Instead of > doing bit shuffling, you could compute this by FP math and get closer to > the desired result, unless the integer is too large to be represented by > FP. Now, the terminating condition seems to rely on the fact that the > initial estimate x>=sqrt(n), but I don't really understand it. My guess > is that if you do x=int(sqrt(n)), then do the first iteration, then swap > x and y such that x>y, then enter the loop, you would simply start with > a better estimate in case that the significant bits can be represented > by the float. > > So this is my try, but not thoroughly tested: > > def isqrt(n): > if n < 0: raise ValueError > if n == 0: > return 0 > bits = n.bit_length() > # the highest exponent in 64bit IEEE is 1023 > if n>2**1022: > a, b = divmod(bits, 2) > x = 2**(a+b) > else: > x=int(math.sqrt(n)) > y=n//x > if x x,y = (y,x) > > while True: > y = (x + n//x)//2 > if y >= x: > return x > x = y > > > Christian > > > > From rosuav at gmail.com Sat Nov 1 04:13:34 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Nov 2014 19:13:34 +1100 Subject: Challenge: optimizing isqrt In-Reply-To: References: <54543787$0$13005$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Nov 1, 2014 at 7:02 PM, Christian Gollwitzer wrote: > Your above algorithm is obviously doing Heron- or Newton-Raphson iterations, > so the same as with floating point math. The first line before the while > loop computes some approximation to sqrt(n). Instead of doing bit shuffling, > you could compute this by FP math and get closer to the desired result, > unless the integer is too large to be represented by FP. Now, the > terminating condition seems to rely on the fact that the initial estimate > x>=sqrt(n), but I don't really understand it. My guess is that if you do > x=int(sqrt(n)), then do the first iteration, then swap x and y such that > x>y, then enter the loop, you would simply start with a better estimate in > case that the significant bits can be represented by the float. Part of the point of that algorithm is that it never uses FP, and is therefore not limited by FP restrictions. As to the assumption that x>=sqrt(n), that would be safe: if the bit length is even (that is, it's between an odd power of 2 and an even one - for example, 2**13 < 16000 <= 2**14), the initial estimate is the exact square root of the power of two at the top of that range (bit length of 14 means x is 2**7, 128 == sqrt(16384)); if the bit length is odd (eg 2**8 < 300 <= 2**9), the initial estimate rounds the halving upward (bit length of 9 means x is 2**(9//2+1), 32 > sqrt(512)). So there's a guarantee that the initial estimate is no lower than the target number. ChrisA From auriocus at gmx.de Sat Nov 1 04:25:40 2014 From: auriocus at gmx.de (Christian Gollwitzer) Date: Sat, 01 Nov 2014 09:25:40 +0100 Subject: Challenge: optimizing isqrt In-Reply-To: References: <54543787$0$13005$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 01.11.14 09:13, schrieb Chris Angelico: > On Sat, Nov 1, 2014 at 7:02 PM, Christian Gollwitzer wrote: >> Your above algorithm is obviously doing Heron- or Newton-Raphson iterations, >> so the same as with floating point math. The first line before the while >> loop computes some approximation to sqrt(n). Instead of doing bit shuffling, >> you could compute this by FP math and get closer to the desired result, >> unless the integer is too large to be represented by FP. Now, the >> terminating condition seems to rely on the fact that the initial estimate >> x>=sqrt(n), but I don't really understand it. My guess is that if you do >> x=int(sqrt(n)), then do the first iteration, then swap x and y such that >> x>y, then enter the loop, you would simply start with a better estimate in >> case that the significant bits can be represented by the float. > > Part of the point of that algorithm is that it never uses FP, and is > therefore not limited by FP restrictions. which are??? From rosuav at gmail.com Sat Nov 1 04:33:08 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Nov 2014 19:33:08 +1100 Subject: Challenge: optimizing isqrt In-Reply-To: References: <54543787$0$13005$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Nov 1, 2014 at 7:25 PM, Christian Gollwitzer wrote: >> Part of the point of that algorithm is that it never uses FP, and is >> therefore not limited by FP restrictions. > > > which are??? Most notably, the inability to represent every integer beyond 2**53, and the inability to represent any integer beyond 2**1024. This algorithm should work fine with any positive integer. ChrisA From auriocus at gmx.de Sat Nov 1 04:38:12 2014 From: auriocus at gmx.de (Christian Gollwitzer) Date: Sat, 01 Nov 2014 09:38:12 +0100 Subject: Challenge: optimizing isqrt In-Reply-To: References: <54543787$0$13005$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 01.11.14 09:33, schrieb Chris Angelico: > On Sat, Nov 1, 2014 at 7:25 PM, Christian Gollwitzer wrote: >>> Part of the point of that algorithm is that it never uses FP, and is >>> therefore not limited by FP restrictions. >> >> >> which are??? > > Most notably, the inability to represent every integer beyond 2**53, > and the inability to represent any integer beyond 2**1024. This > algorithm should work fine with any positive integer. > OK so you did not bother to look at my proposed alternative implementation. If I understood Steven correctly, he wanted to speed up the original isqrt algorithm by using FP when this is possible. I have shown how to do it for n<2**1022 (maybe 2**1024, I'm to lean to check it). I admit that there is some microoptimizatio left, e.g. the first division is done twice, the comparison should be bits>1022, not n>2*1022 etc. Christian From rosuav at gmail.com Sat Nov 1 04:45:45 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Nov 2014 19:45:45 +1100 Subject: Challenge: optimizing isqrt In-Reply-To: References: <54543787$0$13005$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Nov 1, 2014 at 7:38 PM, Christian Gollwitzer wrote: > Am 01.11.14 09:33, schrieb Chris Angelico: >> >> On Sat, Nov 1, 2014 at 7:25 PM, Christian Gollwitzer >> wrote: >>>> >>>> Part of the point of that algorithm is that it never uses FP, and is >>>> therefore not limited by FP restrictions. >>> >>> >>> >>> which are??? >> >> >> Most notably, the inability to represent every integer beyond 2**53, >> and the inability to represent any integer beyond 2**1024. This >> algorithm should work fine with any positive integer. >> > OK so you did not bother to look at my proposed alternative implementation. > If I understood Steven correctly, he wanted to speed up the original isqrt > algorithm by using FP when this is possible. I have shown how to do it for > n<2**1022 (maybe 2**1024, I'm to lean to check it). I admit that there is > some microoptimizatio left, e.g. the first division is done twice, the > comparison should be bits>1022, not n>2*1022 etc. I did look at it. Trouble is, I don't know floating point's details well enough to prove that there are no *other* limitations. FWIW, I've proven the algorithm as far as 2**38. That's still a long way short of 2**53, though, and getting as far as 2**39 would, with my brute-force checker, require between 2.5 and 5 hours. I've made some improvements over the original, but it's still slow. ChrisA From 4kir4.1i at gmail.com Sat Nov 1 05:12:02 2014 From: 4kir4.1i at gmail.com (Akira Li) Date: Sat, 01 Nov 2014 12:12:02 +0300 Subject: Challenge: optimizing isqrt References: <54543787$0$13005$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8761ezp9nh.fsf@gmail.com> Steven D'Aprano writes: > There is an algorithm for calculating the integer square root of any > positive integer using only integer operations: > > def isqrt(n): > if n < 0: raise ValueError > if n == 0: > return 0 > bits = n.bit_length() > a, b = divmod(bits, 2) > x = 2**(a+b) > while True: > y = (x + n//x)//2 > if y >= x: > return x > x = y > > This returns the integer part of the square root of n, that is, the greatest > whole number less than or equal to the square root of n: > > py> isqrt(35) > 5 > py> isqrt(36) > 6 > > > That makes it equivalent to int(math.sqrt(n)), which also happens to be > much, much faster, at least for small values of n. However, for large > values of n, using floating point intermediate calculations fail: > > py> import math > py> int(math.sqrt(2**3000)) > Traceback (most recent call last): > File "", line 1, in > OverflowError: long int too large to convert to float > > Another problem is that, above a certain size, the resolution of floats is > larger than 1, so you can't convert every int into a float without loss: > > py> float(2**90-1) == 2**90-1 > False > > which means that using math.sqrt is not correct: > > py> isqrt(2**90-1) > 35184372088831 > py> int(math.sqrt(2**90-1)) # Off by one. > 35184372088832 > > > So, the challenge is to identify when it is safe to optimise isqrt(n) as > int(math.sqrt(n)): > > Q1: What is the largest value of M, such that > > all(isqrt(i) == int(math.sqrt(n)) for n in range(M)) > > returns True? > > I have done a brute force test, and in nine hours confirmed that M is at > least 7627926244. That took nine hours, and I expect that a brute force > test of every int representable as a float would take *months* of > processing time. > > Q2: For values above M, is there a way of identifying which values of n are > okay to use the optimized version? > > Q3: What is the largest value of n beyond which you can never use the float > optimization? > > > You can assume that Python floats are IEEE-754 C doubles, and that > math.sqrt() is correctly rounded. Where do you want to use your optimized isqrt(i)? There could be specialized algorithms that work only in narrow specific circumstances e.g., the inverse square root (1/sqrt(x)) implementation from Quake III Arena that has 0x5f3759df constant in it (only of historical interest now). If you want to work with very large (thousands, millions of digits) integers then gmp library might be faster then the default Python integer implementation. -- Akira From nad at acm.org Sat Nov 1 06:52:44 2014 From: nad at acm.org (Ned Deily) Date: Sat, 01 Nov 2014 03:52:44 -0700 Subject: Build Question: How to Add -Wl, --option Before Objects In Setup.py? References: Message-ID: In article , Cyd Haselton wrote: > So, after trying various ways to add that flag before lpython in > setup.py, I stripped all --allow-shlib-undefined > --no-allow-shlib-undefined feom the Makefile, ran make clean, and > make. > > I still get the following error: > Modules/python.o \ > -lc -ldl -lm -L. -lpython2.7 -lm > ./libpython2.7.so: undefined reference to `sincos' > collect2: error: ld returned 1 exit status > make: *** [python] Error 1 I don't understand why you are seeing that problem *unless" you might be running into this issue that I found by searching for "sincos Android": https://code.google.com/p/android/issues/detail?id=38423 That looks awfully suspicious. If it isn't that, I don't know what to tell you. You could open an issue on the Python bug tracker (bugs.python.org) but we don't officially support Android so I doubt that will help much. If you haven't already, you might try asking on some Android forums; I know other oddities of building things on Android have been reported. Good luck! -- Ned Deily, nad at acm.org From juan0christian at gmail.com Sat Nov 1 07:41:12 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sat, 1 Nov 2014 09:41:12 -0200 Subject: Python 3.4.2 + PyQt4 + PyCharm 3.4.1 In-Reply-To: References: Message-ID: No one here uses PyCharm and Qt? =/ On Wed, Oct 29, 2014 at 8:45 PM, Juan Christian wrote: > It only occurs whule using PyCharm I tried it via pure terminal and > everything works... =/ > > On Tue, Oct 28, 2014 at 7:45 PM, Juan Christian > wrote: > >> Python 3.4.2 Windows x64 >> PyQt4 4.11.2 Py3.4 Qt4.8.6 (x64) >> PyCharm 3.4.1 Pro Edition >> >> >> So, PyCharm works 100% with everything here but PyQt. >> >> I have this folder structure: >> >> Disk C: >> > PyQt4 >> >> Lib/site-packages/PyQt4/(tons of files here) >> >> > Python34 (normal/default installation) >> >> --- >> >> I tried copying the 'PyQt4' folder to my 'Python34/Lib/site-packages' >> folder but when I try to code something Qt related on PyCharm I get this >> issue: >> >> Some skeletons failed to generate: 19 modules failed in 1 interpreter. >> Details... >> >> Failed modules >> >> Python 3.4.2 >> PyQt4.QAxContainer >> PyQt4.Qsci >> PyQt4.QtCore >> PyQt4.QtDeclarative >> PyQt4.QtDesigner >> PyQt4.QtGui >> PyQt4.QtHelp >> PyQt4.QtMultimedia >> PyQt4.QtNetwork >> PyQt4.QtOpenGL >> PyQt4.QtScript >> PyQt4.QtScriptTools >> PyQt4.QtSql >> PyQt4.QtSvg >> PyQt4.QtTest >> PyQt4.QtWebKit >> PyQt4.QtXml >> PyQt4.QtXmlPatterns >> PyQt4.phonon >> >> Generation of skeletons for the modules above will be tried again when >> the modules are updated or a new version of generator is available. >> >> And PyCharm tells me that my 'import PyQt4.ANYTHING_HERE import *' has >> 'Unresolved references'. >> >> --- >> >> When I try to install the PyQt4 via the installer, in the default >> location (C:/Python34) I get an even 'worse' error, whenever PyCharm try to >> update the skeletons or something like that (that is, whenever I open a >> file there...), I get tons and tons of the same error, 'Error while >> accessing memory at address XXXX', and 'python.exe' stops working. >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ganesh1pal at gmail.com Sat Nov 1 09:05:44 2014 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Sat, 1 Nov 2014 18:35:44 +0530 Subject: Python Fabric on Windows : In-Reply-To: <544F7E5D.8070906@chamonix.reportlab.co.uk> References: <544F7E5D.8070906@chamonix.reportlab.co.uk> Message-ID: On Tue, Oct 28, 2014 at 5:00 PM, Robin Becker wrote: > > I found fabric on windows quite hard, but I have managed to use it. For > ssh I think I had to use the putty tools eg plink to do remote work. > > On the other hand I find plumbum much easier > > http://tomerfiliba.com/blog/Plumbum/ > > Thanks for pointing me to Plumbum , it looks nice but I will stick around with fabric for a while. It works beautifully on linux . I dont want to rewrite my linux scripts . -------------- next part -------------- An HTML attachment was scrubbed... URL: From peterirbizon at gmail.com Sat Nov 1 09:07:01 2014 From: peterirbizon at gmail.com (Peter Irbizon) Date: Sat, 1 Nov 2014 14:07:01 +0100 Subject: PYQT4 referer in javascript still blank Message-ID: Hello, I am trying to set referrer for my script this way in PYQT4: class NetworkManager(QNetworkAccessManager): def createRequest(self, op, req, outgoing_data): req.setRawHeader('Referer', 'http://www.my-university.com/') req.setRawHeader('Accept-Language', 'en') return super(NetworkManager, self).createRequest(op, req, outgoing_data) but when I use javascript document.write('js ref: ' + document.referrer +'
'); on my website it still returns empty line. When I use php $_SERVER["HTTP_REFERER"] it returns correct referer. How should I make it working for javascript as well? -------------- next part -------------- An HTML attachment was scrubbed... URL: From musicalhacksaw at yahoo.co.uk Sat Nov 1 10:17:28 2014 From: musicalhacksaw at yahoo.co.uk (Simon Evans) Date: Sat, 1 Nov 2014 07:17:28 -0700 (PDT) Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 Message-ID: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> Hi Programmers, I have downloaded, installed, and can access the LXMLTreeBuilder/lxml, from Python2.7. however I have also downloaded HTMLTreeBuilder/html5lib but cannot get console to recognize the download, even using the code the download site suggests. I did put it in the Python2.7 directory, but unlike the HTML one, it doesn't recognize it, so the import statement returns an error. Can anyone tell me how I might proceed so's these TreeBuilders/ Parsers will work on my Python console ? I also will have to install HTMLParserTreeBuilder/html.parser and LXMLTreeBuilderForXML/lxml but best to cross that bridge when gotten to, as they say. Thank you for reading.I look forward to hearing from you. Yours Simon Evans From fanhuhuai at gmail.com Sat Nov 1 11:01:12 2014 From: fanhuhuai at gmail.com (fanhuhuai at gmail.com) Date: Sat, 1 Nov 2014 08:01:12 -0700 (PDT) Subject: what can i do to improve my skill after finished python course on codecademy Message-ID: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> i will finish the python course on codecademy soon,i dont konw how to improve my skill and what can i do to use it ,some projects ? should i learn others course ? From d.corti at gmail.com Sat Nov 1 11:03:53 2014 From: d.corti at gmail.com (Dario) Date: Sat, 1 Nov 2014 08:03:53 -0700 (PDT) Subject: pySerial works in miniterm but not in my app In-Reply-To: References: <5cb7e219-cc34-4a4f-ae93-3a2bbfa9121a@googlegroups.com> <9f933554-ae04-4a3f-8317-0ed4f1e6d5b4@googlegroups.com> Message-ID: Il giorno venerd? 31 ottobre 2014 19:00:26 UTC+1, Dennis Lee Bieber ha scritto: > Didn't quite answer my question. If the comm line is using remote I understand your point, I didn't mention but I also tried sending one char at a time and listening at the same time, nothing changed. BUT.. plot twist: in Windows XP, the very same python code and usb adapter are working just right (python 2.7 and pySerial 2.7). Also with c#, no issues. So one could blame the usb adapter or its drivers, but the fact is that minicom (not miniterm) always works, while miniterm only works if used after minicom, and only the first time. I mean: I start minicom, it works. Close it (quit without reset), start miniterm, it works. Close miniterm, open it again, just garbage... From d.corti at gmail.com Sat Nov 1 11:30:43 2014 From: d.corti at gmail.com (Dario) Date: Sat, 1 Nov 2014 08:30:43 -0700 (PDT) Subject: pySerial works in miniterm but not in my app In-Reply-To: References: <5cb7e219-cc34-4a4f-ae93-3a2bbfa9121a@googlegroups.com> <9f933554-ae04-4a3f-8317-0ed4f1e6d5b4@googlegroups.com> Message-ID: <79aa71d6-853c-4171-9928-bb0dd5d311d3@googlegroups.com> Il giorno sabato 1 novembre 2014 16:04:06 UTC+1, Dario ha scritto: > BUT.. plot twist: in Windows XP, the very same python code and usb adapter are working just right (python 2.7 and pySerial 2.7). Also with c#, no issues. I compared the behaviour of mono and python (2.7 and 3.3) on the same hw and os, I guess something is wrong with pySerial implementation... Mono code on Mint: ---- SerialPort s = new SerialPort("/dev/ttyUSB0", 19200, Parity.None, 8, StopBits.One); s.Open(); s.Write("sw o01 +\r"); while (true) Console.Write(Convert.ToChar(s.ReadByte())); ---- Device reacts correctly and I get back what I expect (the first line is because I sent the command via com port, the second is because I pushed a button on the device): dario at ivymint ~ $ sudo ./Test1.exe sw o01 + Command OK Button 1 pushed Now equivalent Python 3.3 code on Mint: --- import serial s = serial.serial_for_url('/dev/ttyUSB0', 19200, bytesize = 8, parity = 'N', stopbits = 1) s.close() s.open() s.write(bytearray('sw o01 +\r','ascii')) while True: print(s.read()) --- In this case, I don't receive anything for my command, and when I press I receive garbage instead of "Button 1 pushed" dario at ivymint ~ $ sudo python3 ./test2.py b'\xfc' b'\x8f' b'\r' b'\x85' b'1' b'+' b'\xfe' From d.corti at gmail.com Sat Nov 1 11:57:31 2014 From: d.corti at gmail.com (Dario) Date: Sat, 1 Nov 2014 08:57:31 -0700 (PDT) Subject: pySerial works in miniterm but not in my app In-Reply-To: <79aa71d6-853c-4171-9928-bb0dd5d311d3@googlegroups.com> References: <5cb7e219-cc34-4a4f-ae93-3a2bbfa9121a@googlegroups.com> <9f933554-ae04-4a3f-8317-0ed4f1e6d5b4@googlegroups.com> <79aa71d6-853c-4171-9928-bb0dd5d311d3@googlegroups.com> Message-ID: <4fa10995-6943-432c-b5d6-72de6d4ddba4@googlegroups.com> Ehm sorry for the neverending spam, anyway I tried from my raspberry pi and it works there: root at pi:/home/pi# python3 ./test.py b's' b'w' b' ' b'o' b'0' b'1' b' ' b'+' b' ' b'C' b'o' b'm' b'm' b'a' b'n' b'd' b' ' b'O' b'K' b'\r' b'\n' Since I need it to work on the rpi and I was using Mint only for easiness, I'm ok with it :) Thanks. From news at blinne.net Sat Nov 1 12:30:14 2014 From: news at blinne.net (Alexander Blinne) Date: Sat, 01 Nov 2014 17:30:14 +0100 Subject: set environmental variable from python References: Message-ID: Am 31.10.2014 um 02:22 schrieb Artur Bercik: > I have to set environmental variable in my windows PC as follows: > > variable name: GISBASE > > value: C:\GRASS-64 > > Is it possible to set it from python? > > import sys > > sys.path.append("C:\\GRASS-64") > > But how to give variable name? I have to set both the variable name and > value. http://lmgtfy.com/?q=how+to+set+environment+variable+with+python From Seymore4Head at Hotmail.invalid Sat Nov 1 12:42:10 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sat, 01 Nov 2014 12:42:10 -0400 Subject: Classes References: <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> <20141031104319.02e1ca6f@rg.highlandtechnology.com> <2i585a5s6d1aagbh6ot2b88i51o8jhq0db@4ax.com> Message-ID: On Sat, 01 Nov 2014 12:00:46 -0400, Dennis Lee Bieber wrote: >On Fri, 31 Oct 2014 19:32:13 -0400, Seymore4Head > declaimed the following: > >> >>class Rectangle(object): >> def __init__(self, length, width=None): >> self.length = length >> if width is None: >> self.width = length >> else: >> self.width = width >> def area(self): >> return self.length * self.width >> def perimeter(self): >> return 2 * (self.length + self.width) >> >>class Square(Rectangle): >> def area(self): >> return self.length * self.width >> def perimeter(self): >> return 2 * (self.length + self.width) >> > Why did you redefine area and perimeter? Those are supposed to be >inherited operations from Rectangle. You've duplicated what should not have >been changed, and removed everything that makes a Square a Square. > > The "assignment" was to create a Square class that enforces the >property of "squareness" (length = width, or a simple "side"). > > What you created does not do that. > >>a=Rectangle(3,5) >>print (a.area()) >>print (a.perimeter()) >>b=Rectangle(5,7) >>print (b.area()) >>print (b.perimeter()) >>c=Square(4) >>print (c.area()) >>print (c.perimeter()) > > You're tests ignore the case of /changing/ side/length/width... >Consider what happens if you execute > >c.length = 5 >c.width = 9 > OK Maybe I misunderstood the question. My answer to you then is ......I don't know. I will have to think about it some more. From buzzard at invalid.invalid Sat Nov 1 12:56:37 2014 From: buzzard at invalid.invalid (duncan smith) Date: Sat, 01 Nov 2014 16:56:37 +0000 Subject: __index__ Message-ID: <545510c7$0$27750$862e30e2@ngroups.net> Hello, I have a Bloom filter class and want to (partially) serialize instances using hex() or oct(). Instances are mutable, so I can't inherit from long. I thought I'd found the answer when I came across __index__, https://docs.python.org/2/reference/datamodel.html#object.__index__. But it doesn't seem to work as I expected it to. >>> class MyClass(object): def __init__(self): self.val = 7 def __index__(self): return self.val >>> x = MyClass() >>> oct(x) Traceback (most recent call last): File "", line 1, in oct(x) TypeError: oct() argument can't be converted to oct >>> oct(x.__index__()) '07' >>> Can someone please explain why my thinking is wrong on this? TIA. Duncan From ned at nedbatchelder.com Sat Nov 1 13:11:25 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sat, 01 Nov 2014 13:11:25 -0400 Subject: __index__ In-Reply-To: <545510c7$0$27750$862e30e2@ngroups.net> References: <545510c7$0$27750$862e30e2@ngroups.net> Message-ID: On 11/1/14 12:56 PM, duncan smith wrote: > Hello, > I have a Bloom filter class and want to (partially) serialize > instances using hex() or oct(). Instances are mutable, so I can't > inherit from long. I thought I'd found the answer when I came across > __index__, > https://docs.python.org/2/reference/datamodel.html#object.__index__. But > it doesn't seem to work as I expected it to. > > >>>> class MyClass(object): > def __init__(self): > self.val = 7 > def __index__(self): > return self.val > > >>>> x = MyClass() >>>> oct(x) > > Traceback (most recent call last): > File "", line 1, in > oct(x) > TypeError: oct() argument can't be converted to oct >>>> oct(x.__index__()) > '07' >>>> > > > Can someone please explain why my thinking is wrong on this? TIA. Just above your link in the docs is __oct__ and __hex__, which are used to implement oct() and hex(): https://docs.python.org/2/reference/datamodel.html#object.__oct__ That said, I would simply add a .hex() method on the class. I would never expect a complex thing like a Bloom filter to be turned into useful hex with the hex() builtin. For example, when making an MD5 hash, you use the md5.hexdigest() method, not hex(md5). -- Ned Batchelder, http://nedbatchelder.com From buzzard at invalid.invalid Sat Nov 1 13:15:51 2014 From: buzzard at invalid.invalid (duncan smith) Date: Sat, 01 Nov 2014 17:15:51 +0000 Subject: __index__ In-Reply-To: <545510c7$0$27750$862e30e2@ngroups.net> References: <545510c7$0$27750$862e30e2@ngroups.net> Message-ID: <54551548$0$27691$862e30e2@ngroups.net> On 01/11/14 16:56, duncan smith wrote: [snip] Sorry, forgot to add that I'm using Python 2.7.6 on Ubuntu 14.04. Cheers. Duncan From ethan at stoneleaf.us Sat Nov 1 14:29:03 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Sat, 01 Nov 2014 11:29:03 -0700 Subject: __index__ In-Reply-To: References: <545510c7$0$27750$862e30e2@ngroups.net> Message-ID: <5455266F.8010307@stoneleaf.us> On 11/01/2014 10:11 AM, Ned Batchelder wrote: > On 11/1/14 12:56 PM, duncan smith wrote: >> >> I have a Bloom filter class and want to (partially) serialize >> instances using hex() or oct(). Instances are mutable, so I can't >> inherit from long. I thought I'd found the answer when I came across >> __index__, it doesn't seem to work as I expected it to. > > Just above your link in the docs is __oct__ and __hex__, which are used to implement oct() and hex(): > https://docs.python.org/2/reference/datamodel.html#object.__oct__ In Python 2 __oct__ and __hex__ are used for oct() and hex(), but in Python 3 __index__ is used. But I agree with Net that using a separate method is probably better. -- ~Ethan~ From chaselton at gmail.com Sat Nov 1 14:47:16 2014 From: chaselton at gmail.com (Cyd Haselton) Date: Sat, 1 Nov 2014 13:47:16 -0500 Subject: Build Question: How to Add -Wl, --option Before Objects In Setup.py? In-Reply-To: References: Message-ID: On Sat, Nov 1, 2014 at 5:52 AM, Ned Deily wrote: > In article > , > Cyd Haselton wrote: >> So, after trying various ways to add that flag before lpython in >> setup.py, I stripped all --allow-shlib-undefined >> --no-allow-shlib-undefined feom the Makefile, ran make clean, and >> make. >> >> I still get the following error: >> Modules/python.o \ >> -lc -ldl -lm -L. -lpython2.7 -lm >> ./libpython2.7.so: undefined reference to `sincos' >> collect2: error: ld returned 1 exit status >> make: *** [python] Error 1 > > I don't understand why you are seeing that problem *unless" you might be > running into this issue that I found by searching for "sincos Android": > > https://code.google.com/p/android/issues/detail?id=38423 > > That looks awfully suspicious. If it isn't that, I don't know what to > tell you. You could open an issue on the Python bug tracker > (bugs.python.org) but we don't officially support Android so I doubt > that will help much. If you haven't already, you might try asking on > some Android forums; I know other oddities of building things on Android > have been reported. > > Good luck! > > -- > Ned Deily, > nad at acm.org > > -- > https://mail.python.org/mailman/listinfo/python-list Hammer -> Head -> Nail. Sure enough, nm -D libm.so shows that sincos is NOT available in that library on my Android device. Now to figure out what to do about it. Nice find! Cyd From buzzard at invalid.invalid Sat Nov 1 15:41:33 2014 From: buzzard at invalid.invalid (duncan smith) Date: Sat, 01 Nov 2014 19:41:33 +0000 Subject: __index__ In-Reply-To: References: <545510c7$0$27750$862e30e2@ngroups.net> Message-ID: <5455376e$0$27681$862e30e2@ngroups.net> On 01/11/14 18:29, Ethan Furman wrote: > On 11/01/2014 10:11 AM, Ned Batchelder wrote: >> On 11/1/14 12:56 PM, duncan smith wrote: >>> >>> I have a Bloom filter class and want to (partially) serialize >>> instances using hex() or oct(). Instances are mutable, so I can't >>> inherit from long. I thought I'd found the answer when I came across >>> __index__, it doesn't seem to work as I expected it to. >> >> Just above your link in the docs is __oct__ and __hex__, which are >> used to implement oct() and hex(): >> https://docs.python.org/2/reference/datamodel.html#object.__oct__ > > In Python 2 __oct__ and __hex__ are used for oct() and hex(), but in > Python 3 __index__ is used. > It was the doc for hex at https://docs.python.org/2/library/functions.html that led me to think I needed to implement the _index__ method. The doc for bin and oct seems to be right (I need __index__ for bin, but it doesn't work for oct). > But I agree with Net that using a separate method is probably better. > > -- > ~Ethan~ Possibly, I'm still tinkering with it. I use the Bloom filters to generate, and act as pseudonyms for token sets. I have another class that represents pseudonyms (of a different kind, but still bit strings) that is derived from long - so hex etc. just work. I should probably (at least) subclass my Bloom filter class before adding the relevant methods. Cheers. Duncan From ethan at stoneleaf.us Sat Nov 1 16:00:20 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Sat, 01 Nov 2014 13:00:20 -0700 Subject: __index__ In-Reply-To: <5455266F.8010307@stoneleaf.us> References: <545510c7$0$27750$862e30e2@ngroups.net> <5455266F.8010307@stoneleaf.us> Message-ID: <54553BD4.5080202@stoneleaf.us> On 11/01/2014 11:29 AM, Ethan Furman wrote: > > But I agree with Net ... Oops, should have ben 'Ned' -- apologies! -- ~Ethan~ From chaselton at gmail.com Sat Nov 1 16:21:10 2014 From: chaselton at gmail.com (Cyd Haselton) Date: Sat, 1 Nov 2014 15:21:10 -0500 Subject: Build Question: How to Add -Wl, --option Before Objects In Setup.py? In-Reply-To: References: Message-ID: On Sat, Nov 1, 2014 at 1:47 PM, Cyd Haselton wrote: > On Sat, Nov 1, 2014 at 5:52 AM, Ned Deily wrote: >> In article >> , >> Cyd Haselton wrote: >>> So, after trying various ways to add that flag before lpython in >>> setup.py, I stripped all --allow-shlib-undefined >>> --no-allow-shlib-undefined feom the Makefile, ran make clean, and >>> make. >>> >>> I still get the following error: >>> Modules/python.o \ >>> -lc -ldl -lm -L. -lpython2.7 -lm >>> ./libpython2.7.so: undefined reference to `sincos' >>> collect2: error: ld returned 1 exit status >>> make: *** [python] Error 1 >> >> I don't understand why you are seeing that problem *unless" you might be >> running into this issue that I found by searching for "sincos Android": >> >> https://code.google.com/p/android/issues/detail?id=38423 >> >> That looks awfully suspicious. If it isn't that, I don't know what to >> tell you. You could open an issue on the Python bug tracker >> (bugs.python.org) but we don't officially support Android so I doubt >> that will help much. If you haven't already, you might try asking on >> some Android forums; I know other oddities of building things on Android >> have been reported. >> >> Good luck! >> >> -- >> Ned Deily, >> nad at acm.org >> >> -- >> https://mail.python.org/mailman/listinfo/python-list > > Hammer -> Head -> Nail. > > Sure enough, nm -D libm.so shows that sincos is NOT available in that > library on my Android device. Now to figure out what to do about it. > > Nice find! > > Cyd UPDATE: After doing a bit of research it looks like it would be easier to build Python without sincos...is that possible? If not, I'll need to figure out how to get bionic libm sources with a proper Makefile (instead of Android's build system) From tjreedy at udel.edu Sat Nov 1 16:43:02 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 01 Nov 2014 16:43:02 -0400 Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> Message-ID: On 11/1/2014 10:17 AM, Simon Evans wrote: > Hi Programmers, I have downloaded, installed, and can access the > LXMLTreeBuilder/lxml, from Python2.7. however I have also downloaded > HTMLTreeBuilder/html5lib but cannot get console to recognize the > download, even using the code the download site suggests. I did put > it in the Python2.7 directory, What OS are you using. Exactly where dod you put each lib? Are each of the two installs a single module or a package directory? If the latter, does the directory contain __init__.py > but unlike the HTML one, it doesn't > recognize it, so the import statement returns an error. There must be some difference. Look carefully. And please post the traceback. -- Terry Jan Reedy From real-not-anti-spam-address at apple-juice.co.uk Sat Nov 1 17:57:03 2014 From: real-not-anti-spam-address at apple-juice.co.uk (D.M. Procida) Date: Sat, 1 Nov 2014 21:57:03 +0000 Subject: Python Namibia 2015 Message-ID: <1lugcs4.1rtb5pf1epad7aN%real-not-anti-spam-address@apple-juice.co.uk> Python Namibia 2015 will be Namibia's first-ever Python conference. http://python-namibia.org We're building an interesting programme of talks and other activities, and we're seeking more. You can find more information about the kind of thing we're looking for, with a link to the proposal submission form, at: http://python-namibia.org/programme/ We'd like to have a wide range of perspectives represented - talks and activities aimed at an audience with a variety of different levels of expertise, and covering many different applications of Python. If you're not sure about how to frame your proposal, just drop me a line. Thanks! Daniele From alister.nospam.ware at ntlworld.com Sat Nov 1 18:01:54 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Sat, 01 Nov 2014 22:01:54 GMT Subject: what can i do to improve my skill after finished python course on codecademy References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> Message-ID: On Sat, 01 Nov 2014 08:01:12 -0700, fanhuhuai wrote: > i will finish the python course on codecademy soon,i dont konw how to > improve my skill and what can i do to use it ,some projects ? should i > learn others course ? find a task you need a solution too. are there any regular admin task you perform that could be automated? do you have any hobbies that could benefit from computerisation? genuine tasks are always better that those created purely to teach "Practicality beats purity" -- "The IETF motto is 'rouch consesus and running code'" -- Scott Bradner (Open Sources, 1999 O'Reilly and Associates) From rosuav at gmail.com Sat Nov 1 18:10:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 2 Nov 2014 09:10:36 +1100 Subject: what can i do to improve my skill after finished python course on codecademy In-Reply-To: References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> Message-ID: On Sun, Nov 2, 2014 at 9:01 AM, alister wrote: > find a task you need a solution too. > are there any regular admin task you perform that could be automated? > do you have any hobbies that could benefit from computerisation? > > genuine tasks are always better that those created purely to teach I agree, but also, pick something that's small and self-contained. Try to find a project that you can complete (to the point of usability) within a day, or at most a week, preferably within the space of a page or two of code. As an added advantage, you'll be able to ask for code review, here or somewhere else; you can learn a lot by writing your code first, and then having other programmers offer comments. (Note that I didn't say "better programmers" or even "more senior programmers". It's called "peer review" in some circles, because the point is that anyone can learn from anyone else.) ChrisA From nad at acm.org Sat Nov 1 18:25:12 2014 From: nad at acm.org (Ned Deily) Date: Sat, 01 Nov 2014 15:25:12 -0700 Subject: Build Question: How to Add -Wl, --option Before Objects In Setup.py? References: Message-ID: In article , Cyd Haselton wrote: > On Sat, Nov 1, 2014 at 1:47 PM, Cyd Haselton wrote: [...] > > Sure enough, nm -D libm.so shows that sincos is NOT available in that > > library on my Android device. Now to figure out what to do about it. [...] > UPDATE: After doing a bit of research it looks like it would be > easier to build Python without sincos...is that possible? > If not, I'll need to figure out how to get bionic libm sources with a > proper Makefile (instead of Android's build system) While sin() and/or cos() are primarily used in the expected places in the Python standard library (like the math module), sin() is also used in the implementation of type "complex" objects, code that is part of the core interpreter. I see that there is an old, undocumented, and unsupported macro to disable building of complex number support. But more hacking is needed to even get a somewhat working build with it these days and then, without complex support, many tests in the standard library fail and what you end up isn't really Python. So, I think rather than hacking up Python, you should try to fix the broken platform. There seem to be a number of project that claim to support Python on Android. Perhaps they could be of help. FWIW, the macro is "WITHOUT_COMPLEX": ./configure [...] CPPFLAGS='-DWITHOUT_COMPLEX' and Lib/optparse.py would need to be patched to comment out its use of "complex". Again, good luck! -- Ned Deily, nad at acm.org From nestorjb at gmail.com Sat Nov 1 19:22:18 2014 From: nestorjb at gmail.com (=?UTF-8?B?TsOpc3RvciBCb3Njw6Fu?=) Date: Sat, 1 Nov 2014 18:52:18 -0430 Subject: When using a decorator exceptions raised reference the decorator not the function In-Reply-To: References: Message-ID: So actually what I ended up doing was a function that will return the last tb_next and this will always give me the reference to the py and line number where the exception was raised. Regards, N?stor On Thu, Oct 30, 2014 at 4:42 PM, N?stor Bosc?n wrote: > Thanks Terry > > Yes both lines where in the traceback using tb_next I got what I needed. > > Regards, > > N?stor > > On Thu, Oct 30, 2014 at 1:36 PM, Terry Reedy wrote: > >> On 10/30/2014 8:33 AM, N?stor Bosc?n wrote: >> >> I'm using Python 2.7 and I'm creating a class decorator that extract >>> information from exceptions for logging purposes. >>> >>> Everytime an exception is raised from the original function and I >>> extract the origin of the exception with sys.exc_info() I get a >>> reference to the line in the decorator where the function is called, not >>> the line of the original function where the exception was raised. >>> >> >> I expect that both lines should be in the traceback. Post an example >> where you do not intercept the exception. >> >> -- >> Terry Jan Reedy >> >> >> -- >> https://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From invalid at invalid.invalid Sat Nov 1 20:31:23 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Sun, 2 Nov 2014 00:31:23 +0000 (UTC) Subject: what can i do to improve my skill after finished python course on codecademy References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> Message-ID: On 2014-11-01, alister wrote: "The IETF motto is 'rouch consesus and running code'" -- Scott Bradner (Open Sources, 1999 O'Reilly and Associates) I don't get it, and googling didn't help. What is "rouch" consensus? -- Grant From python at mrabarnett.plus.com Sat Nov 1 20:55:24 2014 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 02 Nov 2014 00:55:24 +0000 Subject: what can i do to improve my skill after finished python course on codecademy In-Reply-To: References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> Message-ID: <545580FC.2080403@mrabarnett.plus.com> On 2014-11-02 00:31, Grant Edwards wrote: > On 2014-11-01, alister wrote: > > "The IETF motto is 'rouch consesus and running code'" > > -- Scott Bradner (Open Sources, 1999 O'Reilly and Associates) > > I don't get it, and googling didn't help. What is "rouch" consensus? > I googled for: "Scott Bradner" "IETF motto" It gave me: The IETF motto is "rough consensus and running code." From rosuav at gmail.com Sat Nov 1 21:02:39 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 2 Nov 2014 12:02:39 +1100 Subject: what can i do to improve my skill after finished python course on codecademy In-Reply-To: References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> Message-ID: On Sun, Nov 2, 2014 at 11:31 AM, Grant Edwards wrote: > On 2014-11-01, alister wrote: > > "The IETF motto is 'rouch consesus and running code'" > > -- Scott Bradner (Open Sources, 1999 O'Reilly and Associates) > > I don't get it, and googling didn't help. What is "rouch" consensus? Presumably "rough consensus". As long as most people agree (as opposed to total consensus, where *everyone* agrees), and as long as the code can be made to run, perfection is a luxury hat the IETF doesn't strive for. It's a form of "practicality beats purity" as it applies to standards development. The joke may be that this is only approximately correct spelling, as well as only approximate consensus and approximately working code. Or that might just be a transcription error. ChrisA From annieford8 at gmail.com Sun Nov 2 01:37:35 2014 From: annieford8 at gmail.com (michel88) Date: Sat, 1 Nov 2014 22:37:35 -0700 (PDT) Subject: President Bush Meets Pope Before Heading to Paris In-Reply-To: <4d1becb5-3c8a-40f5-b14a-47430f56c891@w34g2000prm.googlegroups.com> References: <4d1becb5-3c8a-40f5-b14a-47430f56c891@w34g2000prm.googlegroups.com> Message-ID: <1414906655947-5076374.post@n6.nabble.com> Out of the list of US presidents , George Bush remains my least favorite. Even though people are saying that Obama is losing popularity over the war on terrorism and his approach to it, I still support him. -- View this message in context: http://python.6.x6.nabble.com/President-Bush-Meets-Pope-Before-Heading-to-Paris-tp1390014p5076374.html Sent from the Python - python-list mailing list archive at Nabble.com. From denismfmcmahon at gmail.com Sun Nov 2 04:50:37 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Sun, 2 Nov 2014 09:50:37 +0000 (UTC) Subject: Classes References: <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> <20141031104319.02e1ca6f@rg.highlandtechnology.com> <2i585a5s6d1aagbh6ot2b88i51o8jhq0db@4ax.com> Message-ID: On Sat, 01 Nov 2014 12:42:10 -0400, Seymore4Head wrote: > OK Maybe I misunderstood the question. > > My answer to you then is ......I don't know. I will have to think about > it some more. The question (I thought) was to write a class for Square that inherited a class Rectangle but imposed on it the additional constraints of a square over a rectangle, namely that length == width. To do this, you need to override the inherited methods to set length and width with new methods to set length and width as follows: when setting length, also set width equal to length. when setting width, also set length equal to width. For bonus points, if your constructor accepts width and length parameters (from the Rectangle constructor) then detect if they are different and raise a suitable error. from math import sqrt class SquareGeometryError(Exception): """The parameters create an illegal geometry for a square""" pass class Rectangle: def __init__(self,length,width): self.length=length self.width=width def area(self): return self.length*self.width def perimeter(self): return 2*self.length+2*self.width def diagonal(self): return sqrt(self.length*self.length+self.width*self.width) def get_width(self): return self.width def get_length(self): return self.length def set_width(self, width): self.width = width def set_length(self, length): self.length = length class Square(Rectangle): _def _init__(self, length, width): if not length == width: raise SquareGeometryError("Length must equal width") self.length = length # or width self.width = length # or width def set_width(self, width): self.length = width self.width = width def set_length(self, length): self.length = length self.width = length Note that to make my square, I only need to over-ride those rectangle methods which allow the setting of length and width to enforce squareness upon the square. All the other methods of rectangle will work equally well for the square. -- Denis McMahon, denismfmcmahon at gmail.com From timothy.c.delaney at gmail.com Sun Nov 2 05:32:13 2014 From: timothy.c.delaney at gmail.com (Tim Delaney) Date: Sun, 2 Nov 2014 21:32:13 +1100 Subject: Classes In-Reply-To: References: <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> <20141031104319.02e1ca6f@rg.highlandtechnology.com> <2i585a5s6d1aagbh6ot2b88i51o8jhq0db@4ax.com> Message-ID: On 2 November 2014 20:50, Denis McMahon wrote: > > The question (I thought) was to write a class for Square that inherited a > class Rectangle but imposed on it the additional constraints of a square > over a rectangle, namely that length == width. > I'm late to the party and this has already been partially addressed in the thread, but it always annoys me. A square is as much a rhombus with 90 degree angles as it is a rectangle with equal length and width, and yet I *never* see the former given as an option. If course, that's probably because rectangles have a multitude of uses for user interfaces, whilst other quadrilaterals are somewhat less useful. Tim Delaney -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg.ewing at canterbury.ac.nz Sun Nov 2 06:32:42 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 03 Nov 2014 00:32:42 +1300 Subject: Classes In-Reply-To: <54543231$0$13000$c3e8da3$5496439d@news.astraweb.com> References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <54543231$0$13000$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Like all good Pythonistas[1], we hate Java and think that getter/setter > methods are pointless. But come on, they're not *wrong*, What's wrong is the statement that getters and setters are necessary to allow the implementation to change without changing the interface. That's factually incorrect in regard to Python. -- Greg From denismfmcmahon at gmail.com Sun Nov 2 07:27:06 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Sun, 2 Nov 2014 12:27:06 +0000 (UTC) Subject: Classes References: <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> <20141031104319.02e1ca6f@rg.highlandtechnology.com> <2i585a5s6d1aagbh6ot2b88i51o8jhq0db@4ax.com> Message-ID: On Sun, 02 Nov 2014 21:32:13 +1100, Tim Delaney wrote: > On 2 November 2014 20:50, Denis McMahon > wrote: > >> The question (I thought) was to write a class for Square that inherited >> a class Rectangle but imposed on it the additional constraints of a >> square over a rectangle, namely that length == width. >> >> > I'm late to the party and this has already been partially addressed in > the thread, but it always annoys me. A square is as much a rhombus with > 90 degree angles as it is a rectangle with equal length and width, and > yet I *never* see the former given as an option. > > If course, that's probably because rectangles have a multitude of uses > for user interfaces, whilst other quadrilaterals are somewhat less > useful. And perhaps that also addresses the square - rectangle (or circle - ellipse) issue - square, rectangle and rhombus are all forms of quadrilateral, and perhaps should all inherit a base class Quadrilateral, rather than trying (and partially failing) to inherit each other. -- Denis McMahon, denismfmcmahon at gmail.com From chaselton at gmail.com Sun Nov 2 08:02:27 2014 From: chaselton at gmail.com (Cyd Haselton) Date: Sun, 2 Nov 2014 07:02:27 -0600 Subject: Build Question: How to Add -Wl, --option Before Objects In Setup.py? In-Reply-To: References: Message-ID: On Sat, Nov 1, 2014 at 5:25 PM, Ned Deily wrote: > In article > , > Cyd Haselton wrote: >> On Sat, Nov 1, 2014 at 1:47 PM, Cyd Haselton wrote: > [...] >> > Sure enough, nm -D libm.so shows that sincos is NOT available in that >> > library on my Android device. Now to figure out what to do about it. > [...] >> UPDATE: After doing a bit of research it looks like it would be >> easier to build Python without sincos...is that possible? >> If not, I'll need to figure out how to get bionic libm sources with a >> proper Makefile (instead of Android's build system) > > While sin() and/or cos() are primarily used in the expected places in > the Python standard library (like the math module), sin() is also used > in the implementation of type "complex" objects, code that is part of > the core interpreter. Just checking: is sincos() the same as sin() and cos()? Nm output for my toolchain's libm does show sin() and cos() just not sincos() > I see that there is an old, undocumented, and > unsupported macro to disable building of complex number support. But > more hacking is needed to even get a somewhat working build with it > these days and then, without complex support, many tests in the standard > library fail and what you end up isn't really Python. So, I think > rather than hacking up Python, you should try to fix the broken > platform. There seem to be a number of project that claim to support > Python on Android. Perhaps they could be of help. > *sigh* Well, I had planned on bootstrapping GCC 4.9.0...I guess I'll be doing it sooner rather than later. Interestingly enough, the toolchain sources at android.googlesource.com only have Python 2.7.5...perhaps the reason is related to this issue. If GCC supports building Python in the source tree, I'll try it with that version and report back. > FWIW, the macro is "WITHOUT_COMPLEX": > > ./configure [...] CPPFLAGS='-DWITHOUT_COMPLEX' > > and Lib/optparse.py would need to be patched to comment out its use of > "complex". > > Again, good luck! > And thanks again for all your help. I'll report back with results, if and when I have them. > -- > Ned Deily, > nad at acm.org > > -- > https://mail.python.org/mailman/listinfo/python-list From fanhuhuai at gmail.com Sun Nov 2 09:49:27 2014 From: fanhuhuai at gmail.com (Huhuai Fan) Date: Sun, 2 Nov 2014 06:49:27 -0800 (PST) Subject: what can i do to improve my skill after finished python course on codecademy In-Reply-To: References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> Message-ID: ? 2014?11?2????UTC+8??8?31?39??Grant Edwards??? > On 2014-11-01, alister wrote: > > "The IETF motto is 'rouch consesus and running code'" > > -- Scott Bradner (Open Sources, 1999 O'Reilly and Associates) > > I don't get it, and googling didn't help. What is "rouch" consensus? > > -- > Grant Thanks for your help, but i have no idea to find a project that i can complete,i am now in perplexed for what to do From musicalhacksaw at yahoo.co.uk Sun Nov 2 09:58:42 2014 From: musicalhacksaw at yahoo.co.uk (Simon Evans) Date: Sun, 2 Nov 2014 06:58:42 -0800 (PST) Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> Message-ID: <1f3c5d34-b5d1-4ede-952b-fed54b817fd7@googlegroups.com> Dear Terry Reedy I am using operating system Windows 7. I put the HTML TreeBuilder / htm5 library into the Python2.7 folder. I read that the LXML Treebuilder /lmxl installs itself automatically to the Python2.7 installation, so that is why I am not having difficulty with that installation. I don't think it really matters where the lxml download ended up necessarily, all I want is to know how I can install it so it works, I cannot get any feedback because it isn't working, all I get is the automated inbuilt response about 'Do I want a treebuilder/ parser that is appropriate to the input' or words to that effect. What I want to know is how to get this lxml treebuilder/parser to run, ie: what is the protocol for running the lxml download so's it'll run, or what sort of code to I put to my python console in order to get it to run, seeing as the input suggested by the download site does not get it to run. Maybe I should rephrase my question : how do I install LXMLTreeBuilder/lxml, and how do I download and install HTMLParserTreeBuilder and LXMLTreeBuilderForXML to my Python2.7, please ? I can post the Traceback but all it says is that it doesn't recognise any input with 'html5lib' in it. I will post the console response if it is important, but I can't see how it is relevant to my request - which is how do I get these 'treebuilder/ parsers' to install and run. From __peter__ at web.de Sun Nov 2 10:08:24 2014 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Nov 2014 16:08:24 +0100 Subject: what can i do to improve my skill after finished python course on codecademy References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> Message-ID: Huhuai Fan wrote: > Thanks for your help, but i have no idea to find a project that i can > complete,i am now in perplexed for what to do Then write a small text-based brainstorming app! From musicalhacksaw at yahoo.co.uk Sun Nov 2 10:23:41 2014 From: musicalhacksaw at yahoo.co.uk (Simon Evans) Date: Sun, 2 Nov 2014 07:23:41 -0800 (PST) Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> Message-ID: <4a7f3057-8244-4eb6-b656-309371102f98@googlegroups.com> I have proceeded to click on the 'setup.py' in the html5-0.999 lib and got a python console for a few seconds, this may have been the installation of the HTML5 parser/ treebuilder - I will have to put the code that did not work to it previously to it again, hopefully it will. From breamoreboy at yahoo.co.uk Sun Nov 2 10:27:00 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 02 Nov 2014 15:27:00 +0000 Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: <1f3c5d34-b5d1-4ede-952b-fed54b817fd7@googlegroups.com> References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> <1f3c5d34-b5d1-4ede-952b-fed54b817fd7@googlegroups.com> Message-ID: On 02/11/2014 14:58, Simon Evans wrote: > Dear Terry Reedy > I am using operating system Windows 7. > I put the HTML TreeBuilder / htm5 library into the Python2.7 folder. > I read that the LXML Treebuilder /lmxl installs itself automatically to the Python2.7 installation, so that is why I am not having difficulty with that installation. > I don't think it really matters where the lxml download ended up necessarily, all I want is to know how I can install it so it works, I cannot get any feedback because it isn't working, all I get is the automated inbuilt response about 'Do I want a treebuilder/ parser that is appropriate to the input' or words to that effect. What I want to know is how to get this lxml treebuilder/parser to run, ie: what is the protocol for running the lxml download so's it'll run, or what sort of code to I put to my python console in order to get it to run, seeing as the input suggested by the download site does not get it to run. Maybe I should rephrase my question : how do I install LXMLTreeBuilder/lxml, and how do I download and install HTMLParserTreeBuilder and LXMLTreeBuilderForXML to my Python2.7, > please ? I can post the Traceback but all it says is that it doesn't recognise any input with 'html5lib' in it. I will post the console response if it is important, but I can't see how it is relevan > t to my request - which is how do I get these 'treebuilder/ parsers' to install and run. > You're not the first person to have this problem, so do either of these help? http://stackoverflow.com/questions/17766725/how-to-re-install-lxml http://stackoverflow.com/questions/21322948/beautifulsoup-wont-recognize-lxml Also note that your post consists of single line paragraphs which makes it difficult to read. Can you change your email settings to correct this or if you're on google groups action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing them, thanks. -- 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 Sun Nov 2 10:30:52 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 02 Nov 2014 15:30:52 +0000 Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: <4a7f3057-8244-4eb6-b656-309371102f98@googlegroups.com> References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> <4a7f3057-8244-4eb6-b656-309371102f98@googlegroups.com> Message-ID: On 02/11/2014 15:23, Simon Evans wrote: > I have proceeded to click on the 'setup.py' in the html5-0.999 lib and got a python console for a few seconds, this may have been the installation of the HTML5 parser/ treebuilder - I will have to put the code that did not work to it previously to it again, hopefully it will. > Please post some context, we're not yet mind readers :) Can you use pip to do your installation, it's far easier than other mechanisms? -- 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 Sun Nov 2 12:16:11 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 2 Nov 2014 12:16:11 -0500 Subject: what can i do to improve my skill after finished python course on codecademy In-Reply-To: References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> Message-ID: On Sun, Nov 2, 2014 at 10:08 AM, Peter Otten <__peter__ at web.de> wrote: > Huhuai Fan wrote: > >> Thanks for your help, but i have no idea to find a project that i can >> complete,i am now in perplexed for what to do > > Then write a small text-based brainstorming app! > > -- > https://mail.python.org/mailman/listinfo/python-list If you like math puzzles you can do the euler project stuff -- Joel Goldstick http://joelgoldstick.com From abhi.darkness at gmail.com Sun Nov 2 12:21:11 2014 From: abhi.darkness at gmail.com (Abhiram) Date: Sun, 2 Nov 2014 22:51:11 +0530 Subject: what can i do to improve my skill after finished python course on codecademy In-Reply-To: References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> Message-ID: >> >> > > If you like math puzzles you can do the euler project stuff > > -- > Joel Goldstick > http://joelgoldstick.com > -- > https://mail.python.org/mailman/listinfo/python-list Ooh. I had to jump onboard to defend this. Project Euler is an absolute delight to do with Python :) You should totally give it a whirl. -Abhiram From invalid at invalid.invalid Sun Nov 2 12:30:23 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Sun, 2 Nov 2014 17:30:23 +0000 (UTC) Subject: what can i do to improve my skill after finished python course on codecademy References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> Message-ID: On 2014-11-02, Chris Angelico wrote: > On Sun, Nov 2, 2014 at 11:31 AM, Grant Edwards wrote: >> On 2014-11-01, alister wrote: >> >> "The IETF motto is 'rouch consesus and running code'" >> >> -- Scott Bradner (Open Sources, 1999 O'Reilly and Associates) >> >> I don't get it, and googling didn't help. What is "rouch" consensus? > > Presumably "rough consensus". [...] > The joke may be that this is only approximately correct spelling, I was wondering about that after I posted. I did find that misspelling in one or two e-mails in a mailing list archive, but it didn't really seem like it was being used as an in-joke. -- Grant From musicalhacksaw at yahoo.co.uk Sun Nov 2 12:51:15 2014 From: musicalhacksaw at yahoo.co.uk (Simon Evans) Date: Sun, 2 Nov 2014 09:51:15 -0800 (PST) Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> Message-ID: <15b4dae1-ba1a-43f0-9be1-f23a7e67a15b@googlegroups.com> Dear Mark Lawrence, I have tried inputting the code in the first link, re: >>> import lxml >>> import lxml.etree >>> import bs4.builder.htmlparser Traceback (most recent call last): File "", line 1, in ImportError: No module named htmlparser >>> import bs4.builder._lxml >>> import bs4.builder.html5lib Traceback (most recent call last): File "", line 1, in ImportError: No module named html5lib >>> which tells me lxml is installed, but that neither html nor html5 is installed. From Seymore4Head at Hotmail.invalid Sun Nov 2 14:10:40 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sun, 02 Nov 2014 14:10:40 -0500 Subject: what can i do to improve my skill after finished python course on codecademy References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> Message-ID: <4c0d5apoa3455vmkgdtp7nn25pl85fgmoh@4ax.com> On Sun, 2 Nov 2014 12:16:11 -0500, Joel Goldstick wrote: >On Sun, Nov 2, 2014 at 10:08 AM, Peter Otten <__peter__ at web.de> wrote: >> Huhuai Fan wrote: >> >>> Thanks for your help, but i have no idea to find a project that i can >>> complete,i am now in perplexed for what to do >> >> Then write a small text-based brainstorming app! >> >> -- >> https://mail.python.org/mailman/listinfo/python-list > >If you like math puzzles you can do the euler project stuff target=1000 thelist=[] thesum=0 for x in range (1,target): if x%3==0: thelist.append(x) if x%5==0 and x%3!=0: thelist.append(x) for x in thelist: thesum+=x print(thelist) print (thesum) From musicalhacksaw at yahoo.co.uk Sun Nov 2 14:22:53 2014 From: musicalhacksaw at yahoo.co.uk (Simon Evans) Date: Sun, 2 Nov 2014 11:22:53 -0800 (PST) Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> Message-ID: I have got the html5lib-0.999.tar.gz and the HTMLParser-0.0.2.tar.gz files in my Downloads the problem is how I install them to Python2.7. The lxml-3.3.3.win32-py2.7 is an exe file, which upon clicking will install but obviously the html and the html5 installations are not so straightforward. From breamoreboy at yahoo.co.uk Sun Nov 2 14:39:42 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 02 Nov 2014 19:39:42 +0000 Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> Message-ID: On 02/11/2014 19:22, Simon Evans wrote: > I have got the html5lib-0.999.tar.gz > > and the HTMLParser-0.0.2.tar.gz files in my Downloads the problem is how I > > install them to Python2.7. > > The lxml-3.3.3.win32-py2.7 is an exe file, which upon clicking will install > > but obviously the html and the html5 installations are not so > > straightforward. > For the second time will you please quote some context. Have you tried using pip as I've already suggested? -- 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 Sun Nov 2 14:42:49 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 02 Nov 2014 19:42:49 +0000 Subject: what can i do to improve my skill after finished python course on codecademy In-Reply-To: <4c0d5apoa3455vmkgdtp7nn25pl85fgmoh@4ax.com> References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> <4c0d5apoa3455vmkgdtp7nn25pl85fgmoh@4ax.com> Message-ID: On 02/11/2014 19:10, Seymore4Head wrote: > On Sun, 2 Nov 2014 12:16:11 -0500, Joel Goldstick > wrote: > >> On Sun, Nov 2, 2014 at 10:08 AM, Peter Otten <__peter__ at web.de> wrote: >>> Huhuai Fan wrote: >>> >>>> Thanks for your help, but i have no idea to find a project that i can >>>> complete,i am now in perplexed for what to do >>> >>> Then write a small text-based brainstorming app! >>> >>> -- >>> https://mail.python.org/mailman/listinfo/python-list >> >> If you like math puzzles you can do the euler project stuff > > target=1000 > thelist=[] > thesum=0 > for x in range (1,target): > if x%3==0: thelist.append(x) > if x%5==0 and x%3!=0: thelist.append(x) > for x in thelist: thesum+=x > print(thelist) > print (thesum) > In [1]: help(sum) Help on built-in function sum in module builtins: sum(...) sum(iterable[, start]) -> value Return the sum of an iterable of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). When the iterable is empty, return start. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From tjreedy at udel.edu Sun Nov 2 15:08:48 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 02 Nov 2014 15:08:48 -0500 Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: <1f3c5d34-b5d1-4ede-952b-fed54b817fd7@googlegroups.com> References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> <1f3c5d34-b5d1-4ede-952b-fed54b817fd7@googlegroups.com> Message-ID: On 11/2/2014 9:58 AM, Simon Evans wrote: > Dear Terry Reedy I am using operating system Windows 7. I put the > HTML TreeBuilder / htm5 library into the Python2.7 folder. Both packages should go in python27/Lib/site-packages, where a 'package' equals a directory with a __init__.py module. > I read > that the LXML Treebuilder /lmxl installs itself automatically to the > Python2.7 installation, so that is why I am not having difficulty > with that installation. I presume it put itself in site-packages, where it belongs. > I don't think it really matters where the > lxml download ended up necessarily, all I want is to know how I can > install it so it works, I cannot get any feedback because it isn't > working, all I get is the automated inbuilt response about 'Do I want > a treebuilder/ parser that is appropriate to the input' or words to > that effect. What I want to know is how to get this lxml > treebuilder/parser to run, ie: what is the protocol for running the > lxml download so's it'll run, or what sort of code to I put to my > python console in order to get it to run, seeing as the input > suggested by the download site does not get it to run. Maybe I > should rephrase my question : how do I install LXMLTreeBuilder/lxml, > and how do I download and install HTMLParserTreeBuilder and > LXMLTreeBuilderForXML to my Python2.7, please ? > I can post the > Traceback but all it says is that it doesn't recognise any input with > 'html5lib' in it. I will post the console response if it is > important, but I can't see how it is relevan t to my request - which > is how do I get these 'treebuilder/ parsers' to install and run. Why do newbies like you fight so hard against cutting and pasting a trackback? -- Terry Jan Reedy From ned at nedbatchelder.com Sun Nov 2 15:43:16 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sun, 02 Nov 2014 15:43:16 -0500 Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> <1f3c5d34-b5d1-4ede-952b-fed54b817fd7@googlegroups.com> Message-ID: On 11/2/14 3:08 PM, Terry Reedy wrote: > > I can post the >> Traceback but all it says is that it doesn't recognise any input with >> 'html5lib' in it. I will post the console response if it is >> important, but I can't see how it is relevan t to my request - which >> is how do I get these 'treebuilder/ parsers' to install and run. > > Why do newbies like you fight so hard against cutting and pasting a > trackback? Simon, I'm sure Terry didn't mean that to come out as stern as it sounds. Providing the actual error reports may not seem important, but you'd be surprised the kinds of clues that lurk there. -- Ned Batchelder, http://nedbatchelder.com From Seymore4Head at Hotmail.invalid Sun Nov 2 15:45:44 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sun, 02 Nov 2014 15:45:44 -0500 Subject: what can i do to improve my skill after finished python course on codecademy References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> <4c0d5apoa3455vmkgdtp7nn25pl85fgmoh@4ax.com> Message-ID: <2e4d5apn4k8vql5m4il1nra46ldd5p8e6l@4ax.com> On Sun, 02 Nov 2014 19:42:49 +0000, Mark Lawrence wrote: >On 02/11/2014 19:10, Seymore4Head wrote: >> On Sun, 2 Nov 2014 12:16:11 -0500, Joel Goldstick >> wrote: >> >>> On Sun, Nov 2, 2014 at 10:08 AM, Peter Otten <__peter__ at web.de> wrote: >>>> Huhuai Fan wrote: >>>> >>>>> Thanks for your help, but i have no idea to find a project that i can >>>>> complete,i am now in perplexed for what to do >>>> >>>> Then write a small text-based brainstorming app! >>>> >>>> -- >>>> https://mail.python.org/mailman/listinfo/python-list >>> >>> If you like math puzzles you can do the euler project stuff >> >> target=1000 >> thelist=[] >> thesum=0 >> for x in range (1,target): >> if x%3==0: thelist.append(x) >> if x%5==0 and x%3!=0: thelist.append(x) >> for x in thelist: thesum+=x >> print(thelist) >> print (thesum) >> > >In [1]: help(sum) >Help on built-in function sum in module builtins: > >sum(...) > sum(iterable[, start]) -> value > > Return the sum of an iterable of numbers (NOT strings) plus the value > of parameter 'start' (which defaults to 0). When the iterable is > empty, return start. Thanks From Seymore4Head at Hotmail.invalid Sun Nov 2 16:03:16 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sun, 02 Nov 2014 16:03:16 -0500 Subject: what can i do to improve my skill after finished python course on codecademy References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> <4c0d5apoa3455vmkgdtp7nn25pl85fgmoh@4ax.com> Message-ID: On Sun, 02 Nov 2014 19:42:49 +0000, Mark Lawrence wrote: >On 02/11/2014 19:10, Seymore4Head wrote: >> On Sun, 2 Nov 2014 12:16:11 -0500, Joel Goldstick >> wrote: >> >>> On Sun, Nov 2, 2014 at 10:08 AM, Peter Otten <__peter__ at web.de> wrote: >>>> Huhuai Fan wrote: >>>> >>>>> Thanks for your help, but i have no idea to find a project that i can >>>>> complete,i am now in perplexed for what to do >>>> >>>> Then write a small text-based brainstorming app! >>>> >>>> -- >>>> https://mail.python.org/mailman/listinfo/python-list >>> >>> If you like math puzzles you can do the euler project stuff >> >> target=1000 >> thelist=[] >> thesum=0 >> for x in range (1,target): >> if x%3==0: thelist.append(x) >> if x%5==0 and x%3!=0: thelist.append(x) >> for x in thelist: thesum+=x >> print(thelist) >> print (thesum) >> > >In [1]: help(sum) >Help on built-in function sum in module builtins: > >sum(...) > sum(iterable[, start]) -> value > > Return the sum of an iterable of numbers (NOT strings) plus the value > of parameter 'start' (which defaults to 0). When the iterable is > empty, return start. BTW I have the answer to question 2, but there is no way I would run the code on numbers much more than 100000 and it wants the answer for 4,000,000. From nad at acm.org Sun Nov 2 16:38:22 2014 From: nad at acm.org (Ned Deily) Date: Sun, 02 Nov 2014 13:38:22 -0800 Subject: Build Question: How to Add -Wl, --option Before Objects In Setup.py? References: Message-ID: In article , Cyd Haselton wrote: > Just checking: is sincos() the same as sin() and cos()? Nm output for > my toolchain's libm does show sin() and cos() just not sincos() See, this is what you get when you ask for free help: bad info. sincos isn't the same, as a little of googling informs me. But, as the thread starting here indicates: https://sourceware.org/ml/binutils/2010-04/msg00219.html gcc can do an optimization that turns a pair of sin() and cos() calls with the same arguments into a single call to sincos(). And there is such a pair in Python's complexobject.c. As the thread explains, there are some platforms where sin() and cos() are implemented but not sincos(). As suggested in the thread, one approach is to give options to gcc to avoid the optimizations: CFLAGS='-fno-builtin-sin -fno-builtin-cos' That does seem to result in a libpython with no references to sincos. -- Ned Deily, nad at acm.org From musicalhacksaw at yahoo.co.uk Sun Nov 2 16:59:25 2014 From: musicalhacksaw at yahoo.co.uk (Simon Evans) Date: Sun, 2 Nov 2014 13:59:25 -0800 (PST) Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> Message-ID: <75794999-f188-470a-96d1-3d8fca80cbf7@googlegroups.com> Oh I don't mind quoting console output, I just thought I'd be sparing you unnecessary detail. output was going nicely as I input text from my 'Getting Started with Beautiful Soup' even when the author reckoned things would go wrong - due to lxml not being installed, things went right, because I had already installed it, re: ---------------------------------------------------------------------------- page 17 ---------------------------------------------------------------------------- Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import urllib2 >>> from bs4 import BeautifulSoup >>> url = "http://www.packtpub.com/books" >>> page = urllib2.urlopen(url) >>> soup_packtpage = BeautifulSoup(page) >>> with open("foo.html","r") as foo_file: ... soup_foo = Soup(foo_file) File "", line 2 soup_foo = Soup(foo_file) ^ IndentationError: expected an indented block >>> soup_foo= BeautifulSoup("foo.html") ---------------------------------------------------------------------------- page 18 ---------------------------------------------------------------------------- >>> print(soup_foo)

foo.html

>>> soup_url = BeautifulSoup("http://www.packtpub.com/books") >>> print(soup_url)

http://www.packtpub.com/books

>>> helloworld = "

Hello World

" >>> soup_string = BeautifulSoup(helloworld) >>> print(soup_string)

Hello World

---------------------------------------------------------------------------- page 19: no code in text on this page ---------------------------------------------------------------------------- page 20 ---------------------------------------------------------------------------- >>> soup_xml = BeautifulSoup(helloworld,features= "xml") >>> soup_xml = BeautifulSoup(helloworld,"xml") >>> print(soup_xml)

Hello World

>>> soup_xml = BeautifulSoup(helloworld,features = "xml") >>> print(soup_xml)

Hello World

>>> ---------------------------------------------------------------------------- Then on bottom of page 20 it says 'we should install the required parsers using easy-install,pip or setup.py install' but as I can't get the downloads of html or html5 parsers, text code halfway down returns statutory response regarding requisite parser needing to be installed, re: ---------------------------------------------------------------------------- page 21 ---------------------------------------------------------------------------- >>> invalid_html = '>> soup_invalid_html = BeautifulSoup(invalid_html,'lxml') >>> print(soup_invalid_html) >>> soup_invalid_html = BeautifulSoup(invalid_html,'html5lib') Traceback (most recent call last): File "", line 1, in File "C:\Python27\lib\site-packages\bs4\__init__.py", line 155, in __init__ % ",".join(features)) ValueError: Couldn't find a tree builder with the features you requested: html5lib. Do you need to install a parser library? >>> From joel.goldstick at gmail.com Sun Nov 2 17:00:53 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 2 Nov 2014 17:00:53 -0500 Subject: what can i do to improve my skill after finished python course on codecademy In-Reply-To: References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> <4c0d5apoa3455vmkgdtp7nn25pl85fgmoh@4ax.com> Message-ID: On Sun, Nov 2, 2014 at 4:03 PM, Seymore4Head wrote: > On Sun, 02 Nov 2014 19:42:49 +0000, Mark Lawrence > wrote: > >>On 02/11/2014 19:10, Seymore4Head wrote: >>> On Sun, 2 Nov 2014 12:16:11 -0500, Joel Goldstick >>> wrote: >>> >>>> On Sun, Nov 2, 2014 at 10:08 AM, Peter Otten <__peter__ at web.de> wrote: >>>>> Huhuai Fan wrote: >>>>> >>>>>> Thanks for your help, but i have no idea to find a project that i can >>>>>> complete,i am now in perplexed for what to do >>>>> >>>>> Then write a small text-based brainstorming app! >>>>> >>>>> -- >>>>> https://mail.python.org/mailman/listinfo/python-list >>>> >>>> If you like math puzzles you can do the euler project stuff >>> >>> target=1000 >>> thelist=[] >>> thesum=0 >>> for x in range (1,target): >>> if x%3==0: thelist.append(x) >>> if x%5==0 and x%3!=0: thelist.append(x) >>> for x in thelist: thesum+=x >>> print(thelist) >>> print (thesum) >>> >> >>In [1]: help(sum) >>Help on built-in function sum in module builtins: >> >>sum(...) >> sum(iterable[, start]) -> value >> >> Return the sum of an iterable of numbers (NOT strings) plus the value >> of parameter 'start' (which defaults to 0). When the iterable is >> empty, return start. > > BTW I have the answer to question 2, but there is no way I would run > the code on numbers much more than 100000 and it wants the answer for > 4,000,000. > > -- > https://mail.python.org/mailman/listinfo/python-list Seymore, please don't hijack a thread. Start a new one -- Joel Goldstick http://joelgoldstick.com From orgnut at yahoo.com Sun Nov 2 17:03:19 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Sun, 02 Nov 2014 14:03:19 -0800 Subject: Classes In-Reply-To: References: <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> <20141031104319.02e1ca6f@rg.highlandtechnology.com> <2i585a5s6d1aagbh6ot2b88i51o8jhq0db@4ax.com> Message-ID: On 11/02/2014 01:50 AM, Denis McMahon wrote: [snip] > from math import sqrt > > class SquareGeometryError(Exception): > """The parameters create an illegal geometry for a square""" > pass > > class Rectangle: > > def __init__(self,length,width): > self.length=length > self.width=width > > def area(self): > return self.length*self.width > > def perimeter(self): > return 2*self.length+2*self.width > > def diagonal(self): > return sqrt(self.length*self.length+self.width*self.width) > > def get_width(self): > return self.width > > def get_length(self): > return self.length > > def set_width(self, width): > self.width = width > > def set_length(self, length): > self.length = length > > class Square(Rectangle): > > _def _init__(self, length, width): > if not length == width: > raise SquareGeometryError("Length must equal width") > self.length = length # or width > self.width = length # or width > > def set_width(self, width): > self.length = width > self.width = width > > def set_length(self, length): > self.length = length > self.width = length > > Note that to make my square, I only need to over-ride those rectangle > methods which allow the setting of length and width to enforce squareness > upon the square. All the other methods of rectangle will work equally > well for the square. > Why do you want to instantiate a Square with two parameters? You only need one -- side. I agree that since you are inheriting from Rectangle you need to keep the length and width attributes to allow the get/set of length/width, so you do need to override the Rectangle set methods. Consider this version: # ------ --------- class Square(Rectangle): def __init__(self, side): self.set_side(side) def get_side(self): return self.length # or width def set_side(self, side): self.length = self.width = side def set_width(self, width): self.set_side(width) def set_length(self, length): self.set_side(length) # ------ -------- This also eliminates the need for your exception. Of course, it still allows someone to directly change either the length or width -- but since "we are all consenting adults here", anyone who does this should know the consequences. ;-) -=- Larry -=- From davea at davea.name Sun Nov 2 17:07:34 2014 From: davea at davea.name (Dave Angel) Date: Sun, 02 Nov 2014 17:07:34 -0500 Subject: what can i do to improve my skill after finished python course on codecademy In-Reply-To: References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> <4c0d5apoa3455vmkgdtp7nn25pl85fgmoh@4ax.com> Message-ID: <5456AB26.4060503@davea.name> On 11/02/2014 04:03 PM, Seymore4Head wrote: > On Sun, 02 Nov 2014 19:42:49 +0000, Mark Lawrence > wrote: > >> On 02/11/2014 19:10, Seymore4Head wrote: >>> On Sun, 2 Nov 2014 12:16:11 -0500, Joel Goldstick >>> wrote: >>> >>>> On Sun, Nov 2, 2014 at 10:08 AM, Peter Otten <__peter__ at web.de> wrote: >>>>> Huhuai Fan wrote: >>>>> >>>>>> Thanks for your help, but i have no idea to find a project that i can >>>>>> complete,i am now in perplexed for what to do >>>>> >>>>> Then write a small text-based brainstorming app! >>>>> >>>>> -- >>>>> https://mail.python.org/mailman/listinfo/python-list >>>> >>>> If you like math puzzles you can do the euler project stuff >>> >>> target=1000 >>> thelist=[] >>> thesum=0 >>> for x in range (1,target): >>> if x%3==0: thelist.append(x) >>> if x%5==0 and x%3!=0: thelist.append(x) >>> for x in thelist: thesum+=x >>> print(thelist) >>> print (thesum) >>> >> >> In [1]: help(sum) >> Help on built-in function sum in module builtins: >> >> sum(...) >> sum(iterable[, start]) -> value >> >> Return the sum of an iterable of numbers (NOT strings) plus the value >> of parameter 'start' (which defaults to 0). When the iterable is >> empty, return start. > > BTW I have the answer to question 2, but there is no way I would run > the code on numbers much more than 100000 and it wants the answer for > 4,000,000. > So that's teaching you that there must be a more elegant approach than brute-force. Sometimes you can use cleverer programming, sometimes you need cleverer math. Sometimes both. As a trivial example, suppose you're asked to sum the numbers from 1000 to 10**25 Brute force would take a few millenia, as something like ans = sum(range( BIG ) - sum(range(1000)) But just knowing the math lets you simplify it to something like ans = (1000 + BIG) * (BIG - 1000) / 2 (give or take a few plus/minus ones) -- DaveA From rosuav at gmail.com Sun Nov 2 17:12:56 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 3 Nov 2014 09:12:56 +1100 Subject: what can i do to improve my skill after finished python course on codecademy In-Reply-To: <5456AB26.4060503@davea.name> References: <957d3844-9b9a-47b7-892f-b7660aa40d88@googlegroups.com> <4c0d5apoa3455vmkgdtp7nn25pl85fgmoh@4ax.com> <5456AB26.4060503@davea.name> Message-ID: On Mon, Nov 3, 2014 at 9:07 AM, Dave Angel wrote: > Brute force would take a few millenia, as something like > ans = sum(range( BIG ) - sum(range(1000)) > > But just knowing the math lets you simplify it to something like > ans = (1000 + BIG) * (BIG - 1000) / 2 Suggestion: Master the brute-force approach first, and use that (on small ranges) to verify the simplified version. And if you already happen to know the sum of all numbers from 1 to 100, say, then you can test both approaches against that, to be sure they're right. ChrisA From musicalhacksaw at yahoo.co.uk Sun Nov 2 17:20:44 2014 From: musicalhacksaw at yahoo.co.uk (Simon Evans) Date: Sun, 2 Nov 2014 14:20:44 -0800 (PST) Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> Message-ID: What I meant to say was I can't get the html5 or the html parsers to install, I have got their downloads in their respective directories in the downloads directory. From breamoreboy at yahoo.co.uk Sun Nov 2 17:31:48 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 02 Nov 2014 22:31:48 +0000 Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: <75794999-f188-470a-96d1-3d8fca80cbf7@googlegroups.com> References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> <75794999-f188-470a-96d1-3d8fca80cbf7@googlegroups.com> Message-ID: On 02/11/2014 21:59, Simon Evans wrote: > > Oh I don't mind quoting console output, I just thought I'd be sparing you > > unnecessary detail. > > output was going nicely as I input text from my 'Getting Started with > > Beautiful Soup' even when the author reckoned things would go wrong - due to > > lxml not being installed, things went right, because I had already installed > > it, re: > ---------------------------------------------------------------------------- > page 17 > ---------------------------------------------------------------------------- > Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win > 32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import urllib2 >>>> from bs4 import BeautifulSoup >>>> url = "http://www.packtpub.com/books" >>>> page = urllib2.urlopen(url) >>>> soup_packtpage = BeautifulSoup(page) >>>> with open("foo.html","r") as foo_file: > ... soup_foo = Soup(foo_file) > File "", line 2 > soup_foo = Soup(foo_file) > ^ > IndentationError: expected an indented block >>>> soup_foo= BeautifulSoup("foo.html") > ---------------------------------------------------------------------------- > page 18 > ---------------------------------------------------------------------------- >>>> print(soup_foo) >

foo.html

>>>> soup_url = BeautifulSoup("http://www.packtpub.com/books") >>>> print(soup_url) >

http://www.packtpub.com/books

>>>> helloworld = "

Hello World

" >>>> soup_string = BeautifulSoup(helloworld) >>>> print(soup_string) >

Hello World

> ---------------------------------------------------------------------------- > page 19: no code in text on this page > ---------------------------------------------------------------------------- > page 20 > ---------------------------------------------------------------------------- >>>> soup_xml = BeautifulSoup(helloworld,features= "xml") >>>> soup_xml = BeautifulSoup(helloworld,"xml") >>>> print(soup_xml) > >

Hello World

>>>> soup_xml = BeautifulSoup(helloworld,features = "xml") >>>> print(soup_xml) > >

Hello World

>>>> > ---------------------------------------------------------------------------- > Then on bottom of page 20 it says 'we should install the required parsers using easy-install,pip or setup.py install' but as I can't get the downloads of html or html5 parsers, text code halfway down returns statutory response regarding requisite parser needing to be installed, re: > ---------------------------------------------------------------------------- > page 21 > ---------------------------------------------------------------------------- >>>> invalid_html = '>>> soup_invalid_html = BeautifulSoup(invalid_html,'lxml') >>>> print(soup_invalid_html) > >>>> soup_invalid_html = BeautifulSoup(invalid_html,'html5lib') > Traceback (most recent call last): > File "", line 1, in > File "C:\Python27\lib\site-packages\bs4\__init__.py", line 155, in __init__ > % ",".join(features)) > ValueError: Couldn't find a tree builder with the features you requested: html5lib. Do you need to install a parser library? >>>> Have you tried this from the command prompt? pip install html5lib And please do something about the extra newlines and single lined paragraphs above, there's no need for it all. -- 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 Sun Nov 2 17:34:18 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 02 Nov 2014 22:34:18 +0000 Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> Message-ID: On 02/11/2014 22:20, Simon Evans wrote: > What I meant to say was I can't get the html5 or the html parsers to install, I have got their downloads in their respective directories in the downloads directory. > For the third time of asking will you please provide some context. For the fourth time have you tried from the command prompt:- pip install html5lib ??? For (at least) the third time will you please do something about one line paragraphs. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From rosuav at gmail.com Sun Nov 2 18:33:14 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 3 Nov 2014 10:33:14 +1100 Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: <75794999-f188-470a-96d1-3d8fca80cbf7@googlegroups.com> References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> <75794999-f188-470a-96d1-3d8fca80cbf7@googlegroups.com> Message-ID: On Mon, Nov 3, 2014 at 8:59 AM, Simon Evans wrote: > Oh I don't mind quoting console output, I just thought I'd be sparing you > unnecessary detail. One of the tricks experienced programmers learn is how to skim a pile of output for what's important. When that output is a Python traceback, I would guess that most of python-list has some experience with reading them; regular responders like Ned, Terry, and Mark, in all probability, have read more tracebacks than I've drunk hot chocolates [1], so when they ask you to post a traceback, you can be confident that they can cope with the level of detail :) ChrisA From denismfmcmahon at gmail.com Sun Nov 2 22:12:32 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Mon, 3 Nov 2014 03:12:32 +0000 (UTC) Subject: Classes References: <20141031104319.02e1ca6f@rg.highlandtechnology.com> <2i585a5s6d1aagbh6ot2b88i51o8jhq0db@4ax.com> Message-ID: On Sun, 02 Nov 2014 11:31:12 -0500, Dennis Lee Bieber wrote: > On Sun, 2 Nov 2014 12:27:06 +0000 (UTC), Denis McMahon > declaimed the following: > >>On Sun, 02 Nov 2014 21:32:13 +1100, Tim Delaney wrote: >>> If course, that's probably because rectangles have a multitude of uses >>> for user interfaces, whilst other quadrilaterals are somewhat less >>> useful. >> >>And perhaps that also addresses the square - rectangle (or circle - >>ellipse) issue - square, rectangle and rhombus are all forms of >>quadrilateral, and perhaps should all inherit a base class >>Quadrilateral, >>rather than trying (and partially failing) to inherit each other. > > I'd class them as parallelograms -- as they differ from a trapezoid in > that opposite faces are parallel... Not to mention "arrow heads" where > two adjacent sides actually bend inwards. So: Quadrilateral Parallelogram Square Rectangle Rhombus Diamond (4 sides eq) Trapezoid Arrowhead Is an arrowhead a trapezoid? -- Denis McMahon, denismfmcmahon at gmail.com From dan at tombstonezero.net Mon Nov 3 01:29:39 2014 From: dan at tombstonezero.net (Dan Sommers) Date: Mon, 3 Nov 2014 06:29:39 +0000 (UTC) Subject: Classes References: <20141031104319.02e1ca6f@rg.highlandtechnology.com> <2i585a5s6d1aagbh6ot2b88i51o8jhq0db@4ax.com> Message-ID: On Mon, 03 Nov 2014 03:12:32 +0000, Denis McMahon wrote: > Quadrilateral > Parallelogram > Square > Rectangle > Rhombus > Diamond (4 sides eq) > Trapezoid > Arrowhead What's the difference between a Diamond and a Rhombus? > Is an arrowhead a trapezoid? No. From antoon.pardon at rece.vub.ac.be Mon Nov 3 06:04:48 2014 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Mon, 03 Nov 2014 12:04:48 +0100 Subject: Dictionaries with variable default. Message-ID: <54576150.6090002@rece.vub.ac.be> Is it possible to have a default dictionary where the default is dependant on the key? I was hoping something like this might work: >>> m = defaultdict(lambda key: key+1) But it obviously doesn't: >>> m[3] Traceback (most recent call last): File "", line 1, in TypeError: () takes exactly 1 argument (0 given) -- Antoon Pardon From rosuav at gmail.com Mon Nov 3 06:09:57 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 3 Nov 2014 22:09:57 +1100 Subject: Dictionaries with variable default. In-Reply-To: <54576150.6090002@rece.vub.ac.be> References: <54576150.6090002@rece.vub.ac.be> Message-ID: On Mon, Nov 3, 2014 at 10:04 PM, Antoon Pardon wrote: > Is it possible to have a default dictionary where the default is dependant > on the key? > > I was hoping something like this might work: >>>> m = defaultdict(lambda key: key+1) > > But it obviously doesn't: >>>> m[3] > > Traceback (most recent call last): > File "", line 1, in > TypeError: () takes exactly 1 argument (0 given) Yes, but not with the defaultdict. Instead, just implement __missing__: class KeyPlusOne(dict): def __missing__(self, key): return key+1 ChrisA From jeanmichel at sequans.com Mon Nov 3 07:41:41 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 3 Nov 2014 13:41:41 +0100 (CET) Subject: Classes In-Reply-To: Message-ID: <910361298.2515286.1415018501753.JavaMail.root@sequans.com> ----- Original Message ----- > From: "Gregory Ewing" > Steven D'Aprano wrote: > > Like all good Pythonistas[1], we hate Java and think that > > getter/setter > > methods are pointless. But come on, they're not *wrong*, > > What's wrong is the statement that getters and setters > are necessary to allow the implementation to change > without changing the interface. That's factually > incorrect in regard to Python. > > -- > Greg I'm not sure that is what the course was stating: "The advantage of following this practice is that the implementer of the class definition (often someone other than the user of the class) may restructure the organization of the data fields associated with the object while avoiding the need to rewrite code that uses the class." I agree with Steven on that one, while getters/setters are not the preferred way, they are not utterly wrong. Python uses the descriptor protocol which is basically getters and setters. It's is just hidden by a strange decorator syntax. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From joseph.smeng at gmail.com Mon Nov 3 08:53:24 2014 From: joseph.smeng at gmail.com (Joseph Shen) Date: Mon, 3 Nov 2014 05:53:24 -0800 (PST) Subject: support for boost::python for build double object Message-ID: In the boost::python library there is a function >>> boost::python::long_ and this function return a boost::python::object variable I'm trying to wrap a double variale but I can't find something just like >> boost::python::double_ can someone help me to build a double object PS. I know there are some functions in pure python c api like >> PyFloat_FromDouble and after create the object I can wrap it in boost::python::object but all I want is same api from boost::python library I can't find what I want tanks. From skip.montanaro at gmail.com Mon Nov 3 09:10:21 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Mon, 3 Nov 2014 08:10:21 -0600 Subject: support for boost::python for build double object In-Reply-To: References: Message-ID: On Mon, Nov 3, 2014 at 7:53 AM, Joseph Shen wrote: > In the boost::python library there is a function > > >>> boost::python::long_ > > and this function return a boost::python::object variable > > I'm trying to wrap a double variable but I can't find > something just like > > >> boost::python::double_ > > can someone help me to build a double object > Is there a boost::python::float_ function? If so, does it produce a 32-bit (C float) or 64-bit (C double) number? Skip -------------- next part -------------- An HTML attachment was scrubbed... URL: From joseph.smeng at gmail.com Mon Nov 3 09:39:25 2014 From: joseph.smeng at gmail.com (Joseph Shen) Date: Mon, 3 Nov 2014 06:39:25 -0800 (PST) Subject: support for boost::python for build double object In-Reply-To: References: Message-ID: On Monday, November 3, 2014 10:11:01 PM UTC+8, Skip Montanaro wrote: > On Mon, Nov 3, 2014 at 7:53 AM, Joseph Shen wrote: > > In the boost::python library there is a function > > > > >>> boost::python::long_ > > > > and this function return a boost::python::object variable > > > > I'm trying to wrap a double variable but I can't find > > something just like > > > > >>? boost::python::double_ > > > > can someone help me to build a double object > Is there a boost::python::float_ function? If so, does it produce a 32-bit (C float) or 64-bit (C double) number? > > > Skip thanks for reply, no there is no such function like float_ or double_ or float32_ etc. I'm reading the boost source code right now to find something wish me good luck From ian.g.kelly at gmail.com Mon Nov 3 09:47:47 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 3 Nov 2014 07:47:47 -0700 Subject: Classes In-Reply-To: References: <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> <20141031104319.02e1ca6f@rg.highlandtechnology.com> <2i585a5s6d1aagbh6ot2b88i51o8jhq0db@4ax.com> Message-ID: On Nov 2, 2014 5:31 AM, "Denis McMahon" wrote: > And perhaps that also addresses the square - rectangle (or circle - > ellipse) issue - square, rectangle and rhombus are all forms of > quadrilateral, and perhaps should all inherit a base class Quadrilateral, > rather than trying (and partially failing) to inherit each other. No, it doesn't matter whether you have square inheriting from rectangle, rhombus or quadrilateral. If the base class has mutator methods, you're still going to have this problem when they allow the object to be mutated in ways that violate the restrictions of the subclass. -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Nov 3 10:02:41 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 03 Nov 2014 15:02:41 +0000 Subject: support for boost::python for build double object In-Reply-To: References: Message-ID: On 03/11/2014 13:53, Joseph Shen wrote: > In the boost::python library there is a function > >>>> boost::python::long_ > > and this function return a boost::python::object variable > > I'm trying to wrap a double variale but I can't find > something just like > >>> boost::python::double_ > > can someone help me to build a double object > > PS. > I know there are some functions in pure python c api like > >>> PyFloat_FromDouble > > and after create the object I can wrap it in boost::python::object > > but all I want is same api from boost::python library > > I can't find what I want > > tanks. > I'm sorry that I can't help directly but try here https://mail.python.org/mailman/listinfo/cplusplus-sig which is also available as gmane.comp.python.c++ -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From rosuav at gmail.com Mon Nov 3 10:34:30 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Nov 2014 02:34:30 +1100 Subject: Classes In-Reply-To: <1r1f5ahd8qjh8fk5a3dpjgo75s7ejf7064@4ax.com> References: <2i585a5s6d1aagbh6ot2b88i51o8jhq0db@4ax.com> <1r1f5ahd8qjh8fk5a3dpjgo75s7ejf7064@4ax.com> Message-ID: On Tue, Nov 4, 2014 at 12:50 AM, Dennis Lee Bieber wrote: > On Mon, 3 Nov 2014 03:12:32 +0000 (UTC), Denis McMahon > declaimed the following: > >>So: >> >>Quadrilateral >> Parallelogram >> Square >> Rectangle >> Rhombus >> Diamond (4 sides eq) >> Trapezoid >> Arrowhead >> >>Is an arrowhead a trapezoid? > > I'd probably indent square under rectangle, and indent diamond where it > is -- both being restrictions on rectangle/rhombus > > But we may need another category, convex and concave; the arrowhead > would fall into the concave grouping. That's fine if you're creating a taxonomical hierarchy of immutables, but neither works if you're creating a mutable class hierarchy that follows LSP. The only way you can make any of this work (as someone suggested earlier, I believe) is by having __new__ potentially return a subclass, so if you ask Parallelogram to give you one with all sides equal and all angles equal, it gives you back a Square. But since a square is a special form of rhombus as well as a special form of rectangle, you'd have to use multiple inheritance or an AST-style subclass hook to verify. Of course, if you're going down that route, you probably want to take this up a level and have a Shape class, and have the subclass hook simply check if it's four-sided as well. ChrisA From musicalhacksaw at yahoo.co.uk Mon Nov 3 11:27:41 2014 From: musicalhacksaw at yahoo.co.uk (Simon Evans) Date: Mon, 3 Nov 2014 08:27:41 -0800 (PST) Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> Message-ID: <20d86ab1-dfe0-46c6-a5fe-065392766e10@googlegroups.com> I input 'pip install html5lib' to the Python 2.7 console and got : >>> pip install html5lib File "", line 1 pip install html5lib ^ SyntaxError: invalid syntax >>> I am not sure what you mean about 'single line paragraphs'. I put my text into double line spacing in my last missive, I left the code input/ output in single line spacing as that is how it reads from the console, after all who am I to alter it? Regarding 'context' if you are referring to the text I am using, it is from 'Getting Started in Beautiful Soup' by Vineeth G. Nair. For what its worth some of the subsequent code in the book runs, but not all, and I think this may be due to the parser installation factor, and I wanted to work through the book (112 pages) without any errors being returned. From rosuav at gmail.com Mon Nov 3 11:41:28 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Nov 2014 03:41:28 +1100 Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: <20d86ab1-dfe0-46c6-a5fe-065392766e10@googlegroups.com> References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> <20d86ab1-dfe0-46c6-a5fe-065392766e10@googlegroups.com> Message-ID: On Tue, Nov 4, 2014 at 3:27 AM, Simon Evans wrote: > I input 'pip install html5lib' to the Python 2.7 console and got : > >>>> pip install html5lib > File "", line 1 > pip install html5lib > ^ > SyntaxError: invalid syntax >>>> This should be run from your command interpreter - cmd.exe, bash, or whatever you normally run programs from. > I am not sure what you mean about 'single line paragraphs'. I put my text > > into double line spacing in my last missive, I left the code input/ output > > in single line spacing as that is how it reads from the console, after all > > who am I to alter it? Regarding 'context' if you are referring to the text > > I am using, it is from 'Getting Started in Beautiful Soup' by Vineeth G. > > Nair. Why the double line spacing? I don't get that... and I think that's what was meant. "Context" in this context means quoted text from previous posts. http://en.wikipedia.org/wiki/Posting_style#Interleaved_style The parts with the angle brackets at the beginning are quoted text, providing context for what you're saying. ChrisA From anuragpatibandla7 at gmail.com Mon Nov 3 12:57:15 2014 From: anuragpatibandla7 at gmail.com (Anurag Patibandla) Date: Mon, 3 Nov 2014 09:57:15 -0800 (PST) Subject: Parsing Python dictionary with multiple objects In-Reply-To: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: <024ff5ca-b0b7-4b03-b45c-1d9edb2aedce@googlegroups.com> json_split = {} value = {"Status": "Submitted", "m_Controller": "Python"} a = range(31) del a[0] for i in a: json_split[i] = value keys = json_split.keys() order = list(keys) q1 = int(round(len(keys)*0.2)) q2 = int(round(len(keys)*0.3)) q3 = int(round(len(keys)*0.5)) b = [q1,q2,q3] n=0 threedicts = [] for i in b: queues = order[n:n+i] n = n+i lists = [(queues[j], json_split.get(queues[j])) for j in range(len(queues))] onedict = {} for q in queues: onedict[q] = json_split[q] threedicts.append (onedict) queue1, queue2, queue3 = threedicts keys1 = queue1.keys() for i in keys1: queue1[i]['Priority'] = ['1'] keys2 = queue2.keys() for j in keys2: queue2[j]['Priority'] = ['2'] keys3 = queue3.keys() for z in keys3: queue3[z]['Priority'] = ['3'] I am trying to add a key value pair of ("Priority":"1") to queue1, ("Priority":"2") to queue2, and ("Priority":"3") to queue3. When I just add ("Priority":"1") to queue1, it works. But when I run the above code, ("Priority":"3") is being added to all the queues. This looks trivial and I don't understand why this is happening. Is there something wrong with what I am doing? From musicalhacksaw at yahoo.co.uk Mon Nov 3 16:28:20 2014 From: musicalhacksaw at yahoo.co.uk (Simon Evans) Date: Mon, 3 Nov 2014 13:28:20 -0800 (PST) Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> Message-ID: <12867b6e-ede8-4136-a1f9-48d922ab4335@googlegroups.com> I input to the cmd console 'pip install html5lib' but again got an error return. I thought one of the participants was unhappy about single line spacing (re: single line paragraphs') Okay I will go back to single line spacing, I don't think it is all that important, really. Anyway this is my console's response:- Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\Intel Atom>pip install html5lib 'pip' is not recognized as an internal or external command, operable program or batch file. C:\Users\Intel Atom> From breamoreboy at yahoo.co.uk Mon Nov 3 16:42:31 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 03 Nov 2014 21:42:31 +0000 Subject: Installing Parsers/Tree Builders to, and accessing these packages from Python2.7 In-Reply-To: <12867b6e-ede8-4136-a1f9-48d922ab4335@googlegroups.com> References: <9580043d-a75b-4b87-9a21-1b9c0347671f@googlegroups.com> <12867b6e-ede8-4136-a1f9-48d922ab4335@googlegroups.com> Message-ID: On 03/11/2014 21:28, Simon Evans wrote: > I input to the cmd console 'pip install html5lib' but again got an error return. I thought one of the participants was unhappy about single line spacing (re: single line paragraphs') Okay I will go back to single line spacing, I don't think it is all that important, really. Thank you for being so inconsiderate. Yet another single line paragraph that stretches out well over the horizon. Add that to the potential for double line spacing and all we end up with is a right mess. You've also replied without any context again. > Anyway this is my console's response:- > > > Microsoft Windows [Version 6.1.7601] > Copyright (c) 2009 Microsoft Corporation. All rights reserved. > > C:\Users\Intel Atom>pip install html5lib > 'pip' is not recognized as an internal or external command, > operable program or batch file. > > C:\Users\Intel Atom> > > Either you haven't installed pip (it comes with the Python 3.4 installer) or it's not on your path. In my installation I've pip.exe, pip3.4.exe and pip3.exe in C:\Python34\Scripts so what have you in your equivalent and what is your path set to? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From greg.ewing at canterbury.ac.nz Mon Nov 3 17:04:11 2014 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Tue, 04 Nov 2014 11:04:11 +1300 Subject: Classes In-Reply-To: <910361298.2515286.1415018501753.JavaMail.root@sequans.com> References: <910361298.2515286.1415018501753.JavaMail.root@sequans.com> Message-ID: <5457FBDB.9020500@canterbury.ac.nz> Jean-Michel Pichavant wrote: > I agree with Steven on that one, while getters/setters are not the preferred > way, they are not utterly wrong. I'm not saying that they're wrong in general, only that they're wrong for *Python*. This matters, because the course in question is purportedly teaching Python. To make a blanket statement like that in a Python course, without pointing out that it applies *only* to some languages *other* than Python, is grossly misleading. Now it may be that the quotation is taken out of context, and the instructor did in fact point this out, but the way the paragraph is worded, it sounds like it's just been blindly lifted from some Java or C++ book. -- Greg From albert at spenarnc.xs4all.nl Mon Nov 3 19:46:06 2014 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 04 Nov 2014 00:46:06 GMT Subject: (-1)**1000 References: <54476a77$0$21664$426a74cc@news.free.fr> <5447786d$0$12750$426a74cc@news.free.fr> Message-ID: <545821ce$0$15860$e4fe514c@dreader35.news.xs4all.nl> In article , Ned Batchelder wrote: >On 10/22/14 5:27 AM, ast wrote: >> >> "Chris Angelico" a ??crit dans le message de >> news:mailman.15058.1413968065.18130.python-list at python.org... >>> On Wed, Oct 22, 2014 at 7:27 PM, ast wrote: >>>> If i am writing (-1)**1000 on a python program, will the >>>> interpreter do (-1)*(-1)*...*(-1) or something clever ? >>>> >>>> In fact i have (-1)**N with N an integer potentially big. >>> >>> Exponentiation is far more efficient than the naive implementation of >>> iterated multiplication. >> >> In the very particular case of (-1)**N, I belive that Python check >> the odd or even parity of N and provides the result accordingly. >> >> I tried: >>>>> (-1)**1000000000000000000000000000000000 >> 1 >>>>> (-1)**1000000000000000000000000000000001 >> -1 >> >> and it is instantaneous >> >> > >Keep in mind that actually calculating the exponentiation wouldn't do >1000000000000000000000000000000000 multiplications anyway: the clever >way to do integer powers is by squaring based on the binary >representation of the exponent. It's explained here: >http://stackoverflow.com/a/101613/14343 > >So even if Python is actually calculating the value, it's only doing 75 >multiplications or so. I'm pretty sure that if we replace -1 by 2 , it never gets at its 75-th multiplication. > >-- >Ned Batchelder, http://nedbatchelder.com > Groetjes Albert -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From denismfmcmahon at gmail.com Mon Nov 3 20:10:21 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 4 Nov 2014 01:10:21 +0000 (UTC) Subject: Classes References: <20141031104319.02e1ca6f@rg.highlandtechnology.com> <2i585a5s6d1aagbh6ot2b88i51o8jhq0db@4ax.com> Message-ID: On Mon, 03 Nov 2014 06:29:39 +0000, Dan Sommers wrote: > On Mon, 03 Nov 2014 03:12:32 +0000, Denis McMahon wrote: > >> Quadrilateral >> Parallelogram >> Square Rectangle Rhombus Diamond (4 sides eq) >> Trapezoid >> Arrowhead > > What's the difference between a Diamond and a Rhombus? Oops, I was thinking a rhombus was a general parallelogram, my mistake. -- Denis McMahon, denismfmcmahon at gmail.com From greg.ewing at canterbury.ac.nz Tue Nov 4 00:30:33 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 04 Nov 2014 18:30:33 +1300 Subject: Classes In-Reply-To: References: <20141031104319.02e1ca6f@rg.highlandtechnology.com> <2i585a5s6d1aagbh6ot2b88i51o8jhq0db@4ax.com> Message-ID: Denis McMahon wrote: > On Mon, 03 Nov 2014 06:29:39 +0000, Dan Sommers wrote: > >>What's the difference between a Diamond and a Rhombus? > > Oops, I was thinking a rhombus was a general parallelogram, my mistake. Some diamonds are neither rhombuses nor parallelograms: http://minecraft.gamepedia.com/Diamond More a sort of irregular hexagon... -- Greg From greg.ewing at canterbury.ac.nz Tue Nov 4 00:38:36 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 04 Nov 2014 18:38:36 +1300 Subject: Classes In-Reply-To: References: Message-ID: Jean-Michel Pichavant wrote: > Python uses the descriptor protocol which is > basically getters and setters. It's is just hidden by a strange decorator > syntax. This is about the interface, not the implementation. "Getters and setters" in this context means designing the API of your class to have things like getFoo() and setFoo() in it. That's not just totally unnecessary in Python, it's counterproductive. It makes the API tedious to use for no benefit. -- Greg From vek.m1234 at gmail.com Tue Nov 4 04:52:52 2014 From: vek.m1234 at gmail.com (Veek M) Date: Tue, 04 Nov 2014 16:22:52 +0630 Subject: Python extension using a C library with one 'hello' function Message-ID: https://github.com/Veek/Python/tree/master/junk/hello doesn't work. I have: hello.c which contains: int hello(void); hello.h To wrap that up, i have: hello.py -> _hello (c extension) -> pyhello.c -> method py_hello() People using this will do: python3.2>> import hello python3.2>> hello.hello() It doesn't compile/work. deathstar> python setup.py build_ext --inplace running build_ext building '_hello' extension creating build creating build/temp.linux-x86_64-3.2 gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes - D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=4 -Wformat - Werror=format-security -fPIC -I/usr/include/python3.2mu -c pyhello.c -o build/temp.linux-x86_64-3.2/pyhello.o pyhello.c:15:6: warning: character constant too long for its type [enabled by default] pyhello.c:15:5: warning: initialization makes pointer from integer without a cast [enabled by default] pyhello.c:15:5: warning: (near initialization for 'hellomethods[0].ml_name') [enabled by default] pyhello.c:15:5: warning: initialization from incompatible pointer type [enabled by default] pyhello.c:15:5: warning: (near initialization for 'hellomethods[0].ml_meth') [enabled by default] pyhello.c:15:5: warning: initialization makes integer from pointer without a cast [enabled by default] pyhello.c:15:5: warning: (near initialization for 'hellomethods[0].ml_flags') [enabled by default] gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-x86_64-3.2/pyhello.o -o /root/github/junk/hello/_hello.cpython-32mu.so >>> import hello Traceback (most recent call last): File "", line 1, in File "hello.py", line 1, in from _hello import * ImportError: ./_hello.cpython-32mu.so: undefined symbol: hello >>> From mfthguven at gmail.com Tue Nov 4 06:29:20 2014 From: mfthguven at gmail.com (=?ISO-8859-1?Q?Fatih_G=FCven?=) Date: Tue, 4 Nov 2014 03:29:20 -0800 (PST) Subject: generating unique variable name via loops Message-ID: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> Hi, I want to generate a unique variable name for list using python. list1=... list2=... . . . listx=... where x is a number. You can remember it from saving a file in a directory. If you have already created a "new file", save dialog sugget that <<"new file " is already exist, do you want to save it as "new file (1)"?>> so I want to apply it for list names. Do you any idea about this. From rustompmody at gmail.com Tue Nov 4 07:43:59 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 4 Nov 2014 04:43:59 -0800 (PST) Subject: Idle on Mac issues Message-ID: <90cc9fbb-3c11-4e2b-bad2-5ee7fe51a7bc@googlegroups.com> I seem to be stuck with some issues of Idle on macs. The page https://www.python.org/download/mac/tcltk seems to talk only of Tcl/Tk versions 8.5 Macports seem to have at 8.6 https://www.macports.org/ports.php?by=library&substr=tcl With a direct download of Tcl/Tk there are some security warnings that prevent it from installing. Using whatever Tcl/Tk comes with python means many things dont work: - The options menu wont open - Various keyboard shortcuts dont work Any suggestions/directions? [Me: A non Mac-er with Mac-ers in my class!] From mfthguven at gmail.com Tue Nov 4 07:48:06 2014 From: mfthguven at gmail.com (=?ISO-8859-1?Q?Fatih_G=FCven?=) Date: Tue, 4 Nov 2014 04:48:06 -0800 (PST) Subject: generating unique variable name via loops In-Reply-To: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> References: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> Message-ID: <8df0b347-0569-4505-95f8-12baf44a1743@googlegroups.com> 4 Kas?m 2014 Sal? 13:29:34 UTC+2 tarihinde Fatih G?ven yazd?: Editted: Grammar revision. > Hi, > > I want to generate a unique variable name for list using python. > > list1=... > list2=... > . > . > . > listx=... where x is a number. > > You can remember it from saving a file in a directory. If you have already created a "new file", save dialog suggest that <<"new file " is already exist, do you want to save it as "new file (1)"?>> so I want to apply it for list names. > > Do you have any idea about this. From __peter__ at web.de Tue Nov 4 08:09:42 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Nov 2014 14:09:42 +0100 Subject: generating unique variable name via loops References: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> Message-ID: Fatih G?ven wrote: > I want to generate a unique variable name for list using python. > > list1=... > list2=... > . > . > . > listx=... where x is a number. > > You can remember it from saving a file in a directory. If you have already > created a "new file", save dialog sugget that <<"new file " is already > exist, do you want to save it as "new file (1)"?>> so I want to apply it > for list names. > > Do you any idea about this. Do you really want to use list1, list2, list3, ... as variable names? You shouldn't. Instead use a dict or a list of lists: >>> list_of_lists = [] >>> list_of_lists.append([1, 2, 3]) >>> list_of_lists.append(["a", "b", "c"]) >>> list_of_lists.append(["foo", "bar", "baz"]) You can then access the second list with >>> letters = list_of_lists[1] >>> print(letters) ['a', 'b', 'c'] On the other hand if you just want to generate names an easy to understand approach is to increment a global variable every time you invoke the name- generating function: >>> _index = 1 >>> def next_name(): ... global _index ... name = "list{}".format(_index) ... _index += 1 ... return name ... >>> next_name() 'list1' >>> next_name() 'list2' >>> next_name() 'list3' From anddamNOPSAM+gruppi at brapi.net Tue Nov 4 08:15:59 2014 From: anddamNOPSAM+gruppi at brapi.net (Andrea D'Amore) Date: Tue, 4 Nov 2014 14:15:59 +0100 Subject: Idle on Mac issues References: <90cc9fbb-3c11-4e2b-bad2-5ee7fe51a7bc@googlegroups.com> Message-ID: On 2014-11-04 12:43:59 +0000, Rustom Mody said: > I seem to be stuck with some issues of Idle on macs. > The page https://www.python.org/download/mac/tcltk > seems to talk only of Tcl/Tk versions 8.5 System's 8.5 should be enough, if not there's explicit mention of the ActiveTcl distribution. > Macports seem to have at 8.6 > https://www.macports.org/ports.php?by=library&substr=tcl But that won't likely be used by a binary python installation, unless you're using python from MacPorts as well. > Using whatever Tcl/Tk comes with python means many things dont work: > - The options menu wont open > - Various keyboard shortcuts dont work > Any suggestions/directions? > [Me: A non Mac-er with Mac-ers in my class!] I'm on 10.10 (happily) running MacPorts, I have system's python 2.7.6 as well as 2.7.8 and 3.4.2 from MacPorts, these two built with Xquartz support. I can start the idle binary provided by all of those, the system's with native GUI, and have working Options menu in all of them. I'd suggest the people having issue to describe their issues here, with details on the system version, python version, the exact command they run and the error they get. -- Andrea -------------- next part -------------- An HTML attachment was scrubbed... URL: From vek.m1234 at gmail.com Tue Nov 4 07:19:14 2014 From: vek.m1234 at gmail.com (Veek M) Date: Tue, 04 Nov 2014 18:49:14 +0630 Subject: generating unique variable name via loops References: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> <8df0b347-0569-4505-95f8-12baf44a1743@googlegroups.com> Message-ID: Fatih G?ven wrote: > 4 Kas?m 2014 Sal? 13:29:34 UTC+2 tarihinde Fatih G?ven yazd?: >> I want to generate a unique variable name for list using python. >> >> list1=... >> list2=... for x in range(1,10): exec("list%d = []" % x) From antoon.pardon at rece.vub.ac.be Tue Nov 4 08:21:30 2014 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Tue, 04 Nov 2014 14:21:30 +0100 Subject: Dictionaries with variable default. In-Reply-To: References: <54576150.6090002@rece.vub.ac.be> Message-ID: <5458D2DA.5050903@rece.vub.ac.be> Op 03-11-14 om 12:09 schreef Chris Angelico: > On Mon, Nov 3, 2014 at 10:04 PM, Antoon Pardon > wrote: >> Is it possible to have a default dictionary where the default is dependant >> on the key? >> >> I was hoping something like this might work: >>>>> m = defaultdict(lambda key: key+1) >> But it obviously doesn't: >>>>> m[3] >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: () takes exactly 1 argument (0 given) > Yes, but not with the defaultdict. Instead, just implement __missing__: > > class KeyPlusOne(dict): > def __missing__(self, key): return key+1 > > ChrisA So How should I call this: class ...dict(dict): def __init__(self, fun): self.fun = fun def __missing__(self, key): return self.fun(key) From __peter__ at web.de Tue Nov 4 08:37:31 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Nov 2014 14:37:31 +0100 Subject: generating unique variable name via loops References: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> <8df0b347-0569-4505-95f8-12baf44a1743@googlegroups.com> Message-ID: Veek M wrote: > Fatih G?ven wrote: > >> 4 Kas?m 2014 Sal? 13:29:34 UTC+2 tarihinde Fatih G?ven yazd?: >>> I want to generate a unique variable name for list using python. >>> >>> list1=... >>> list2=... > > for x in range(1,10): > exec("list%d = []" % x) Why would you do this? From mfthguven at gmail.com Tue Nov 4 08:45:04 2014 From: mfthguven at gmail.com (=?ISO-8859-1?Q?Fatih_G=FCven?=) Date: Tue, 4 Nov 2014 05:45:04 -0800 (PST) Subject: generating unique variable name via loops In-Reply-To: References: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> <8df0b347-0569-4505-95f8-12baf44a1743@googlegroups.com> Message-ID: <95028c6b-b6d2-40ec-9cc7-557cc9e42342@googlegroups.com> 4 Kas?m 2014 Sal? 15:19:20 UTC+2 tarihinde Veek M yazd?: > Fatih G?ven wrote: > > > 4 Kas?m 2014 Sal? 13:29:34 UTC+2 tarihinde Fatih G?ven yazd?: > >> I want to generate a unique variable name for list using python. > >> > >> list1=... > >> list2=... > > for x in range(1,10): > exec("list%d = []" % x) This is okay but i can't use the method ".append" for example list1.append("abc") From vek.m1234 at gmail.com Tue Nov 4 07:50:17 2014 From: vek.m1234 at gmail.com (Veek M) Date: Tue, 04 Nov 2014 19:20:17 +0630 Subject: generating unique variable name via loops References: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> <8df0b347-0569-4505-95f8-12baf44a1743@googlegroups.com> <95028c6b-b6d2-40ec-9cc7-557cc9e42342@googlegroups.com> Message-ID: Fatih G?ven wrote: > This is okay but i can't use the method ".append" for example > list1.append("abc") works for me From mfthguven at gmail.com Tue Nov 4 08:53:04 2014 From: mfthguven at gmail.com (=?ISO-8859-1?Q?Fatih_G=FCven?=) Date: Tue, 4 Nov 2014 05:53:04 -0800 (PST) Subject: generating unique variable name via loops In-Reply-To: References: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> <8df0b347-0569-4505-95f8-12baf44a1743@googlegroups.com> Message-ID: 4 Kas?m 2014 Sal? 15:37:59 UTC+2 tarihinde Peter Otten yazd?: > Veek M wrote: > > > Fatih G?ven wrote: > > > >> 4 Kas?m 2014 Sal? 13:29:34 UTC+2 tarihinde Fatih G?ven yazd?: > >>> I want to generate a unique variable name for list using python. > >>> > >>> list1=... > >>> list2=... > > > > for x in range(1,10): > > exec("list%d = []" % x) > > Why would you do this? I have a structured and repetitive data. I want to read a .txt file line by line and classified it to call easily. For example employee1 has a name, a salary, shift, age etc. and employee2 and other 101 employee have all of it. Call employee1.name or employee2.salary and assign it to a new variable, something etc. From cousinstanley at gmail.com Tue Nov 4 09:13:54 2014 From: cousinstanley at gmail.com (Cousin Stanley) Date: Tue, 04 Nov 2014 07:13:54 -0700 Subject: Dictionaries with variable default. References: <54576150.6090002@rece.vub.ac.be> Message-ID: > So How should I call this: > > class ...dict(dict): > def __init__(self, fun): > self.fun = fun > > def __missing__(self, key): > return self.fun(key) I don't know how you should, but I tried the following which seems to work .... class KeyPlusOne( dict ) : def __missing__( self , key ) : return ( 2 * key ) + 1 kp1 = KeyPlusOne() d = { } for n in range( 11 ) : d[ n ] = kp1[ n ] print '\n key : value \n' for key , value in d.iteritems() : print ' %2d : %2d' % ( key , value ) -- Stanley C. Kitching Human Being Phoenix, Arizona From nomail at invalid.com Tue Nov 4 09:16:32 2014 From: nomail at invalid.com (ast) Date: Tue, 4 Nov 2014 15:16:32 +0100 Subject: fill, expand from tkinter.pack() layout manager Message-ID: <5458dfc6$0$27505$426a74cc@news.free.fr> Hi I dont really understood how "fill" and "expand" works with layout manager tkinter.pack() Example: from tkinter import * root = Tk() w = Label(root, text="Red", bg="red", fg="white") w.pack(side=LEFT, fill = BOTH) Here is the result: http://cjoint.com/?0Kepj1E3Tv3 Why is the label "w" only extended vertically and not horizontally too ? I specified "fill = BOTH" so it should extend in both direction. (I know that with expand = 1, it will expand in both direction) thx From jeanmichel at sequans.com Tue Nov 4 09:38:52 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 4 Nov 2014 15:38:52 +0100 (CET) Subject: generating unique variable name via loops In-Reply-To: Message-ID: <342307772.2724812.1415111932401.JavaMail.root@sequans.com> ----- Original Message ----- > From: "Fatih G?ven" > I have a structured and repetitive data. I want to read a .txt file > line by line and classified it to call easily. For example employee1 > has a name, a salary, shift, age etc. and employee2 and other 101 > employee have all of it. > > Call employee1.name or employee2.salary and assign it to a new > variable, something etc. Some python 2.7 pseudo code to give you some leads employes = {} with open('file.txt') as f_: for line in f_: name, age, phone = line.split(',') employes[name] = (age, phone) print employes If your file is a csv format, it could even be easier using the csv module. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From nomail at invalid.com Tue Nov 4 09:41:47 2014 From: nomail at invalid.com (ast) Date: Tue, 4 Nov 2014 15:41:47 +0100 Subject: fill, expand from tkinter.pack() layout manager In-Reply-To: <5458dfc6$0$27505$426a74cc@news.free.fr> References: <5458dfc6$0$27505$426a74cc@news.free.fr> Message-ID: <5458e5b2$0$2929$426a74cc@news.free.fr> "ast" a ?crit dans le message de news:5458dfc6$0$27505$426a74cc at news.free.fr... > w.pack(side=LEFT, fill = BOTH) > Why is the label "w" only extended vertically and not horizontally too ? with: w.pack(side=TOP, fill = BOTH) it expand horizontally but not vertically with: w.pack(side=LEFT, fill = BOTH, expand = 1) or w.pack(side=TOP, fill = BOTH, expand = 1) it expand both horizontally and vertically From mfthguven at gmail.com Tue Nov 4 09:42:29 2014 From: mfthguven at gmail.com (=?ISO-8859-1?Q?Fatih_G=FCven?=) Date: Tue, 4 Nov 2014 06:42:29 -0800 (PST) Subject: fill, expand from tkinter.pack() layout manager In-Reply-To: <5458dfc6$0$27505$426a74cc@news.free.fr> References: <5458dfc6$0$27505$426a74cc@news.free.fr> Message-ID: 4 Kas?m 2014 Sal? 16:16:52 UTC+2 tarihinde ast yazd?: > Hi > > I dont really understood how "fill" and "expand" > works with layout manager tkinter.pack() > > Example: > > from tkinter import * > root = Tk() > w = Label(root, text="Red", bg="red", fg="white") > w.pack(side=LEFT, fill = BOTH) > > Here is the result: > http://cjoint.com/?0Kepj1E3Tv3 > > Why is the label "w" only extended vertically and not horizontally too ? > I specified "fill = BOTH" so it should extend in both direction. > > (I know that with expand = 1, it will expand in both direction) > > thx Hi, Packing widgets splits frame into equal areas with expand=1. if expand="false", widgets don't touch each other and widgets save their own dimension. From gandalf23 at mail.com Tue Nov 4 09:53:31 2014 From: gandalf23 at mail.com (Kiuhnm) Date: Tue, 4 Nov 2014 06:53:31 -0800 (PST) Subject: simple download manager Message-ID: <5d9b7957-ee57-4cc4-b4eb-7a933bad1a5e@googlegroups.com> I wish to automate the downloading from a particular site which has some ADs and which requires to click on a lot of buttons before the download starts. What library should I use to handle HTTP? Also, I need to support big files (> 1 GB) so the library should hand the data to me chunk by chunk. From rosuav at gmail.com Tue Nov 4 09:57:11 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Nov 2014 01:57:11 +1100 Subject: Python extension using a C library with one 'hello' function In-Reply-To: References: Message-ID: On Tue, Nov 4, 2014 at 8:52 PM, Veek M wrote: > https://github.com/Veek/Python/tree/master/junk/hello > doesn't work. > I have: > hello.c which contains: int hello(void); > hello.h > > To wrap that up, i have: > hello.py -> _hello (c extension) -> pyhello.c -> method py_hello() > > People using this will do: > python3.2>> import hello > python3.2>> hello.hello() > > It doesn't compile/work. > [details chomped] Have you considered using Cython? It'll likely make your job a LOT easier. ChrisA From rosuav at gmail.com Tue Nov 4 09:59:52 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Nov 2014 01:59:52 +1100 Subject: simple download manager In-Reply-To: <5d9b7957-ee57-4cc4-b4eb-7a933bad1a5e@googlegroups.com> References: <5d9b7957-ee57-4cc4-b4eb-7a933bad1a5e@googlegroups.com> Message-ID: On Wed, Nov 5, 2014 at 1:53 AM, Kiuhnm wrote: > I wish to automate the downloading from a particular site which has some ADs and which requires to click on a lot of buttons before the download starts. > > What library should I use to handle HTTP? > Also, I need to support big files (> 1 GB) so the library should hand the data to me chunk by chunk. You may be violating the site's terms of service, so be aware of what you're doing. This could be a really simple job (just figure out what the last HTTP query is, and replicate that), or it could be insanely complicated (crypto, JavaScript, and/or timestamped URLs could easily be involved). To start off, I would recommend not writing a single like of Python code, but just pulling up Mozilla Firefox with Firebug, or Google Chrome with in-built inspection tools, or some equivalent, and watching the exact queries that go through. Once you figure out what queries are happening, you can figure out how to do them in Python. ChrisA From __peter__ at web.de Tue Nov 4 10:00:43 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Nov 2014 16:00:43 +0100 Subject: generating unique variable name via loops References: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> <8df0b347-0569-4505-95f8-12baf44a1743@googlegroups.com> Message-ID: Fatih G?ven wrote: > 4 Kas?m 2014 Sal? 15:37:59 UTC+2 tarihinde Peter Otten yazd?: >> Veek M wrote: >> >> > Fatih G?ven wrote: >> > >> >> 4 Kas?m 2014 Sal? 13:29:34 UTC+2 tarihinde Fatih G?ven yazd?: >> >>> I want to generate a unique variable name for list using python. >> >>> >> >>> list1=... >> >>> list2=... >> > >> > for x in range(1,10): >> > exec("list%d = []" % x) >> >> Why would you do this? > > I have a structured and repetitive data. I was actually asking "Veek M". > I want to read a .txt file line > by line and classified it to call easily. For example employee1 has a > name, a salary, shift, age etc. and employee2 and other 101 employee have > all of it. > > Call employee1.name or employee2.salary and assign it to a new variable, > something etc. I can only repeat my previous advice. Instead of creating variables for employee1, employee2, and so on make a list of employees: $ cat employees.txt Peter,3000 Paul,2000 Mary,1000 $ cat employees.py #!/usr/bin/env python3 import csv class Employee: def __init__(self, name, salary): self.name = name self.salary = salary if __name__ == "__main__": employees = [] with open("employees.txt") as f: for row in csv.reader(f): employees.append(Employee(row[0], int(row[1]))) for employee in employees: print(employee.name, "-- salary:", employee.salary, "doubloons") $ python3 employees.py Peter -- salary: 3000 doubloons Paul -- salary: 2000 doubloons Mary -- salary: 1000 doubloons You wouldn't want to reference Paul as employee2 -- what if the order in the text file changed? Instead you can make a dict that maps name to employee... employees_by_name = {} for employee in employees: name = employee.name if name in employees_by_name: raise ValueError("duplicate name {}".format(name)) employees_by_name[name] = employee and use that dict to look up an employee: while True: name = input("enter a name ") if name == "": print("That's all folks") break if name not in employees_by_name: print("unknown name") else: print("Salary:", employees_by_name[name].salary, "doubloons") $ python3 employees.py Peter -- salary: 3000 doubloons Paul -- salary: 2000 doubloons Mary -- salary: 1000 doubloons enter a name Peter Salary: 3000 doubloons enter a name Mary Salary: 1000 doubloons enter a name paul unknown name enter a name Paul Salary: 2000 doubloons enter a name That's all folks $ From mmr15 at case.edu Tue Nov 4 10:04:18 2014 From: mmr15 at case.edu (Matthew Ruffalo) Date: Tue, 04 Nov 2014 10:04:18 -0500 Subject: generating unique variable name via loops In-Reply-To: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> References: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> Message-ID: <5458EAF2.8000200@case.edu> Hi- Questions like this appear so often in various places (mailing lists, forums, sites like Stack Overflow) that I think a very blunt/candid answer is appropriate. This is especially true since there's always someone who responds to the question as-is with some monstrosity of exec() and string formatting, instead of addressing the underlying issue of using the right data structure for what you're trying to accomplish. On 11/04/2014 06:29 AM, Fatih G?ven wrote: > I want to generate a unique variable name for list using python. > > list1=... > list2=... > . > . > . > listx=... where x is a number. *Incorrect.* You do not want to do this. You think you do, but that's presumably because you aren't familiar with common data structures that are available in Python. As Peter Otten said, this is *exactly* the right situation to use a list. You mentioned having structured and repetitive data, wanting to read a .txt file and process each line, and wanting to access each employee's data as appropriate. The general structure of this would be >>> employees = [] >>> with open('employee_data.txt') as f: ... for line in f: ... # parse_line here isn't anything standard or built-in, it's ... # what you would write to transform a line of the data ... # file into whatever object you're interested in with ... # 'name', 'salary', etc. attributes ... employee = parse_line(line) ... employees.append(employee) ... >>> employees[0].salary 150000 Your line1 is now employees[0] and so on. Now, you can *easily* answer questions like "what's the total salary of all employees?" >>> total = 0 >>> for employee in employees: ... total += employee.salary ... >>> total 7502000 (or 'sum(employee.salary for employee in employees)' of course.) MMR... From gandalf23 at mail.com Tue Nov 4 10:10:47 2014 From: gandalf23 at mail.com (Kiuhnm) Date: Tue, 4 Nov 2014 07:10:47 -0800 (PST) Subject: simple download manager In-Reply-To: References: <5d9b7957-ee57-4cc4-b4eb-7a933bad1a5e@googlegroups.com> Message-ID: On Tuesday, November 4, 2014 4:00:51 PM UTC+1, Chris Angelico wrote: > On Wed, Nov 5, 2014 at 1:53 AM, Kiuhnm wrote: > > I wish to automate the downloading from a particular site which has some ADs and which requires to click on a lot of buttons before the download starts. > > > > What library should I use to handle HTTP? > > Also, I need to support big files (> 1 GB) so the library should hand the data to me chunk by chunk. > > You may be violating the site's terms of service, so be aware of what > you're doing. > > This could be a really simple job (just figure out what the last HTTP > query is, and replicate that), or it could be insanely complicated > (crypto, JavaScript, and/or timestamped URLs could easily be > involved). To start off, I would recommend not writing a single like > of Python code, but just pulling up Mozilla Firefox with Firebug, or > Google Chrome with in-built inspection tools, or some equivalent, and > watching the exact queries that go through. Once you figure out what > queries are happening, you can figure out how to do them in Python. > > ChrisA It'll be tricky. I'm sure of that, but if the browser can do it, so can I :) Fortunately, there are no captchas. From jason.swails at gmail.com Tue Nov 4 10:30:00 2014 From: jason.swails at gmail.com (Jason Swails) Date: Tue, 04 Nov 2014 10:30:00 -0500 Subject: Python extension using a C library with one 'hello' function In-Reply-To: References: Message-ID: <1415115000.25472.4.camel@gmail.com> On Tue, 2014-11-04 at 16:22 +0630, Veek M wrote: > https://github.com/Veek/Python/tree/master/junk/hello > doesn't work. > I have: > hello.c which contains: int hello(void); > hello.h > > To wrap that up, i have: > hello.py -> _hello (c extension) -> pyhello.c -> method py_hello() > > People using this will do: > python3.2>> import hello > python3.2>> hello.hello() > > It doesn't compile/work. > > deathstar> python setup.py build_ext --inplace > running build_ext > building '_hello' extension > creating build > creating build/temp.linux-x86_64-3.2 > gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes - > D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=4 -Wformat - > Werror=format-security -fPIC -I/usr/include/python3.2mu -c pyhello.c -o > build/temp.linux-x86_64-3.2/pyhello.o > pyhello.c:15:6: warning: character constant too long for its type [enabled > by default] > pyhello.c:15:5: warning: initialization makes pointer from integer without a > cast [enabled by default] > pyhello.c:15:5: warning: (near initialization for 'hellomethods[0].ml_name') > [enabled by default] > pyhello.c:15:5: warning: initialization from incompatible pointer type > [enabled by default] > pyhello.c:15:5: warning: (near initialization for 'hellomethods[0].ml_meth') > [enabled by default] > pyhello.c:15:5: warning: initialization makes integer from pointer without a > cast [enabled by default] > pyhello.c:15:5: warning: (near initialization for > 'hellomethods[0].ml_flags') [enabled by default] > gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-z,relro > build/temp.linux-x86_64-3.2/pyhello.o -o > /root/github/junk/hello/_hello.cpython-32mu.so > > > >>> import hello > Traceback (most recent call last): > File "", line 1, in > File "hello.py", line 1, in > from _hello import * > ImportError: ./_hello.cpython-32mu.so: undefined symbol: hello When I try your code, I get the error: ImportError: dynamic module does not define init function (PyInit__hello) There were a couple other problems as well. Like 'hello' in hellomethods instead of "hello" (note the double quotes). Also, NULL is no longer acceptable as a METH_XXXARGS replacement, you need to set it to METH_NOARGS (or MET_VARARGS if you plan on accepting arguments). I've found that you also need a NULL sentinel in the hellomethods array to avoid segfaults on my Linux box. After fixing these problems, you still need to add "hello.c" to the list of sources in setup.py to make sure that module is built. I've submitted a PR to your github repo showing you the changes necessary to get your module working on my computer. Hope this helps, Jason From sd at syntonetic.com Tue Nov 4 07:11:15 2014 From: sd at syntonetic.com (=?windows-1252?Q?S=F8ren?=) Date: Tue, 04 Nov 2014 13:11:15 +0100 Subject: Python extension using a C library with one 'hello' function In-Reply-To: <5458C1DF.9010802@syntonetic.com> References: <5458C1DF.9010802@syntonetic.com> Message-ID: <5458C263.7090409@syntonetic.com> I'm not sure if it fits your needs, but we are very happy with calling c libs directly from python using ctypes: https://docs.python.org/2/library/ctypes.html It requires a few extra lines in Python to handle the parameter and return types. import ctypes result = ctypes.windll.Hello.hello() From illusiontechniques at gmail.com Tue Nov 4 10:28:33 2014 From: illusiontechniques at gmail.com (C Smith) Date: Tue, 4 Nov 2014 07:28:33 -0800 Subject: Code review Message-ID: I was wondering if I could get some feedback on the biggest thing I have done as an amateur Python coder. The sidepots algorithm isn't correct yet, but I haven't worked on it in a while and thought I would get some advice before diving back in. import random, os ################################################################## class Table(object): def __init__(self,bigblind=20,PLAYERNUM=0,pot=0,PLAYERORDER=None, hand_done=0,\ left_to_act=None,cost_to_play=0,in_hand=None,last_raise=0,cards_in_play=None,round='preflop'): if cards_in_play is None: cards_in_play = [] if in_hand is None: in_hand = [] if PLAYERORDER is None: PLAYERORDER = [] if left_to_act is None: left_to_act = [] self.hand_done = hand_done self.round = round self.cards_in_play = cards_in_play self.last_raise = last_raise self.in_hand = in_hand self.cost_to_play = cost_to_play self.left_to_act = left_to_act self.PLAYERORDER = PLAYERORDER self.bigblind = bigblind self.PLAYERNUM = PLAYERNUM self.pot = pot ################################################################## def fillseats(self,listofplayers, playas): seating = [x for x in range(1,len(listofplayers)+1)] random.shuffle(seating) for y in listofplayers: playas[y].seatnumber = seating.pop() for x in listofplayers: newx = str(playas[x].seatnumber)+x self.PLAYERORDER.append(newx) self.PLAYERORDER = sorted(self.PLAYERORDER) neworder = [] for x in self.PLAYERORDER: neworder.append(x[1:]) self.PLAYERORDER = neworder self.PLAYERNUM = len(self.PLAYERORDER) ########################################################## def postblinds(self,playas,bigblind,deck): # establish player.start_stack for sidepots for player in self.PLAYERORDER: playas[player].start_stack = playas[player].stacksize # Heads up post blinds if len(self.PLAYERORDER) == 2: if bigblind >= playas[self.PLAYERORDER[1]].stacksize: if bigblind == playas[self.PLAYERORDER[1]].stacksize: playas[self.PLAYERORDER[1]].stacksize = 0 self.pot += bigblind playas[self.PLAYERORDER[1]].all_in = 1 playas[self.PLAYERORDER[1]].in_front = bigblind playas[self.PLAYERORDER[1]].put_in_pot = bigblind else: self.pot += playas[self.PLAYERORDER[1]].stacksize playas[self.PLAYERORDER[1]].in_front = playas[self.PLAYERORDER[1]].stacksize playas[self.PLAYERORDER[1]].put_in_pot = playas[self.PLAYERORDER[1]].stacksize playas[self.PLAYERORDER[1]].stacksize = 0 playas[self.PLAYERORDER[1]].all_in = 1 if (bigblind/2) >= playas[self.PLAYERORDER[0]].stacksize: if bigblind == playas[self.PLAYERORDER[0]].stacksize: playas[self.PLAYERORDER[0]].in_front = bigblind/2 playas[self.PLAYERORDER[0]].put_in_pot = bigblind/2 playas[self.PLAYERORDER[0]].stacksize = 0 self.pot += bigblind/2 playas[self.PLAYERORDER[0]].all_in = 1 else: playas[self.PLAYERORDER[0]].put_in_pot = playas[self.PLAYERORDER[0]].stacksize playas[self.PLAYERORDER[0]].in_front = playas[self.PLAYERORDER[0]].stacksize playas[self.PLAYERORDER[0]].stacksize = 0 playas[self.PLAYERORDER[0]].all_in = 1 if playas[self.PLAYERORDER[0]].all_in == 0: playas[self.PLAYERORDER[0]].stacksize -= bigblind/2 playas[self.PLAYERORDER[0]].in_front = bigblind/2 playas[self.PLAYERORDER[0]].put_in_pot = bigblind/2 self.pot += bigblind/2 if playas[self.PLAYERORDER[1]].all_in == 0: playas[self.PLAYERORDER[1]].stacksize -= bigblind playas[self.PLAYERORDER[1]].in_front = bigblind playas[self.PLAYERORDER[1]].put_in_pot = bigblind self.pot += bigblind self.left_to_act = self.PLAYERORDER[:] self.cost_to_play = bigblind self.last_raise = bigblind else: # post blinds for more that 2 players # player has not enough or just enough for big blind if playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].stacksize <= bigblind: if playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].stacksize < bigblind: playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].put_in_pot = playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].stacksize playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].in_front = playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].stacksize playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].all_in = 1 self.pot += playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].stacksize playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].stacksize = 0 elif playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].stacksize == bigblind: playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].in_front = bigblind playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].put_in_pot = bigblind playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].all_in = 1 self.pot += bigblind playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].stacksize = 0 else: # Normal post bigblind playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].stacksize -= bigblind playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].in_front = bigblind playas[self.PLAYERORDER[2%len(self.PLAYERORDER)]].put_in_pot = bigblind self.pot += bigblind # player has not enough or just enough for small blind if playas[self.PLAYERORDER[1]].stacksize <= bigblind/2: if playas[self.PLAYERORDER[1]].stacksize < bigblind/2: playas[self.PLAYERORDER[1]].all_in = 1 self.pot += playas[self.PLAYERORDER[1]].stacksize playas[self.PLAYERORDER[1]].in_front = playas[self.PLAYERORDER[1]].stacksize playas[self.PLAYERORDER[1]].put_in_pot = playas[self.PLAYERORDER[1]].stacksize playas[self.PLAYERORDER[1]].stacksize = 0 elif playas[self.PLAYERORDER[1]].stacksize == bigblind/2: playas[self.PLAYERORDER[1]].all_in = 1 self.pot += bigblind/2 playas[self.PLAYERORDER[1]].in_front = bigblind/2 playas[self.PLAYERORDER[1]].put_in_pot = bigblind/2 playas[self.PLAYERORDER[1]].stacksize = 0 else: # normal post small blind playas[self.PLAYERORDER[1]].stacksize -= bigblind/2 playas[self.PLAYERORDER[1]].in_front = bigblind/2 playas[self.PLAYERORDER[1]].put_in_pot = bigblind/2 self.pot += bigblind/2 self.left_to_act = self.PLAYERORDER[3%len(self.PLAYERORDER):]+self.PLAYERORDER[:3%len(self.PLAYERORDER)] self.cost_to_play = bigblind self.last_raise = bigblind for x in self.PLAYERORDER: playas[x].drawcard(deck.draw()) for x in self.PLAYERORDER: playas[x].drawcard(deck.draw()) for x in self.PLAYERORDER: print x+" stacksize is "+str(playas[x].stacksize) print x+" is at seat number "+str(playas[x].seatnumber) print raw_input('to begin, hit any key') self.get_action(playas, bigblind, deck) ################################################################## def showdown(self,playas,bigblind,deck): print "in_hand equals %s" % self.in_hand handtobeat = 0 for player in self.in_hand: final_hand = self.cards_in_play + playas[player].hand ranks = [x[0] for x in final_hand] suits = [x[1] for x in final_hand] #ints with Ace as 14 and 2 for straights straightranks = [] #ints with Ace as 14 for pairs pairranks = [] for rank in ranks: if rank == 'T': straightranks.append(10) elif rank == 'J': straightranks.append(11) elif rank == 'Q': straightranks.append(12) elif rank == 'K': straightranks.append(13) elif rank == 'A': straightranks.append(1) straightranks.append(14) else: straightranks.append(int(rank)) pairranks = [x for x in straightranks if x != 1] straightranks = sorted(list(set(straightranks)),reverse=True) ########### USE straightranks FOR STRAIGHTS if straight_flush_finder(final_hand)[0] == True: playas[player].hand_rank = (9,straight_flush_finder(final_hand)) elif four_of_a_kind_finder(pairranks)[0] == True: playas[player].hand_rank = (8,four_of_a_kind_finder(pairranks)) elif fullhouse_finder(pairranks)[0] == True: playas[player].hand_rank = (7,fullhouse_finder(pairranks)) elif flush_finder(final_hand)[0] == True: playas[player].hand_rank = (6,flush_finder(final_hand)) elif straight_finder(straightranks)[0] == True: playas[player].hand_rank = (5,straight_finder(straightranks)) elif three_of_a_kind_finder(pairranks)[0] == True: playas[player].hand_rank = (4,three_of_a_kind_finder(pairranks)) elif two_pair_finder(pairranks)[0] == True: playas[player].hand_rank = (3,two_pair_finder(pairranks)) elif one_pair_finder(pairranks)[0] == True: playas[player].hand_rank = (2,one_pair_finder(pairranks)) else: playas[player].hand_rank = (1,highcard_finder(pairranks)) # check if any player has a different amount in the pot (sidepot necessary) one_put_in_pot = playas[self.in_hand[0]].put_in_pot for player in self.in_hand: if playas[player].put_in_pot != one_put_in_pot: bigstack = 0 bigplayer = '' for player in self.in_hand: if playas[player].put_in_pot > bigstack: bigplayer = player bigstack = playas[player].put_in_pot in_hand_copy = self.in_hand[:] in_hand_copy.remove(bigplayer) lowstack = 999999999999999 lowman = '' for player in in_hand_copy: if playas[player].put_in_pot < lowstack: lowman = player lowstack = playas[player].put_in_pot if playas[bigplayer].put_in_pot > playas[lowman].put_in_pot: print 'bigplayer %s put in pot is %s' % (bigplayer, playas[bigplayer].put_in_pot) print 'lowman %s put in pot %s' % (lowman, playas[lowman].put_in_pot) for player in self.in_hand: print '%s is in hand and put %s in pot' % (player, playas[player].put_in_pot) raw_input("Sidepot split necessary, hit enter to continue") sidepot1 = 0 for player in self.PLAYERORDER: sidepot1 += min(playas[player].put_in_pot,playas[lowman].put_in_pot) sidepot1elig = self.in_hand[:] self.pot -= sidepot1 sidepot1winners = [] handtobeat = 0 for player in sidepot1elig: if playas[player].hand_rank[0] >= handtobeat: handtobeat = playas[player].hand_rank[0] sidepot1winners.append(player) for player in sidepot1winners: if playas[player].hand_rank[0] < handtobeat: sidepot1winners.remove(player) sidepot1winners = tie_breaker(sidepot1winners,playas) for player in sidepot1winners[0]: print '%s you win %s chips' % (player,sidepot1/len(sidepot1winners[0])) playas[player].stacksize += (sidepot1/len(sidepot1winners[0])) showmuck = 'x' while showmuck not in ['s','m']: showmuck = raw_input('%s show or muck hand? (hit s OR m) ' % player) if showmuck == 's': playas[player].showhand() print playas[player].hand_rank if showmuck == 'm': playas[player].muckhand() anothercopy = self.in_hand[:] for player in anothercopy: if playas[player].start_stack == playas[lowman].start_stack: self.in_hand.remove(player) break ############## rest of showdown handtobeat = 0 winningplayers = [] for player in self.in_hand: if playas[player].hand_rank[0] >= handtobeat: handtobeat = playas[player].hand_rank[0] winningplayers.append(player) winnerscopy = winningplayers[:] for player in winnerscopy: if playas[player].hand_rank[0] < handtobeat: winningplayers.remove(player) # tie_breaker changes winningplayers into nested list winningplayers = tie_breaker(winningplayers,playas) for winnerwinner in winningplayers[0]: self.hand_done = 1 print '%s you win %s chips' % (winnerwinner,self.pot/len(winningplayers[0])) playas[winnerwinner].stacksize += (self.pot/len(winningplayers[0])) showmuck = 'x' while showmuck not in ['s','m']: showmuck = raw_input('%s show or muck hand? (hit s OR m) ' % winnerwinner) if showmuck == 's': playas[winnerwinner].showhand() print playas[winnerwinner].hand_rank if showmuck == 'm': playas[winnerwinner].muckhand() self.end_hand(playas,bigblind,deck) ################################################################################# def turn_one(self, deck): self.cards_in_play.append(deck.draw()) print self.cards_in_play[-1] + ' drawn' raw_input('Hit Enter') def burn_one(self, deck): deck.burn() print 'Card Burnt' raw_input('Hit Enter') ################################## def end_hand(self, playas, bigblind, deck): print 'hand done' playercopy = self.PLAYERORDER[:] for x in playercopy: print '%s stacksize is %s' % (x, playas[x].stacksize) if playas[x].stacksize == 0: print '%s you are out of the game.' % x self.PLAYERORDER.remove(x) if len(self.PLAYERORDER) == 1: print 'tournament over, %s wins' % self.PLAYERORDER[0] exit() raw_input('Hit enter for the next hand') for player in self.PLAYERORDER: playas[player].put_in_pot = 0 playas[player].all_in = 0 buttonmover = self.PLAYERORDER[0] self.PLAYERORDER = self.PLAYERORDER[1:] self.PLAYERORDER.append(buttonmover) self.left_to_act = [] self.in_hand = [] self.hand_done = 0 for x in self.PLAYERORDER: playas[x].in_front = 0 playas[x].hand = [] self.cards_in_play = [] self.pot = 0 self.round = 'preflop' self.last_raise = 0 self.cost_to_play = 0 deck.renew() self.postblinds(playas, bigblind, deck) ################################################################## def get_action(self,playas,bigblind,deck): ###################### test if folded around to a player (hand done without showdown) ################## if len(self.left_to_act) == 0 and len(self.in_hand) == 1: self.hand_done = 1 print '%s you win %s chips' % (self.in_hand[0],self.pot) playas[self.in_hand[0]].stacksize += self.pot showmuck = 'x' while showmuck not in ['s','m']: showmuck = raw_input('%s show or muck hand? (hit s OR m) ' % self.in_hand[0]) if showmuck == 's': playas[self.in_hand[0]].showhand() if showmuck == 'm': playas[self.in_hand[0]].muckhand() for player in self.in_hand: print playas[player].put_in_pot raw_input('Hit enter') self.end_hand(playas,bigblind,deck) ########################################################################### ################# test if river (last) round is done (SHOWDOWN) ################ if len(self.left_to_act) == 0 and self.round == 'river': self.hand_done = 1 #return excess chips bigstack = 0 bigplayer = '' for player in self.in_hand: if playas[player].put_in_pot > bigstack: bigplayer = player bigstack = playas[player].put_in_pot in_hand_copy = self.in_hand[:] in_hand_copy.remove(bigplayer) nextbigstack = 0 nextbigplayer = '' for player in in_hand_copy: if playas[player].put_in_pot > nextbigstack: nextbigplayer = player nextbigstack = playas[player].put_in_pot if playas[bigplayer].put_in_pot > playas[nextbigplayer].put_in_pot: ## ## nextbigstack could have folded difference = playas[bigplayer].put_in_pot - playas[nextbigplayer].put_in_pot playas[bigplayer].stacksize += difference playas[bigplayer].put_in_pot = playas[nextbigplayer].put_in_pot self.pot -= difference self.showdown(playas,bigblind,deck) print self.cards_in_play print 'Hand done' raw_input('hit enter') self.end_hand(playas,bigblind,deck) ##################################################################################### ################# test if turn (2nd to last round) is done ################################## if len(self.left_to_act) == 0 and self.round == 'turn': print self.cards_in_play print 'Turn done' raw_input('hit enter') self.round = 'river' for x in self.PLAYERORDER: playas[x].in_front = 0 self.last_raise = bigblind self.cost_to_play = 0 neworder = self.PLAYERORDER[1:]+self.PLAYERORDER[0:1] for x in neworder: if x in self.in_hand: self.left_to_act.append(x) self.in_hand = [] self.burn_one(deck) self.turn_one(deck) for player in self.in_hand: playas[player].in_front = 0 self.get_action(playas,bigblind,deck) ##################################################################################### ################# test if flop is done ################################################### if len(self.left_to_act) == 0 and self.round == 'postflop': print self.cards_in_play print 'Postflop done' raw_input('hit enter') self.round = 'turn' for x in self.PLAYERORDER: playas[x].in_front = 0 self.last_raise = bigblind self.cost_to_play = 0 neworder = self.PLAYERORDER[1:]+self.PLAYERORDER[0:1] for x in neworder: if x in self.in_hand: self.left_to_act.append(x) self.in_hand = [] self.burn_one(deck) self.turn_one(deck) for player in self.in_hand: playas[player].in_front = 0 self.get_action(playas,bigblind,deck) ##################################################################################### ################# test if preflop play is done ################################## if len(self.left_to_act) == 0 and self.round == 'preflop': for x in self.PLAYERORDER: playas[x].in_front = 0 print ' stacksize is %s' % playas[x].stacksize print 'in hand ',self.in_hand print 'player order ',self.PLAYERORDER print 'flop done' print 'pot is '+str(self.pot) self.last_raise = bigblind self.cost_to_play = 0 neworder = self.PLAYERORDER[1:]+self.PLAYERORDER[0:1] for x in neworder: if x in self.in_hand: self.left_to_act.append(x) self.in_hand = [] self.burn_one(deck) self.turn_one(deck) self.turn_one(deck) self.turn_one(deck) print self.cards_in_play self.round = 'postflop' raw_input("hit enter") self.get_action(playas,bigblind,deck) ############### turnscreen(self.left_to_act) ############### # Catch a player all-in and pass their turn if playas[self.left_to_act[0]].all_in == 1: raw_input("%s you are all in, hit enter to continue" % self.left_to_act[0]) if self.left_to_act[0] not in self.in_hand: self.in_hand.append(self.left_to_act[0]) del self.left_to_act[0] self.get_action(playas,bigblind,deck) ############# Display for each action prompt for x in self.PLAYERORDER: print x +'stacksize is '+ str(playas[x].stacksize) print self.left_to_act[0] + ' your hand is '+playas[self.left_to_act[0]].hand[0]+' '+playas[self.left_to_act[0]].hand[1] print 'The last raise is '+str(self.last_raise) print 'The pot is '+str(self.pot) print 'The cost to play is '+str(self.cost_to_play-playas[self.left_to_act[0]].in_front) print 'You have %s in the pot' % playas[self.left_to_act[0]].put_in_pot print 'You started the hand with %s chips' % playas[self.left_to_act[0]].start_stack print 'This round, you have put %s chips in the pot' % playas[self.left_to_act[0]].in_front showcards = (', ').join(x for x in self.cards_in_play) print 'The cards in play are '+showcards # Check if a player can Check their turn if playas[self.left_to_act[0]].in_front >= self.cost_to_play: current_action = 'q' current_action = raw_input("%s will you check, bet, or fold? (type c OR b OR f) " % self.left_to_act[0]) #Check your turn, if infront == cost if current_action == 'c': if self.left_to_act[0] in self.in_hand: del self.in_hand[self.left_to_act[0]] self.in_hand.append(self.left_to_act[0]) self.left_to_act.remove(self.left_to_act[0]) self.get_action(playas,bigblind,deck) # Bet , after check option elif current_action == 'b': currentraise = 3 while currentraise % 10 != 0: currentraise = int(raw_input('%s what will you bet? (increments of 10) ' % self.left_to_act[0])) while currentraise < 2*self.last_raise: currentraise = int(raw_input('%s what will you bet? (increments of 10) ' % self.left_to_act[0])) # Bet with exactly enough chips, after check option if self.cost_to_play-playas[self.left_to_act[0]].in_front + currentraise == playas[self.left_to_act[0]].stacksize: raw_input("%s you are all in" % self.left_to_act[0]) playas[self.left_to_act[0]].all_in = 1 self.last_raise = playas[self.left_to_act[0]].stacksize self.pot += (self.cost_to_play-playas[self.left_to_act[0]].in_front+playas[self.left_to_act[0]].stacksize) self.cost_to_play += playas[self.left_to_act[0]].stacksize playas[self.left_to_act[0]].in_front += playas[self.left_to_act[0]].stacksize playas[self.left_to_act[0]].put_in_pot += playas[self.left_to_act[0]].stacksize playas[self.left_to_act[0]].stacksize = 0 if self.left_to_act[0] in self.in_hand: self.in_hand.remove(self.left_to_act[0]) for x in self.in_hand: if x not in self.left_to_act: self.left_to_act.append(x) self.in_hand.append(self.left_to_act[0]) self.left_to_act.remove(self.left_to_act[0]) self.get_action(playas,bigblind,deck) ### Bet, not enough chips, after check option elif self.cost_to_play-playas[self.left_to_act[0]].in_front + currentraise > playas[self.left_to_act[0]].stacksize: raw_input("Not enough to raise that amount, %s put all in, hit enter" % self.left_to_act[0]) playas[self.left_to_act[0]].all_in = 1 self.pot += playas[self.left_to_act[0]].stacksize playas[self.left_to_act[0]].put_in_pot += playas[self.left_to_act[0]].stacksize currentraise = playas[self.left_to_act[0]].stacksize-self.cost_to_play-playas[self.left_to_act[0]].in_front playas[self.left_to_act[0]].in_front += playas[self.left_to_act[0]].stacksize self.cost_to_play += currentraise self.last_raise = playas[self.left_to_act[0]].stacksize playas[self.left_to_act[0]].stacksize = 0 if self.left_to_act[0] in self.in_hand: self.in_hand.remove(self.left_to_act[0]) for x in self.in_hand: if x not in self.left_to_act: self.left_to_act.append(x) self.in_hand.append(self.left_to_act[0]) self.left_to_act.remove(self.left_to_act[0]) self.get_action(playas,bigblind,deck) # Rest of Bet, more than enough chips after check option self.pot += (currentraise + self.cost_to_play-playas[self.left_to_act[0]].in_front) playas[self.left_to_act[0]].put_in_pot += (currentraise + self.cost_to_play-playas[self.left_to_act[0]].in_front) self.last_raise = currentraise self.cost_to_play += currentraise playas[self.left_to_act[0]].stacksize -= (self.cost_to_play - playas[self.left_to_act[0]].in_front) playas[self.left_to_act[0]].in_front += (self.cost_to_play - playas[self.left_to_act[0]].in_front) if self.left_to_act[0] in self.in_hand: self.in_hand.remove(self.left_to_act[0]) for x in self.in_hand: if x not in self.left_to_act: self.left_to_act.append(x) self.in_hand.append(self.left_to_act[0]) self.left_to_act.remove(self.left_to_act[0]) self.get_action(playas,bigblind,deck) # Fold, after check option. Hey, you can do it! elif current_action == 'f': if self.left_to_act[0] in self.in_hand: self.in_hand.remove(self.left_to_act[0]) self.left_to_act.remove(self.left_to_act[0]) self.get_action(playas,bigblind,deck) # Prompt for action, no check option current_action = raw_input("%s will you call, raise, or fold? (type c OR r OR f) " % self.left_to_act[0]) # Call if current_action == 'c': # Not enough chips, or just enough chips to call if self.cost_to_play-playas[self.left_to_act[0]].in_front >= playas[self.left_to_act[0]].stacksize: playas[self.left_to_act[0]].all_in = 1 self.pot += playas[self.left_to_act[0]].stacksize playas[self.left_to_act[0]].put_in_pot += playas[self.left_to_act[0]].stacksize playas[self.left_to_act[0]].in_front += playas[self.left_to_act[0]].stacksize playas[self.left_to_act[0]].stacksize = 0 if self.left_to_act[0] in self.in_hand: self.in_hand.remove(self.left_to_act[0]) self.in_hand.append(self.left_to_act[0]) self.left_to_act.remove(self.left_to_act[0]) self.get_action(playas,bigblind,deck) # Call, with more than enough chips else: playas[self.left_to_act[0]].stacksize -= (self.cost_to_play-playas[self.left_to_act[0]].in_front) self.pot += (self.cost_to_play-playas[self.left_to_act[0]].in_front) playas[self.left_to_act[0]].put_in_pot += (self.cost_to_play-playas[self.left_to_act[0]].in_front) playas[self.left_to_act[0]].in_front += (self.cost_to_play-playas[self.left_to_act[0]].in_front) if self.left_to_act[0] in self.in_hand: self.in_hand.remove(self.left_to_act[0]) self.in_hand.append(self.left_to_act[0]) self.left_to_act.remove(self.left_to_act[0]) self.get_action(playas,bigblind,deck) # Raise, no check option elif current_action == 'r': currentraise = 3 while currentraise % 10 != 0: currentraise = int(raw_input('%s what will you raise? (increments of 10) ' % self.left_to_act[0])) while currentraise < 2*self.last_raise: currentraise = int(raw_input('%s what will you raise? (increments of 10) ' % self.left_to_act[0])) # Raise with exactly enough chips if self.cost_to_play-playas[self.left_to_act[0]].in_front + currentraise == playas[self.left_to_act[0]].stacksize: raw_input("%s you are all in" % self.left_to_act[0]) self.pot += playas[self.left_to_act[0]].stacksize playas[self.left_to_act[0]].put_in_pot += playas[self.left_to_act[0]].stacksize self.cost_to_play += currentraise self.last_raise = currentraise playas[self.left_to_act[0]].all_in = 1 playas[self.left_to_act[0]].in_front += playas[self.left_to_act[0]].stacksize playas[self.left_to_act[0]].stacksize = 0 if self.left_to_act[0] in self.in_hand: self.in_hand.remove(self.left_to_act[0]) for x in self.in_hand: if x not in self.left_to_act: self.left_to_act.append(x) self.in_hand.append(self.left_to_act[0]) self.left_to_act.remove(self.left_to_act[0]) self.get_action(playas,bigblind,deck) ### Raise not enough chips elif self.cost_to_play-playas[self.left_to_act[0]].in_front + currentraise > playas[self.left_to_act[0]].stacksize: raw_input("%s put all in, hit enter" % self.left_to_act[0]) playas[self.left_to_act[0]].all_in = 1 self.cost_to_play = playas[self.left_to_act[0]].stacksize self.last_raise = playas[self.left_to_act[0]].stacksize self.pot += playas[self.left_to_act[0]].stacksize playas[self.left_to_act[0]].put_in_pot += playas[self.left_to_act[0]].stacksize playas[self.left_to_act[0]].in_front += playas[self.left_to_act[0]].stacksize playas[self.left_to_act[0]].stacksize = 0 if self.left_to_act[0] in self.in_hand: self.in_hand.remove(self.left_to_act[0]) for x in self.in_hand: if x not in self.left_to_act: self.left_to_act.append(x) self.in_hand.append(self.left_to_act[0]) self.left_to_act.remove(self.left_to_act[0]) self.get_action(playas,bigblind,deck) # Raise with enough chips self.pot += (currentraise + self.cost_to_play-playas[self.left_to_act[0]].in_front) playas[self.left_to_act[0]].put_in_pot += (currentraise + self.cost_to_play-playas[self.left_to_act[0]].in_front) self.last_raise = currentraise self.cost_to_play += currentraise playas[self.left_to_act[0]].stacksize -= (self.cost_to_play - playas[self.left_to_act[0]].in_front) playas[self.left_to_act[0]].in_front += (self.cost_to_play - playas[self.left_to_act[0]].in_front) if self.left_to_act[0] in self.in_hand: self.in_hand.remove(self.left_to_act[0]) for x in self.in_hand: if x not in self.left_to_act: self.left_to_act.append(x) self.in_hand.append(self.left_to_act[0]) self.left_to_act.remove(self.left_to_act[0]) self.get_action(playas,bigblind,deck) # Fold, after call option elif current_action == 'f': if self.left_to_act[0] in self.in_hand: self.in_hand.remove(self.left_to_act[0]) self.left_to_act.remove(self.left_to_act[0]) self.get_action(playas,bigblind,deck) ######################################################################### class Deck(object): def __init__(self,cards=None): if cards is None: cards = [] self.cards = cards suits = ["S","C","D","H"] ranks = ["2","3","4","5","6","7","8","9","T","J","Q","K","A"] for suit in suits: for rank in ranks: self.cards.append(rank+suit) random.shuffle(self.cards) def draw(self): return self.cards.pop() def burn(self): self.cards = self.cards[0:-1] def renew(self): suits = ["S","C","D","H"] ranks = ["2","3","4","5","6","7","8","9","T","J","Q","K","A"] self.cards = [] for suit in suits: for rank in ranks: self.cards.append(rank+suit) random.shuffle(self.cards) ################################################################## class Player(object): playercount = 0 def __init__(self,stacksize=0,HUMAN=True,hand=None,seatnumber=0,\ in_front=0,hand_rank=0,all_in=0,start_stack=0, put_in_pot=0): self.all_in = all_in self.seatnumber = seatnumber self.start_stack = start_stack self.hand_rank = hand_rank self.stacksize = stacksize self.HUMAN = HUMAN self.in_front = in_front self.put_in_pot = put_in_pot if hand == None: hand = [] self.hand = hand Player.playercount += 1 def drawcard(self,card): self.hand.append(card) def muckhand(self): self.hand = [] print 'mucked' def showhand(self): print self.hand ################################################################## def tie_breaker(winningplayers,playas): ranky = playas[winningplayers[0]].hand_rank[0] reallywinners = [] reallyreally = [] reallyreallyreally = [] thisisitiswear = [] okaylastone = [] high_int = 0 if ranky == 9 or ranky == 5: for player in winningplayers: if playas[player].hand_rank[1][1] > high_int: reallywinners = [] high_int = playas[player].hand_rank[1][1] if player not in reallywinners: reallywinners.append(player) if playas[player].hand_rank[1][1] == high_int: if player not in reallywinners: reallywinners.append(player) elif ranky == 8 or ranky == 7: for player in winningplayers: if playas[player].hand_rank[1][1] > high_int: reallywinners = [] high_int = playas[player].hand_rank[1][1] if player not in reallywinners: reallywinners.append(player) if playas[player].hand_rank[1][1] == high_int: if player not in reallywinners: reallywinners.append(player) if len(reallywinners) >= 2: high_int = 0 for player in reallywinners: if playas[player].hand_rank[1][2] > high_int: reallyreally = [] high_int = playas[player].hand_rank[1][2] if player not in reallyreally: reallyreally.append(player) if playas[player].hand_rank[1][2] == high_int: if player not in reallyreally: reallyreally.append(player) elif ranky == 6: for player in winningplayers: if playas[player].hand_rank[1][1][0] > high_int: reallywinners = [] high_int = playas[player].hand_rank[1][1][0] if player not in reallywinners: reallywinners.append(player) if playas[player].hand_rank[1][1][0] == high_int: if player not in reallywinners: reallywinners.append(player) elif ranky == 4: for player in winningplayers: if playas[player].hand_rank[1][1] > high_int: reallywinners = [] high_int = playas[player].hand_rank[1][1] if player not in reallywinners: reallywinners.append(player) if playas[player].hand_rank[1][1] == high_int: if player not in reallywinners: reallywinners.append(player) if len(reallywinners) >= 2: high_int = 0 for player in reallywinners: if playas[player].hand_rank[1][2][0] > high_int: reallyreally = [] high_int = playas[player].hand_rank[1][2][0] if player not in reallyreally: reallyreally.append(player) if playas[player].hand_rank[1][2][1] == high_int: if player not in reallyreally: reallyreally.append(player) elif ranky == 3: for player in winningplayers: if playas[player].hand_rank[1][1] > high_int: reallywinners = [] high_int = playas[player].hand_rank[1][1] if player not in reallywinners: reallywinners.append(player) if playas[player].hand_rank[1][1] == high_int: if player not in reallywinners: reallywinners.append(player) if len(reallywinners) >= 2: high_int = 0 for player in reallywinners: if playas[player].hand_rank[1][2] > high_int: reallyreally = [] high_int = playas[player].hand_rank[1][2] if player not in reallyreally: reallyreally.append(player) if playas[player].hand_rank[1][2] == high_int: if player not in reallyreally: reallyreally.append(player) if len(reallyreally) >= 2: high_int = 0 for player in reallyreally: if playas[player].hand_rank[1][3] > high_int: reallyreallyreally = [] high_int = playas[player].hand_rank[1][3] if player not in reallyreallyreally: reallyreallyreally.append(player) if playas[player].hand_rank[1][3] == high_int: if player not in reallyreallyreally: reallyreallyreally.append(player) elif ranky == 2: for player in winningplayers: if playas[player].hand_rank[1][1] > high_int: high_int = playas[player].hand_rank[1][1] reallywinners = [] if player not in reallywinners: reallywinners.append(player) if playas[player].hand_rank[1][1] == high_int: if player not in reallywinners: reallywinners.append(player) if len(reallywinners) >= 2: high_int = 0 for player in reallywinners: if playas[player].hand_rank[1][2][0] > high_int: high_int = playas[player].hand_rank[1][2][0] reallyreally = [] if player not in reallyreally: reallyreally.append(player) if playas[player].hand_rank[1][2][0] == high_int: if player not in reallyreally: reallyreally.append(player) if len(reallyreally) >= 2: high_int = 0 for player in reallyreally: if playas[player].hand_rank[1][2][1] > high_int: high_int = playas[player].hand_rank[1][2][1] reallyreallyreally = [] if player not in reallyreallyreally: reallyreallyreally.append(player) if playas[player].hand_rank[1][2][1] == high_int: if player not in reallyreallyreally: reallyreallyreally.append(player) if len(reallyreallyreally) >= 2: high_int = 0 for player in reallyreallyreally: if playas[player].hand_rank[1][2][2] > high_int: high_int = playas[player].hand_rank[1][2][2] thisisitiswear = [] if player not in thisisitiswear: thisisitiswear.append(player) if playas[player].hand_rank[1][2][2] == high_int: if player not in thisisitiswear: thisisitiswear.append(player) elif ranky == 1: for player in winningplayers: if playas[player].hand_rank[1][0] > high_int: high_int = playas[player].hand_rank[1][0] reallywinners = [] if player not in reallywinners: reallywinners.append(player) if playas[player].hand_rank[1][0] == high_int: if player not in reallywinners: reallywinners.append(player) if len(reallywinners) >= 2: high_int = 0 for player in reallywinners: if playas[player].hand_rank[1][1] > high_int: high_int = playas[player].hand_rank[1][1] reallyreally = [] if player not in reallyreally: reallyreally.append(player) if playas[player].hand_rank[1][1] == high_int: if player not in reallyreally: reallyreally.append(player) if len(reallyreally) >= 2: high_int = 0 for player in reallyreally: if playas[player].hand_rank[1][2] > high_int: high_int = playas[player].hand_rank[1][2] reallyreallyreally = [] if player not in reallyreallyreally: reallyreallyreally.append(player) if playas[player].hand_rank[1][2] == high_int: if player not in reallyreallyreally: reallyreallyreally.append(player) if len(reallyreallyreally) >= 2: high_int = 0 for player in reallyreallyreally: if playas[player].hand_rank[1][3] > high_int: high_int = playas[player].hand_rank[1][3] thisisitiswear = [] if player not in thisisitiswear: thisisitiswear.append(player) if playas[player].hand_rank[1][3] == high_int: if player not in thisisitiswear: thisisitiswear.append(player) if len(thisisitiswear) >= 2: high_int = 0 for player in thisisitiswear: if playas[player].hand_rank[1][4] > high_int: high_int = playas[player].hand_rank[1][4] okaylastone = [] if player not in okaylastone: okaylastone.append(player) if playas[player].hand_rank[1][4] == high_int: if player not in okaylastone: okaylastone.append(player) if len(okaylastone) >= 1: return [okaylastone,thisisitiswear,reallyreallyreally,reallyreally,reallywinners] elif len(thisisitiswear) >= 1: return [thisisitiswear,reallyreallyreally,reallyreally,reallywinners] elif len(reallyreallyreally) >= 1: return [reallyreallyreally,reallyreally,reallywinners] elif len(reallyreally) >= 1: return [reallyreally,reallywinners] else: return [reallywinners] ###################################################################### def turnscreen(listplayrs): os.system('cls' if os.name=='nt' else 'clear') raw_input("Turn the screen to %s and hit enter" % listplayrs[0]) os.system('cls' if os.name=='nt' else 'clear') ############################################################### def straight_finder(ranks): if len(ranks) < 5: return (False,0) if ranks[0] == ranks[1]+1 and ranks[1] == ranks[2]+1 and ranks[2] == ranks[3]+1\ and ranks[3] == ranks[4]+1: return (True,ranks[0]) else: return straight_finder(ranks[1:]) ############################################################################### def four_of_a_kind_finder(ranks): rankcounter = {14:0,13:0,12:0,11:0,10:0,9:0,8:0,7:0,6:0,5:0,4:0,3:0,2:0} for rank in ranks: rankcounter[rank] += 1 if 4 in rankcounter.values(): highcards = [] quads = 0 for card,amount in rankcounter.items(): if amount == 4: quads = card if 0 < amount < 4: highcards.append(card) return (True,quads,max(highcards)) else: return (False,0) ################################################################################ def fullhouse_finder(ranks): rankcounter = {14:0,13:0,12:0,11:0,10:0,9:0,8:0,7:0,6:0,5:0,4:0,3:0,2:0} for rank in ranks: rankcounter[rank] += 1 set3s = [] set2s = [] for card,amount in rankcounter.items(): if amount == 3: set3s.append(card) if amount == 2: set2s.append(card) if len(set3s) == 2: set2s.append(min(have3)) set3s.remove(min(have3)) if len(set3s) == 1 and len(set2s) >= 1: return (True,set3s[0],max(set2s)) else: return (False,0,0) ################################################# def two_pair_finder(pairranks): rankcounter = {14:0,13:0,12:0,11:0,10:0,9:0,8:0,7:0,6:0,5:0,4:0,3:0,2:0} pairsof2 = [] for rank in pairranks: rankcounter[rank] += 1 if rankcounter[rank] == 2: pairsof2.append(rank) highlist = [] for rank,amount in rankcounter.items(): if amount == 1: highlist.append(rank) highcard = max(highlist) if len(pairsof2) >= 2: overpair = max(pairsof2) pairsof2.remove(max(pairsof2)) return (True,overpair,max(pairsof2),highcard) else: return (False,0,0,0) ################################################# def flush_finder(final_hand): flushdict = {'S':0,'C':0,'H':0,'D':0} for card in final_hand: flushdict[card[1]] += 1 flushranks = [] for card in final_hand: if flushdict[card[1]] >= 5: suit = card[1] if card[0] == 'A': flushranks.append(14) elif card[0] == 'K': flushranks.append(13) elif card[0] == 'Q': flushranks.append(12) elif card[0] == 'J': flushranks.append(11) elif card[0] == 'T': flushranks.append(10) else: flushranks.append(int(card[0])) if len(flushranks) >= 5: return (True,sorted(flushranks,reverse=True),suit) else: return (False,0,0) ################################################################## def straight_flush_finder(final_hand): flushsuits = {'S':0,'C':0,'H':0,'D':0} for card in final_hand: flushsuits[card[1]] += 1 flushranks = [] for card in final_hand: if flushsuits[card[1]] >= 5: suit = card[1] if card[0] == 'A': flushranks.append(14) elif card[0] == 'K': flushranks.append(13) elif card[0] == 'Q': flushranks.append(12) elif card[0] == 'J': flushranks.append(11) elif card[0] == 'T': flushranks.append(10) else: flushranks.append(int(card[0])) if len(flushranks) >= 5: flushrankscopy = flushranks[:] for rank in flushrankscopy: if rank == 14: flushranks.append(1) newflushranks = sorted(list(set(flushranks)),reverse=True) while len(newflushranks) >= 5: if newflushranks[0] == newflushranks[1]+1 and newflushranks[1] == newflushranks[2]+1 and newflushranks[2] == newflushranks[3]+1\ and newflushranks[3] == newflushranks[4]+1: return (True,newflushranks[0]) else: newflushranks = newflushranks[1:] return (False,0,0) return (False,0,0) ###################################################################### def three_of_a_kind_finder(pairranks): rankcounter = {14:0,13:0,12:0,11:0,10:0,9:0,8:0,7:0,6:0,5:0,4:0,3:0,2:0} for rank in pairranks: rankcounter[rank] += 1 threes = [] highcards = [] for card,amount in rankcounter.items(): if amount == 3: threes.append(card) if 0 < amount < 3: highcards.append(card) highcards.sort(reverse=True) if len(threes) >= 1: return (True,max(threes),highcards[:2]) return (False,0) ###################################################################### def one_pair_finder(pairranks): rankcounter = {14:0,13:0,12:0,11:0,10:0,9:0,8:0,7:0,6:0,5:0,4:0,3:0,2:0} for rank in pairranks: rankcounter[rank] += 1 highcards = [] pairsof2 = [] for card,amount in rankcounter.items(): if amount == 1: highcards.append(card) if amount == 2: pairsof2.append(card) if len(pairsof2) >=1: return (True,max(pairsof2),sorted(highcards,reverse=True)) else: return (False,0,0) ###################################################################### def highcard_finder(pairranks): highlist = (sorted(pairranks,reverse=True)) return highlist ###################################################################### def main(): playernum = 0 while playernum not in range(2,10): playernum = int(raw_input("Welcome to Simultron, How Many Players?")) listofplayers = [] for x in range(int(playernum)): listofplayers.append("player"+str(x+1)) for x in listofplayers: print "Welcome "+x startstack = 0 while startstack not in range(100,1000000,10): startstack = int(raw_input("What will the starting stack sizes be? (100-1000000 increments of 10) ")) bigblind = 19 while bigblind not in range(20,1000,20): bigblind = int(raw_input("What will the big blind start at? (20-1000, increments of 20) ")) deck1 = Deck() table1 = Table(bigblind) playas = dict((name, Player(stacksize=startstack)) for name in listofplayers) table1.fillseats(listofplayers,playas) table1.postblinds(playas,bigblind,deck1) if __name__ == "__main__": main() From mfthguven at gmail.com Tue Nov 4 10:36:54 2014 From: mfthguven at gmail.com (=?ISO-8859-1?Q?Fatih_G=FCven?=) Date: Tue, 4 Nov 2014 07:36:54 -0800 (PST) Subject: generating unique variable name via loops In-Reply-To: References: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> <8df0b347-0569-4505-95f8-12baf44a1743@googlegroups.com> Message-ID: <67a561c5-82db-4a98-a9d2-d5ea18a74c50@googlegroups.com> 4 Kas?m 2014 Sal? 17:01:17 UTC+2 tarihinde Peter Otten yazd?: > Fatih G?ven wrote: > > > 4 Kas?m 2014 Sal? 15:37:59 UTC+2 tarihinde Peter Otten yazd?: > >> Veek M wrote: > >> > >> > Fatih G?ven wrote: > >> > > >> >> 4 Kas?m 2014 Sal? 13:29:34 UTC+2 tarihinde Fatih G?ven yazd?: > >> >>> I want to generate a unique variable name for list using python. > >> >>> > >> >>> list1=... > >> >>> list2=... > >> > > >> > for x in range(1,10): > >> > exec("list%d = []" % x) > >> > >> Why would you do this? > > > > I have a structured and repetitive data. > > I was actually asking "Veek M". > > > I want to read a .txt file line > > by line and classified it to call easily. For example employee1 has a > > name, a salary, shift, age etc. and employee2 and other 101 employee have > > all of it. > > > > Call employee1.name or employee2.salary and assign it to a new variable, > > something etc. > > I can only repeat my previous advice. Instead of creating variables for > employee1, employee2, and so on make a list of employees: > > $ cat employees.txt > Peter,3000 > Paul,2000 > Mary,1000 > > $ cat employees.py > #!/usr/bin/env python3 > import csv > > class Employee: > def __init__(self, name, salary): > self.name = name > self.salary = salary > > if __name__ == "__main__": > employees = [] > with open("employees.txt") as f: > for row in csv.reader(f): > employees.append(Employee(row[0], int(row[1]))) > > for employee in employees: > print(employee.name, "-- salary:", employee.salary, "doubloons") > > $ python3 employees.py > Peter -- salary: 3000 doubloons > Paul -- salary: 2000 doubloons > Mary -- salary: 1000 doubloons > > You wouldn't want to reference Paul as employee2 -- what if the order in the > text file changed? Instead you can make a dict that maps name to employee... > > employees_by_name = {} > for employee in employees: > name = employee.name > if name in employees_by_name: > raise ValueError("duplicate name {}".format(name)) > employees_by_name[name] = employee > > and use that dict to look up an employee: > > while True: > name = input("enter a name ") > if name == "": > print("That's all folks") > break > if name not in employees_by_name: > print("unknown name") > else: > print("Salary:", employees_by_name[name].salary, "doubloons") > > $ python3 employees.py > Peter -- salary: 3000 doubloons > Paul -- salary: 2000 doubloons > Mary -- salary: 1000 doubloons > enter a name Peter > Salary: 3000 doubloons > enter a name Mary > Salary: 1000 doubloons > enter a name paul > unknown name > enter a name Paul > Salary: 2000 doubloons > enter a name > That's all folks > $ Thanks for your concern, I will try this. Actually, the main focus is that are there any other Paul in my team. So i want to create a simple ID for employee to distinguish two Paul. I belive that you have a solution for this. From __peter__ at web.de Tue Nov 4 11:06:25 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Nov 2014 17:06:25 +0100 Subject: generating unique variable name via loops References: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> <8df0b347-0569-4505-95f8-12baf44a1743@googlegroups.com> <67a561c5-82db-4a98-a9d2-d5ea18a74c50@googlegroups.com> Message-ID: Fatih G?ven wrote: > 4 Kas?m 2014 Sal? 17:01:17 UTC+2 tarihinde Peter Otten yazd?: >> Fatih G?ven wrote: >> >> > 4 Kas?m 2014 Sal? 15:37:59 UTC+2 tarihinde Peter Otten yazd?: >> >> Veek M wrote: >> >> >> >> > Fatih G?ven wrote: >> >> > >> >> >> 4 Kas?m 2014 Sal? 13:29:34 UTC+2 tarihinde Fatih G?ven yazd?: >> >> >>> I want to generate a unique variable name for list using python. >> >> >>> >> >> >>> list1=... >> >> >>> list2=... >> >> > >> >> > for x in range(1,10): >> >> > exec("list%d = []" % x) >> >> >> >> Why would you do this? >> > >> > I have a structured and repetitive data. >> >> I was actually asking "Veek M". >> >> > I want to read a .txt file line >> > by line and classified it to call easily. For example employee1 has a >> > name, a salary, shift, age etc. and employee2 and other 101 employee >> > have all of it. >> > >> > Call employee1.name or employee2.salary and assign it to a new >> > variable, something etc. >> >> I can only repeat my previous advice. Instead of creating variables for >> employee1, employee2, and so on make a list of employees: >> >> $ cat employees.txt >> Peter,3000 >> Paul,2000 >> Mary,1000 >> >> $ cat employees.py >> #!/usr/bin/env python3 >> import csv >> >> class Employee: >> def __init__(self, name, salary): >> self.name = name >> self.salary = salary >> >> if __name__ == "__main__": >> employees = [] >> with open("employees.txt") as f: >> for row in csv.reader(f): >> employees.append(Employee(row[0], int(row[1]))) >> >> for employee in employees: >> print(employee.name, "-- salary:", employee.salary, "doubloons") >> >> $ python3 employees.py >> Peter -- salary: 3000 doubloons >> Paul -- salary: 2000 doubloons >> Mary -- salary: 1000 doubloons >> >> You wouldn't want to reference Paul as employee2 -- what if the order in >> the text file changed? Instead you can make a dict that maps name to >> employee... >> >> employees_by_name = {} >> for employee in employees: >> name = employee.name >> if name in employees_by_name: >> raise ValueError("duplicate name {}".format(name)) >> employees_by_name[name] = employee >> >> and use that dict to look up an employee: >> >> while True: >> name = input("enter a name ") >> if name == "": >> print("That's all folks") >> break >> if name not in employees_by_name: >> print("unknown name") >> else: >> print("Salary:", employees_by_name[name].salary, "doubloons") >> >> $ python3 employees.py >> Peter -- salary: 3000 doubloons >> Paul -- salary: 2000 doubloons >> Mary -- salary: 1000 doubloons >> enter a name Peter >> Salary: 3000 doubloons >> enter a name Mary >> Salary: 1000 doubloons >> enter a name paul >> unknown name >> enter a name Paul >> Salary: 2000 doubloons >> enter a name >> That's all folks >> $ > > > Thanks for your concern, I will try this. Actually, the main focus is that > are there any other Paul in my team. So i want to create a simple ID for > employee to distinguish two Paul. I belive that you have a solution for > this. The easiest is to use the index: #!/usr/bin/env python3 import csv class Employee: def __init__(self, name, salary): self.name = name self.salary = salary if __name__ == "__main__": employees = [] with open("employees.txt") as f: for row in csv.reader(f): employees.append(Employee(row[0], int(row[1]))) for index, employee in enumerate(employees, 1): print("#{}, name: {}".format(index, employee.name)) while True: index = input("enter an index (1...{}) ".format(len(employees))) if index == "": print("That's all folks") break index = int(index) -1 employee = employees[index] print("Name: {0.name}, Salary: {0.salary}".format(employee)) If the ID must stay the same for two runs of the script you have to put it into the text file as another column. However, you are soon reaching territory where a database is more convenient than a text file. From vek.m1234 at gmail.com Tue Nov 4 10:15:09 2014 From: vek.m1234 at gmail.com (Veek M) Date: Tue, 04 Nov 2014 21:45:09 +0630 Subject: Python extension using a C library with one 'hello' function References: Message-ID: Jason Swails wrote: > I've submitted a PR to your github repo showing you the changes > necessary to get your module working on my computer. Segfaults :p which is an improvement :) open("./_hello.cpython-32mu.so", O_RDONLY) = 5 read(5, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\300\7\0\0\0\0\0\0"..., 832) = 832 fstat(5, {st_mode=S_IFREG|0755, st_size=19217, ...}) = 0 getcwd("/root/github/junk/hello", 128) = 24 mmap(NULL, 2101544, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 5, 0) = 0x7f65daea5000 mprotect(0x7f65daea6000, 2093056, PROT_NONE) = 0 mmap(0x7f65db0a5000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED| MAP_DENYWRITE, 5, 0) = 0x7f65db0a5000 close(5) = 0 mprotect(0x7f65db0a5000, 4096, PROT_READ) = 0 --- SIGSEGV (Segmentation fault) @ 0 (0) --- From vek.m1234 at gmail.com Tue Nov 4 10:16:53 2014 From: vek.m1234 at gmail.com (Veek M) Date: Tue, 04 Nov 2014 21:46:53 +0630 Subject: Python extension using a C library with one 'hello' function References: <5458C1DF.9010802@syntonetic.com> Message-ID: S?ren wrote: > import ctypes Hi, yeah i kind of liked it - still reading the docs though, Beazley has the Python.h solution so I though I'd try that first. From jason.swails at gmail.com Tue Nov 4 11:28:57 2014 From: jason.swails at gmail.com (Jason Swails) Date: Tue, 04 Nov 2014 11:28:57 -0500 Subject: Python extension using a C library with one 'hello' function In-Reply-To: References: Message-ID: <1415118537.25472.6.camel@gmail.com> On Tue, 2014-11-04 at 21:45 +0630, Veek M wrote: > Jason Swails wrote: > > > I've submitted a PR to your github repo showing you the changes > > necessary to get your module working on my computer. > > Segfaults :p which is an improvement :) What operating system are you running this on? It works fine for me on Linux: bash$ ls hello.c hello.h hello.py pyhello.c setup.py bash$ python3.4 setup.py build_ext --inplace running build_ext building '_hello' extension creating build creating build/temp.linux-x86_64-3.4 x86_64-pc-linux-gnu-gcc -pthread -fPIC -I/usr/include/python3.4 -c pyhello.c -o build/temp.linux-x86_64-3.4/pyhello.o pyhello.c:15:5: warning: initialization from incompatible pointer type [enabled by default] {"hello", py_hello, METH_NOARGS, py_hello_doc}, ^ pyhello.c:15:5: warning: (near initialization for ?hellomethods[0].ml_meth?) [enabled by default] x86_64-pc-linux-gnu-gcc -pthread -fPIC -I/usr/include/python3.4 -c hello.c -o build/temp.linux-x86_64-3.4/hello.o x86_64-pc-linux-gnu-gcc -pthread -shared build/temp.linux-x86_64-3.4/pyhello.o build/temp.linux-x86_64-3.4/hello.o -L/usr/lib64 -lpython3.4 -o /home/swails/BugHunter/CAPI/Python/junk/hello/_hello.cpython-34.so bash$ python3.4 Python 3.4.1 (default, Aug 24 2014, 10:04:41) [GCC 4.7.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import hello >>> hello.hello() hello world 0 You can get rid of the warning by casting py_hello to (PyCFunction)... maybe that's causing your segfault? All the best, Jason From vek.m1234 at gmail.com Tue Nov 4 10:43:42 2014 From: vek.m1234 at gmail.com (Veek M) Date: Tue, 04 Nov 2014 22:13:42 +0630 Subject: Python extension using a C library with one 'hello' function References: Message-ID: Jason Swails wrote: > What operating system are you running this on? It works fine for me on > Linux: Wheezy Debian, Linux deathstar 3.2.0-4-amd64 #1 SMP Debian 3.2.60-1+deb7u3 x86_64 GNU/Linux gcc (Debian 4.7.2-5) 4.7.2 Python 3.2.3 I ran it through gdb - not very useful: (gdb) bt #0 0x000000000055e1bd in PyModule_Create2 () #1 0x000000000043a830 in _PyImport_LoadDynamicModule () #2 0x0000000000476d84 in ?? () #3 0x00000000004aa3f9 in ?? () #4 0x0000000000477010 in ?? () #5 0x000000000048ee8d in ?? () #6 0x00000000004a833b in PyObject_Call () #7 0x00000000004b88c9 in PyEval_EvalFrameEx () #8 0x00000000004cdee7 in PyEval_EvalCodeEx () strace -f python3.2 munmap(0x7f215d4b9000, 4096) = 0 stat("hello.py", {st_mode=S_IFREG|0644, st_size=22, ...}) = 0 stat("_hello", 0x7fff9bd38110) = -1 ENOENT (No such file or directory) stat("_hello.cpython-32mu.so", {st_mode=S_IFREG|0755, st_size=19217, ...}) = 0 open("_hello.cpython-32mu.so", O_RDONLY) = 4 fstat(4, {st_mode=S_IFREG|0755, st_size=19217, ...}) = 0 open("./_hello.cpython-32mu.so", O_RDONLY) = 5 read(5, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\300\7\0\0\0\0\0\0"..., 832) = 832 fstat(5, {st_mode=S_IFREG|0755, st_size=19217, ...}) = 0 getcwd("/root/github/junk/hello", 128) = 24 mmap(NULL, 2101544, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 5, 0) = 0x7f215b71c000 mprotect(0x7f215b71d000, 2093056, PROT_NONE) = 0 mmap(0x7f215b91c000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED| MAP_DENYWRITE, 5, 0) = 0x7f215b91c000 close(5) = 0 mprotect(0x7f215b91c000, 4096, PROT_READ) = 0 --- SIGSEGV (Segmentation fault) @ 0 (0) --- +++ killed by SIGSEGV +++ Segmentation fault From romapera15 at gmail.com Tue Nov 4 11:45:32 2014 From: romapera15 at gmail.com (=?UTF-8?Q?fran=C3=A7ai_s?=) Date: Tue, 4 Nov 2014 13:45:32 -0300 Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? Message-ID: I intend to write in lowest level of computer programming as a hobby. It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? What is the lowest level of programming computers that you can write ? Is binary code? Is hex code? Is another machine code? Honestly do not know if it is true that there is another machine code beyond the binary and hex code. Is Assembly? From invalid at invalid.invalid Tue Nov 4 12:05:34 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 4 Nov 2014 17:05:34 +0000 (UTC) Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? References: Message-ID: On 2014-11-04, fran?ai s wrote: > I intend to write in lowest level of computer programming as a hobby. > > It is true that is impossible write in binary code, No. You can write in binary if you want. If I were going to do something like that I'd pick a CPU like a PDP11 with a nice simple, regular, orthogonal instruction set. That will minimize the amount of stuff you'll need to memorize. The MSP430 isn't bad either. > the lowest level of programming that you can write is in hex code? Hex is just a shorthand notation for binary where a group of 4 bits is represented by a single character 0-9,A-F, but it's the exact same "code": binary hex 0000 0 0001 1 0010 2 0011 3 0100 4 0101 5 0110 6 0111 7 1000 8 1001 9 1010 A 1011 B 1100 C 1101 D 1110 E 1111 F > What is the lowest level of programming computers that you can write ? > > Is binary code? > Is hex code? They're the same thing. I supposed I could write in hex/binary if I really wanted to. I did it once or twice in the distant past, but it's not something I'd consider fun. The lowest language I actually write code in is assembly. > Is another machine code? Honestly do not know if it is true that > there is another machine code beyond the binary and hex code. > Is Assembly? Assembly is small a step up from binary, where you enter keywords that are translated directly into binary using a simple lookup table. You still have to know all about the CPU's instructions, registers, modes, and so on the same as you do when writing in binary -- you just don't have to memorize exactly which bit patterns are used for which instructions. On many CPUs there is another layer below "binary" and that's the microcode that runs on the actual CPU gates. The microcode is a little program that interprets the "binary" code that you're talking about writing. The only people that write microcode are the design engieers where the CPU was designed. If you really want to write in "binary", you should probably first learn to program in assembly language as a way to understand the the CPU and it's instruction set and addressing modes. The assmebler will still do all sorts of bookkeeping and keep track of memory addresses for you so that when you insert or remove an instruction you don't have to manually adjust the addresses for the entire rest of the program. -- Grant Edwards grant.b.edwards Yow! A dwarf is passing out at somewhere in Detroit! gmail.com From vek.m1234 at gmail.com Tue Nov 4 11:09:58 2014 From: vek.m1234 at gmail.com (Veek M) Date: Tue, 04 Nov 2014 22:39:58 +0630 Subject: Python extension using a C library with one 'hello' function References: Message-ID: static PyMethodDef hellomethods[] = { {"hello", py_hello, METH_VARARGS, py_hello_doc}, {NULL, NULL, 0, NULL}, }; It's basically the METH_VARARGS field that's giving the problem. Switching it to NULL gives, SystemError: Bad call flags in PyCFunction_Call. METH_OLDARGS is no longer supported! and METH_NOARGS doesn't work in 3.2 From denismfmcmahon at gmail.com Tue Nov 4 12:14:26 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 4 Nov 2014 17:14:26 +0000 (UTC) Subject: generating unique variable name via loops References: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> <8df0b347-0569-4505-95f8-12baf44a1743@googlegroups.com> <95028c6b-b6d2-40ec-9cc7-557cc9e42342@googlegroups.com> Message-ID: On Tue, 04 Nov 2014 05:45:04 -0800, Fatih G?ven wrote: > 4 Kas?m 2014 Sal? 15:19:20 UTC+2 tarihinde Veek M yazd?: >> Fatih G?ven wrote: >> >> > 4 Kas?m 2014 Sal? 13:29:34 UTC+2 tarihinde Fatih G?ven yazd?: >> >> I want to generate a unique variable name for list using python. >> >> >> >> list1=... >> >> list2=... >> >> for x in range(1,10): >> exec("list%d = []" % x) > > This is okay but i can't use the method ".append" for example > list1.append("abc") This is one solution using a dictionary of lists to maintain the name association. It may not be the best method. It may not be the best solution for you. It may not be the answer your instructor is looking for, and it contains deliberate syntax errors. lists = {} for fn in filenames infile = open(fn, "r") lists[fn] = [] for line in infile lists[fn].append(line) infile.close() If you have to ask how to do this sort of thing, you probably shouldn't be coding employee data processing systems anyway! If this was a coding assignment for a course, you should have had sufficient instruction in the relevant algorithms and language features to be able to figure it out yourself. In either case, what not explain what you tried, what you expected it to do, and what it actually did. -- Denis McMahon, denismfmcmahon at gmail.com From denismfmcmahon at gmail.com Tue Nov 4 12:15:54 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 4 Nov 2014 17:15:54 +0000 (UTC) Subject: generating unique variable name via loops References: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> <8df0b347-0569-4505-95f8-12baf44a1743@googlegroups.com> Message-ID: On Tue, 04 Nov 2014 05:53:04 -0800, Fatih G?ven wrote: > Call employee1.name or employee2.salary and assign it to a new variable, > something etc. 1) Put the file into a database. 2) database calls -- Denis McMahon, denismfmcmahon at gmail.com From jason.swails at gmail.com Tue Nov 4 12:28:04 2014 From: jason.swails at gmail.com (Jason Swails) Date: Tue, 4 Nov 2014 12:28:04 -0500 Subject: Python extension using a C library with one 'hello' function In-Reply-To: References: Message-ID: On Tue, Nov 4, 2014 at 11:09 AM, Veek M wrote: > static PyMethodDef hellomethods[] = { > {"hello", py_hello, METH_VARARGS, py_hello_doc}, > {NULL, NULL, 0, NULL}, > }; > > It's basically the METH_VARARGS field that's giving the problem. Switching > it to NULL gives, > SystemError: Bad call flags in PyCFunction_Call. METH_OLDARGS is no longer > supported! > ?Yes, I got that problem too, which is why I switched it to METH_NOARGS. ? > and METH_NOARGS doesn't work in 3.2 > I ?t does for me: ? Python 3.2.5 (default, Aug 24 2014, 10:06:23) [GCC 4.7.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import hello >>> hello.hello() hello world 0 >>> ?As you can see -- this is a Python 3.2 built with GCC 4.7 (On Gentoo Linux). It also works on Python 3.1 and 3.0 (but obviously doesn't work for Python 2.X). I can't tell why you're having so many problems...? Try doing a "git clean -fxd" to make sure you don't have leftover files lying around somewhere that are causing grief. Also, you need to add "-g" to the compiler arguments to make sure you build with debug symbols if you want a meaningful traceback. Good luck, Jason -- Jason M. Swails BioMaPS, Rutgers University Postdoctoral Researcher -------------- next part -------------- An HTML attachment was scrubbed... URL: From vek.m1234 at gmail.com Tue Nov 4 11:33:03 2014 From: vek.m1234 at gmail.com (Veek M) Date: Tue, 04 Nov 2014 23:03:03 +0630 Subject: Python extension using a C library with one 'hello' function References: Message-ID: okay got it working - thanks Jason! The 3.2 docs are slightly different. From rustompmody at gmail.com Tue Nov 4 12:37:24 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 4 Nov 2014 09:37:24 -0800 (PST) Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: References: Message-ID: <9dad69d7-6d9c-4ed1-9b2b-d8573b5aa581@googlegroups.com> On Tuesday, November 4, 2014 10:19:36 PM UTC+5:30, fran?ai s wrote: > I intend to write in lowest level of computer programming as a hobby. > > It is true that is impossible write in binary code, the lowest level > of programming that you can write is in hex code? > > What is the lowest level of programming computers that you can write ? > > Is binary code? > > Is hex code? > > Is another machine code? Honestly do not know if it is true that there > is another machine code beyond the binary and hex code. > > Is Assembly? Machines of earlier years had something called microprogramming below the machine language level. After the advent of RISC machines (ie for the last 20 years or so) this is not available to a 'normal' user. [Where by 'normal' user I mean someone who is not an employee of Intel for example]. Classic book for this is Tanenbaum's Structured computer organization. Then below this is a bunch of layers (very remote from programming) which electronics folks deal with going upto the solid-state physics of silicon From robin at reportlab.com Tue Nov 4 12:50:05 2014 From: robin at reportlab.com (Robin Becker) Date: Tue, 04 Nov 2014 17:50:05 +0000 Subject: pkcs7 signing Message-ID: <545911CD.1060300@chamonix.reportlab.co.uk> Is there a way to do pkcs7 / 12 signing with python. I looked at various cryptographic packages, but it's not clear if any of them can do this. -- Robin Becker From sjmsoft at gmail.com Tue Nov 4 13:06:46 2014 From: sjmsoft at gmail.com (sjmsoft at gmail.com) Date: Tue, 4 Nov 2014 10:06:46 -0800 (PST) Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: References: Message-ID: Grant's statements are correct and his advice is sound. I would not waste my time writing machine code, even as a hobby (and not even if your other hobbies include juggling chain saws). It's too time-consuming, tedious, bug-prone, and eyeglass-prescription-enhancing. Programming in assembly language will show you how the machine really works, and is challenging enough for almost anyone. And it will help you truly appreciate a powerful high-level language like Python. I've written much assembly language, on two different architectures, over the past 35 years, and I'm glad I did. But these days I work in assembly language only when necessary (legacy code). Give me Python any day! Cheers, Steve J. Martin From ethan at stoneleaf.us Tue Nov 4 13:23:50 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 04 Nov 2014 10:23:50 -0800 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: Message-ID: <545919B6.7040007@stoneleaf.us> This list is for the development _of_ Python, not development _with_ Python. Try asking on Python List. (forwarding...) On 11/04/2014 08:52 AM, Roberto Mart?nez wrote: > > I am trying to replace dinamically the __call__ method of an object using setattr. > Example: > > $ cat testcall.py > class A: > def __init__(self): > setattr(self, '__call__', self.newcall) > > def __call__(self): > print("OLD") > > def newcall(self): > print("NEW") > > a=A() > a() > > I expect to get "NEW" instead of "OLD", but in Python 3.4 I get "OLD". > > $ python2.7 testcall.py > NEW > $ python3.4 testcall.py > OLD > > I have a few questions: > > - Is this an expected behavior? > - Is possible to replace __call__ dinamically in Python 3? How? In 2.7 that would be a classic class, about which I know little. In 3.x you have a new class, one which inherits from 'object'. When you replace __call__ you need to replace it the class, not on the instance: setattr(__self__.__class__, self.newcall) -- ~Ethan~ From sohcahtoa82 at gmail.com Tue Nov 4 13:24:53 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Tue, 4 Nov 2014 10:24:53 -0800 (PST) Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: References: Message-ID: On Tuesday, November 4, 2014 8:49:36 AM UTC-8, fran?ai s wrote: > I intend to write in lowest level of computer programming as a hobby. > > It is true that is impossible write in binary code, the lowest level > of programming that you can write is in hex code? > > What is the lowest level of programming computers that you can write ? > > Is binary code? > > Is hex code? > > Is another machine code? Honestly do not know if it is true that there > is another machine code beyond the binary and hex code. > > Is Assembly? I can't think of any reason why someone would WANT to program in binary/hex machine code. If you want to program in a language that is as close to the metal as you can get, just learn Assembly. It will save you many headaches, especially if you're planning on writing for x86 CPUs. The number of opcodes is absurd without even getting into 64-bit instructions, SSE, etc. From jason.swails at gmail.com Tue Nov 4 13:28:52 2014 From: jason.swails at gmail.com (Jason Swails) Date: Tue, 04 Nov 2014 13:28:52 -0500 Subject: Python extension using a C library with one 'hello' function In-Reply-To: References: Message-ID: <1415125732.25472.7.camel@gmail.com> On Tue, 2014-11-04 at 23:03 +0630, Veek M wrote: > okay got it working - thanks Jason! The 3.2 docs are slightly different. What did you need to do to get it working? From python.list at tim.thechases.com Tue Nov 4 10:05:30 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 4 Nov 2014 09:05:30 -0600 Subject: generating unique variable name via loops In-Reply-To: References: <8d3d202f-3bb8-4683-8dd7-b065fab06c34@googlegroups.com> <8df0b347-0569-4505-95f8-12baf44a1743@googlegroups.com> Message-ID: <20141104090530.546692e8@bigbox.christie.dr> On 2014-11-04 05:53, Fatih G?ven wrote: > > > for x in range(1,10): > > > exec("list%d = []" % x) > > > > Why would you do this? > > I have a structured and repetitive data. I want to read a .txt file > line by line and classified it to call easily. For example > employee1 has a name, a salary, shift, age etc. and employee2 and > other 101 employee have all of it. > > Call employee1.name or employee2.salary and assign it to a new > variable, something etc. -- This sounds remarkably like a CSV or tab-delimited file. If so, the way to do it would be import csv with open("data.txt", "rb") as f: dr = csv.DictReader(f) for row in dr: do_something(row["Name"], row["salary"]) If the file format is more complex, it's often useful to create a generator to simplify the logic: class Person: def __init__(self, name="", salary=0, shift="", ): self.name = name self.salary = salary self.shift = shift def various_person_methods(self, ...): pass def people_from_file(f): "build Person objects as you iterate over the file" for row in file: person = Person( ... ) yield person with open("data.txt", "r"): for person in people_from_file(f): do_something(person) You can then reuse that generator with multiple files if you need. -tkc From nomail at invalid.com Tue Nov 4 13:51:32 2014 From: nomail at invalid.com (ast) Date: Tue, 4 Nov 2014 19:51:32 +0100 Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: References: Message-ID: <5459203a$0$12772$426a74cc@news.free.fr> a ?crit dans le message de news:e5c95792-f81f-42b4-9996-5545f560781d at googlegroups.com... On Tuesday, November 4, 2014 8:49:36 AM UTC-8, fran?ai s wrote: >I can't think of any reason why someone would WANT >to program in binary/hex machine code. It happens if you design yourself a specialized microcoded machine, also known as a number cruncher and you dont want to developp assembly tools to program it. So you have to fill a memory with 0 and 1 It's sometimes the work of electronic engineers, chip designers. From robertomartinezp at gmail.com Tue Nov 4 14:01:38 2014 From: robertomartinezp at gmail.com (=?ISO-8859-1?Q?Roberto_Mart=EDnez?=) Date: Tue, 4 Nov 2014 20:01:38 +0100 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: <545919B6.7040007@stoneleaf.us> References: <545919B6.7040007@stoneleaf.us> Message-ID: Yikes, I didn't realize the difference in inheritance. The thing with this is tricky. I need the change in the instance, not in the class, because I have multiple instances and all of them must have different implementations of __call__. The workaround of calling a different method inside __call__ is not valid for my case because I want to change the *signature* of the function also -for introspection reasons. Thank you all. Best regards, Roberto (Ethan, sorry for posting to python-dev, I thought that it was an implementation detail of CPython 3.X) On Tue, Nov 4, 2014 at 7:23 PM, Ethan Furman wrote: > This list is for the development _of_ Python, not development _with_ > Python. > > Try asking on Python List. > > (forwarding...) > > > On 11/04/2014 08:52 AM, Roberto Mart?nez wrote: > >> >> I am trying to replace dinamically the __call__ method of an object using >> setattr. >> Example: >> >> $ cat testcall.py >> class A: >> def __init__(self): >> setattr(self, '__call__', self.newcall) >> >> def __call__(self): >> print("OLD") >> >> def newcall(self): >> print("NEW") >> >> a=A() >> a() >> >> I expect to get "NEW" instead of "OLD", but in Python 3.4 I get "OLD". >> >> $ python2.7 testcall.py >> NEW >> $ python3.4 testcall.py >> OLD >> >> I have a few questions: >> >> - Is this an expected behavior? >> - Is possible to replace __call__ dinamically in Python 3? How? >> > > In 2.7 that would be a classic class, about which I know little. > > In 3.x you have a new class, one which inherits from 'object'. When you > replace __call__ you need to replace it the class, not on the instance: > > setattr(__self__.__class__, self.newcall) > > -- > ~Ethan~ > -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip.montanaro at gmail.com Tue Nov 4 14:06:04 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Tue, 4 Nov 2014 13:06:04 -0600 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> Message-ID: On Tue, Nov 4, 2014 at 1:01 PM, Roberto Mart?nez wrote: > The workaround of calling a different method inside __call__ is not valid > for my case because I want to change the *signature* of the function also > -for introspection reasons. You could define __call__ like so: def __call__(self, *args, **kwds): self._my_call(*args, **kwds) then set self._my_call at runtime. Skip -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Tue Nov 4 14:09:14 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 04 Nov 2014 11:09:14 -0800 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> Message-ID: <5459245A.3020304@stoneleaf.us> On 11/04/2014 11:01 AM, Roberto Mart?nez wrote: > > (Ethan, sorry for posting to python-dev, I thought that it was an implementation detail of CPython 3.X) No worries. It's good practice to post here first, just in case. ;) -- ~Ethan~ From jeanmichel at sequans.com Tue Nov 4 14:10:29 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 4 Nov 2014 20:10:29 +0100 (CET) Subject: Code review In-Reply-To: Message-ID: <1957100274.2828058.1415128229768.JavaMail.root@sequans.com> ----- Original Message ----- > From: "C Smith" > To: python-list at python.org > Sent: Tuesday, 4 November, 2014 4:28:33 PM > Subject: Code review > > I was wondering if I could get some feedback on the biggest thing I > have done as an amateur Python coder. The sidepots algorithm isn't > correct yet, but I haven't worked on it in a while and thought I > would > get some advice before diving back in. > > import random, os > ################################################################## > class Table(object): > def __init__(self,bigblind=20,PLAYERNUM=0,pot=0,PLAYERORDER=None, > hand_done=0,\ > left_to_act=None,cost_to_play=0,in_hand=None,last_raise=0,cards_in_play=None,round='preflop'): > if cards_in_play is None: > cards_in_play = [] > if in_hand is None: > in_hand = [] > if PLAYERORDER is None: > PLAYERORDER = [] > if left_to_act is None: > left_to_act = [] [snip hundreds of code lines] - Most methods have too much code, split methods into more unitary logical functions. - For instance, add classes 'Hand' and 'Card' - not enough comments - have you written some tests? The code reached a reasonable size where tests would be very helpful (module unittest) - why do you use uppercase attributes ? like PLAYERORDER. These are not 'constants', you change them Example of (incomplete) Card and Hand implementation (python 2.7): class Card(object): """Card implementation.""" def __init__(self, suit, rank): self._suit = suit self._rank = rank # write test card1 == card2 def __eq__(self, other): return (self.suit, self.rank) == (other.suit, other.rank) # use cards as dict keys def __hash__(self): return hash(self.suit, self.rank) # will allow python to sort a list of cards def __lt__(self, other): return int(self) < int(other) def __int__(self): """Return the numerical value of a card""" # the dictionary is incomplete return {'1':1,'2':2,'J':11,'Q':12}[self.rank] def __str__(self): return '' % (self.rank, self.suit) # alias in case card.rank has more meaning than int(card) @property def rank(self): return int(self) # read only access to suit @property def suit(self): return self._suit class Hand(object): """Short incomplete example of Hand class""" def __init__(self): self._cards = [] def add(self, card): if not self.full: self._cards.append(card) if card.rank == 14: # it's an Ace # trick to get Ace considered as 1 as well self._cards.append(Card(card.suite, '1')) # generate the ordered sequence of cards, hiding the '1' cards @property def cards(self): return (card for card in sorted(self._cards) if card.rank > 1) # allow to write len(hand) def __len__(self): return len(list(self.cards)) #property def full(self): return len(self) == 5 # allow to write 'for card in hand:' def __iter__(self): return iter(self.cards) def remove(self, card): # and so on... Otherwise: replace if left_to_act is None: left_to_act = [] self.left_to_act = left_to_act by self.left_to_act = left_to_act or [] replace if ranky == 9 or ranky == 5 by if ranky in [9,5] replace if foo == True by if foo replace if len(self.left_to_act) == 0 by if self.left_to_act And much more... but honestly, there's too much code :) I'll let you chew on this one. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From ethan at stoneleaf.us Tue Nov 4 14:12:15 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 04 Nov 2014 11:12:15 -0800 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> Message-ID: <5459250F.5000104@stoneleaf.us> On 11/04/2014 11:01 AM, Roberto Mart?nez wrote: > Yikes, I didn't realize the difference in inheritance. > > The thing with this is tricky. I need the change in the instance, not in the class, because I have multiple instances > and all of them must have different implementations of __call__. > > The workaround of calling a different method inside __call__ is not valid for my case because I want to change the > *signature* of the function also -for introspection reasons. If you really absolutely positively have to have the signature be correct for each instance, you may to either look at a function creating factory, a class creating factory, or a meta-class. The first option may work if you don't need an actual class, both of the last two options will be creating different classes, probably with one instance each (unless you have several instances which could share the same __call__). -- ~Ethan~ From robertomartinezp at gmail.com Tue Nov 4 14:15:24 2014 From: robertomartinezp at gmail.com (=?ISO-8859-1?Q?Roberto_Mart=EDnez?=) Date: Tue, 4 Nov 2014 20:15:24 +0100 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> Message-ID: On Tue, Nov 4, 2014 at 8:06 PM, Skip Montanaro wrote: > > On Tue, Nov 4, 2014 at 1:01 PM, Roberto Mart?nez < > robertomartinezp at gmail.com> wrote: > >> The workaround of calling a different method inside __call__ is not valid >> for my case because I want to change the *signature* of the function also >> -for introspection reasons. > > > You could define __call__ like so: > > def __call__(self, *args, **kwds): > self._my_call(*args, **kwds) > This was my first approach, but it is not very informative to the user and I prefer to have arguments with descriptive names. We have to change __doc__ too, so this is not an ideal solution for me. I tried to implement __getattribute__, but is not called either. :( then set self._my_call at runtime. > > Skip > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From njs at pobox.com Tue Nov 4 14:23:03 2014 From: njs at pobox.com (Nathaniel Smith) Date: Tue, 4 Nov 2014 19:23:03 +0000 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> Message-ID: On Tue, Nov 4, 2014 at 7:15 PM, Roberto Mart?nez wrote: > > > On Tue, Nov 4, 2014 at 8:06 PM, Skip Montanaro > wrote: >> >> >> On Tue, Nov 4, 2014 at 1:01 PM, Roberto Mart?nez >> wrote: >>> >>> The workaround of calling a different method inside __call__ is not valid >>> for my case because I want to change the *signature* of the function also >>> -for introspection reasons. >> >> >> You could define __call__ like so: >> >> def __call__(self, *args, **kwds): >> self._my_call(*args, **kwds) > > > This was my first approach, but it is not very informative to the user and I > prefer to have arguments with descriptive names. We have to change __doc__ > too, so this is not an ideal solution for me. > > I tried to implement __getattribute__, but is not called either. :( I'd suggest starting a new thread on python-list (or stack overflow or whatever) explaining what the heck you're trying to do here and asking for higher-level advice/suggestions, because your current implementation strategy seems to have placed you on a path that is rapidly descending past "spaghetti" towards "tentacular". (Or alternatively I guess you could go all in: I?! I?! Metaclasses Fhtagn!) -n -- Nathaniel J. Smith Postdoctoral researcher - Informatics - University of Edinburgh http://vorpus.org From sohcahtoa82 at gmail.com Tue Nov 4 14:24:30 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Tue, 4 Nov 2014 11:24:30 -0800 (PST) Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: <5459203a$0$12772$426a74cc@news.free.fr> References: <5459203a$0$12772$426a74cc@news.free.fr> Message-ID: <39ed3434-2d1c-4d74-b20d-db8b346f1c7d@googlegroups.com> On Tuesday, November 4, 2014 10:51:53 AM UTC-8, ast wrote: > a ?crit dans le message de > news:e5c95792-f81f-42b4-9996-5545f560781d at googlegroups.com... > On Tuesday, November 4, 2014 8:49:36 AM UTC-8, fran?ai s wrote: > > > >I can't think of any reason why someone would WANT > >to program in binary/hex machine code. > > It happens if you design yourself a specialized microcoded > machine, also known as a number cruncher and you dont > want to developp assembly tools to program it. So you > have to fill a memory with 0 and 1 > It's sometimes the work of electronic engineers, chip > designers. Well, yeah, that's pretty obvious, but I think that's a bit outside the scope of this discussion. The OP didn't mention designing a chip. From toby at tobiah.org Tue Nov 4 14:29:14 2014 From: toby at tobiah.org (Tobiah) Date: Tue, 04 Nov 2014 11:29:14 -0800 Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: References: Message-ID: On 11/04/2014 08:45 AM, fran?ai s wrote: > I intend to write in lowest level of computer programming as a hobby. > > It is true that is impossible write in binary code, the lowest level > of programming that you can write is in hex code? > > What is the lowest level of programming computers that you can write ? > > Is binary code? > > Is hex code? My first computers at home were Z80 powered Timex's. I tried writing video games in BASIC, but the machines were to slow to animate anything at reasonable speeds. I knew about machine language from a high-school computer course (using and Apple IIe). I bought a book on the Z80, and started reading. My Z80 manual showed each 8-bit instruction's anatomy in Hex and binary. Some of the instructions used several bits to denote some aspect of the instruction. I got some graph paper, and started coding that way, using one square per bit, and one line per byte. I translated all the binary by brain into integer, and used BASIC programs to 'poke' the bytes into memory then execute at the starting address. This was all quite educational and extremely tedious. Eventually, when I found out that assemblers existed, I wrote a crude one in BASIC, and found that to be a luxury. Later when I got an Atari 800, and the assembler cartridge I actually wrote a working two player Tron type game in assembly. Having delved into all of this, I'd like to echo the sentiments of a previous poster, that assembly is really the place to start for a low level language. You get all of the control of machine language, with far less of the headaches. Depending on what you want out of your hobby, if a working program that is of some use is one of those things, then start with assembly. If you just want to geek out and write a program that can guess a number between 1 and 100 by using graph paper, then sure, go for binary writing. From anuragpatibandla7 at gmail.com Tue Nov 4 14:37:35 2014 From: anuragpatibandla7 at gmail.com (Anurag Patibandla) Date: Tue, 4 Nov 2014 11:37:35 -0800 (PST) Subject: Problem adding a Key Value pair Message-ID: <32931127-fc4d-4ea5-87eb-f763a4fdf52c@googlegroups.com> I am trying to add a key value pair of ("Priority":"1") to queue1, ("Priority":"2") to queue2, and ("Priority":"3") to queue3. When I just add ("Priority":"1") to queue1, it works. But when I run the above code, ("Priority":"3") is being added to all the queues. This looks trivial and I don't understand why this is happening. Is there something wrong with what I am doing? json_split = {} value = {"Status": "Submitted", "m_Controller": "Python"} a = range(31) del a[0] for i in a: json_split[i] = value keys = json_split.keys() order = list(keys) q1 = int(round(len(keys)*0.2)) q2 = int(round(len(keys)*0.3)) q3 = int(round(len(keys)*0.5)) b = [q1,q2,q3] n=0 threedicts = [] for i in b: queues = order[n:n+i] n = n+i lists = [(queues[j], json_split.get(queues[j])) for j in range(len(queues))] onedict = {} for q in queues: onedict[q] = json_split[q] threedicts.append (onedict) queue1, queue2, queue3 = threedicts keys1 = queue1.keys() for i in keys1: queue1[i]['Priority'] = ['1'] keys2 = queue2.keys() for j in keys2: queue2[j]['Priority'] = ['2'] keys3 = queue3.keys() for z in keys3: queue3[z]['Priority'] = ['3'] From ethan at stoneleaf.us Tue Nov 4 14:47:02 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 04 Nov 2014 11:47:02 -0800 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> Message-ID: <54592D36.2000708@stoneleaf.us> On 11/04/2014 11:23 AM, Nathaniel Smith wrote: > > (Or alternatively I guess you could go all in: I??! I??! Metaclasses Fhtagn!) Metaclasses aren't that bad! I've written one. And the dizzy spells are getting better! -- ~Ethan~ From invalid at invalid.invalid Tue Nov 4 14:46:40 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 4 Nov 2014 19:46:40 +0000 (UTC) Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? References: <5459203a$0$12772$426a74cc@news.free.fr> Message-ID: On 2014-11-04, ast wrote: > > a ?crit dans le message de > news:e5c95792-f81f-42b4-9996-5545f560781d at googlegroups.com... > On Tuesday, November 4, 2014 8:49:36 AM UTC-8, fran?ai s wrote: > > >>I can't think of any reason why someone would WANT >>to program in binary/hex machine code. > > It happens if you design yourself a specialized microcoded > machine, also known as a number cruncher and you dont > want to developp assembly tools to program it. It only takes a couple hours to write a half decent two-pass absolute assembler in Python. I've done it. There are also generic assember toolkits/frameworks available. Doing real work in binary is insane. I know people _think_ they're're only going to spend an hour writing "just this one" program in binary, so it's not worth spending a few hours developing tools. IME, they're always wrong. > So you have to fill a memory with 0 and 1 > > It's sometimes the work of electronic engineers, chip designers. -- Grant Edwards grant.b.edwards Yow! Did I say I was at a sardine? Or a bus??? gmail.com From nad at acm.org Tue Nov 4 14:55:00 2014 From: nad at acm.org (Ned Deily) Date: Tue, 04 Nov 2014 11:55:00 -0800 Subject: Idle on Mac issues References: <90cc9fbb-3c11-4e2b-bad2-5ee7fe51a7bc@googlegroups.com> Message-ID: In article , Andrea D'Amore wrote: > On 2014-11-04 12:43:59 +0000, Rustom Mody said: > > > I seem to be stuck with some issues of Idle on macs. > > The page https://www.python.org/download/mac/tcltk > > seems to talk only of Tcl/Tk versions 8.5 > > System's 8.5 should be enough, if not there's explicit mention of the > ActiveTcl distribution. The Tcl/Tk 8.5.x versions shipped by Apple since OS X 10.6, and including 10.10, lag behind the current releases of Tcl/Tk; all Apple 8.5 version have serious bugs that have been fixed upstream. The most serious involves an immediate, unrecoverable crash in Tk when typing a composition character in an edit window or the IDLE shell, for example option-u (to make an umlaut) with a US input method. That's why we strongly urge IDLE users to *not* use the Apple-supplied Tcl/Tk. (The Apple-supplied Tk 8.5 with OS X 10.6 is pretty much unusable with IDLE.) Unfortunately, it's not trivial nor advisable to modify the system-supplied Python to use a newer third-party Tcl/Tk. The Pythons provide by the python.org OS X binary installers will automatically use a third-party Tcl/Tk 8.5.x installed in /Library/Frameworks (like ActiveTcl 8.5) and fall back to the system Tcl/Tk 8.5 in /System/Library/Frameworks. Since Apple does not currently ship Tcl/Tk 8.6, the python.org OS X binary installer Pythons currently do not support 8.6, either. > > Macports seem to have at 8.6 > > https://www.macports.org/ports.php?by=library&substr=tcl > > But that won't likely be used by a binary python installation, unless > you're using python from MacPorts as well. Yes, but, if you are using MacPorts, you should use one of its Python anyway. Note that the MacPorts Tk 8.6 has two variants: +quartz (for the native Cocoa Tk) and +x11 (for a traditional X11-based Tk). Because of many odd implementation choices with X11 and X11 Tk on OS X, I do not recommend using the X11 Tk on OS X with IDLE. > I'm on 10.10 (happily) running MacPorts, I have system's python 2.7.6 > as well as 2.7.8 and 3.4.2 from MacPorts, these two built with Xquartz > support. > I can start the idle binary provided by all of those, the system's with > native GUI, and have working Options menu in all of them. BTW, there have been various tweaks to IDLE's Preferences and Options menus in recent releases of Python. You are well-advised to use the latest versions of Python, currently 3.4.2 and 2.7.8, to get the best experience with IDLE. > I'd suggest the people having issue to describe their issues here, with > details on the system version, python version, the exact command they > run and the error they get. Good suggestion. Also, it would be a good idea to check the Python bug tracker, bugs.python.org, for existing problem reports and to open new issues if none found. -- Ned Deily, nad at acm.org From python at mrabarnett.plus.com Tue Nov 4 15:19:32 2014 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Nov 2014 20:19:32 +0000 Subject: Problem adding a Key Value pair In-Reply-To: <32931127-fc4d-4ea5-87eb-f763a4fdf52c@googlegroups.com> References: <32931127-fc4d-4ea5-87eb-f763a4fdf52c@googlegroups.com> Message-ID: <545934D4.2000004@mrabarnett.plus.com> On 2014-11-04 19:37, Anurag Patibandla wrote: > > I am trying to add a key value pair of ("Priority":"1") to queue1, ("Priority":"2") to queue2, and ("Priority":"3") to queue3. > When I just add ("Priority":"1") to queue1, it works. > But when I run the above code, ("Priority":"3") is being added to all the queues. > This looks trivial and I don't understand why this is happening. Is there something wrong with what I am doing? > > json_split = {} > value = {"Status": "Submitted", "m_Controller": "Python"} > a = range(31) > del a[0] That's better as: a = range(1, 31) > for i in a: > json_split[i] = value Here the key will be whatever 'i' refers to (1..30) and the value will be the dict referred to by 'value'. Try adding the line: print json_split[1] is json_split[2] It'll print out 'True'; it's saying that they are the same dict. You want the values of json_split to be _separate_ dicts. The fix is simple. Just make a copy of the dict for each one: for i in a: json_split[i] = dict(value) [snip] From gordon at panix.com Tue Nov 4 15:35:20 2014 From: gordon at panix.com (John Gordon) Date: Tue, 4 Nov 2014 20:35:20 +0000 (UTC) Subject: Code review References: Message-ID: C Smith writes: > I was wondering if I could get some feedback on the biggest thing I > have done as an amateur Python coder. Comments. You need a *lot* more comments. Like, every line or two of code should have a comment explaining what is being accomplished. Seriously. Every line or two. Some blank lines wouldn't hurt either. Also it would be nice to define some of the terms you're using. What is a blind? What does "in front" mean? What is a "muck hand"? -- John Gordon Imagine what it must be like for a real medical doctor to gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'. From anuragpatibandla7 at gmail.com Tue Nov 4 15:56:53 2014 From: anuragpatibandla7 at gmail.com (Anurag Patibandla) Date: Tue, 4 Nov 2014 12:56:53 -0800 (PST) Subject: Problem adding a Key Value pair In-Reply-To: <32931127-fc4d-4ea5-87eb-f763a4fdf52c@googlegroups.com> References: <32931127-fc4d-4ea5-87eb-f763a4fdf52c@googlegroups.com> Message-ID: <1559df04-46f6-4cb9-a31a-4ca5fb22ac90@googlegroups.com> On Tuesday, November 4, 2014 2:37:49 PM UTC-5, Anurag Patibandla wrote: > I am trying to add a key value pair of ("Priority":"1") to queue1, ("Priority":"2") to queue2, and ("Priority":"3") to queue3. > When I just add ("Priority":"1") to queue1, it works. > But when I run the above code, ("Priority":"3") is being added to all the queues. > This looks trivial and I don't understand why this is happening. Is there something wrong with what I am doing? > > json_split = {} > value = {"Status": "Submitted", "m_Controller": "Python"} > a = range(31) > del a[0] > for i in a: > json_split[i] = value > keys = json_split.keys() > order = list(keys) > q1 = int(round(len(keys)*0.2)) > q2 = int(round(len(keys)*0.3)) > q3 = int(round(len(keys)*0.5)) > b = [q1,q2,q3] > n=0 > threedicts = [] > for i in b: > queues = order[n:n+i] > n = n+i > lists = [(queues[j], json_split.get(queues[j])) for j in range(len(queues))] > onedict = {} > for q in queues: > onedict[q] = json_split[q] > threedicts.append (onedict) > queue1, queue2, queue3 = threedicts > keys1 = queue1.keys() > for i in keys1: > queue1[i]['Priority'] = ['1'] > keys2 = queue2.keys() > for j in keys2: > queue2[j]['Priority'] = ['2'] > keys3 = queue3.keys() > for z in keys3: > queue3[z]['Priority'] = ['3'] Awesome! Thank you!! From anddamNOPSAM+gruppi at brapi.net Tue Nov 4 16:41:44 2014 From: anddamNOPSAM+gruppi at brapi.net (Andrea D'Amore) Date: Tue, 4 Nov 2014 22:41:44 +0100 Subject: Idle on Mac issues References: <90cc9fbb-3c11-4e2b-bad2-5ee7fe51a7bc@googlegroups.com> Message-ID: On 2014-11-04 19:55:00 +0000, Ned Deily said: > [?] all Apple 8.5 version have serious bugs that have been fixed > upstream. The most > serious involves an immediate, unrecoverable crash in Tk when typing a > composition character in an edit window or the IDLE shell [?] I stand corrected, I wasn't aware of these issues since I've always used the version available in ports. > Note that the MacPorts Tk 8.6 has two variants: +quartz (for > the native Cocoa Tk) and +x11 (for a traditional X11-based Tk).Because > of many odd implementation choices with X11 and X11 Tk on OS X, I do not > recommend using the X11 Tk on OS X with IDLE. I know, I'm using tk +x11 on purpose due to an issue with a specific program and the +quartz version. > You are well-advised to use the > latest versions of Python, currently 3.4.2 and 2.7.8, to get the best > experience with IDLE. I mentioned the slightly outdated 2.7.6 as that's the one shipped with the system and it's better not to tinker with it, IIRC there are system scripts relying on it. -- Andrea From t.v.werkhoven at gmail.com Tue Nov 4 17:37:02 2014 From: t.v.werkhoven at gmail.com (Theo van Werkhoven) Date: Tue, 04 Nov 2014 23:37:02 +0100 Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: References: Message-ID: <5459550E.5080809@van-werkhoven.nl> You could go to and get the Altair 8800 or IMSAI 8080 emulator. Run the program and toggle in binary code for these easy to use 8 bit processors. There's a short manual for the IMSAI on the same page and the manual plus instruction set for the Altair can be found in . Have fun with binary, I wish these machine were still available. Theo On 4-11-2014 17:45, fran?ai s wrote: > I intend to write in lowest level of computer programming as a hobby. > > It is true that is impossible write in binary code, the lowest level > of programming that you can write is in hex code? > > What is the lowest level of programming computers that you can write ? > > Is binary code? > > Is hex code? > > Is another machine code? Honestly do not know if it is true that there > is another machine code beyond the binary and hex code. > > Is Assembly? From sohcahtoa82 at gmail.com Tue Nov 4 19:09:34 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Tue, 4 Nov 2014 16:09:34 -0800 (PST) Subject: Code review In-Reply-To: References: Message-ID: <19b75713-78cd-4dad-976d-096653c058de@googlegroups.com> On Tuesday, November 4, 2014 12:35:32 PM UTC-8, John Gordon wrote: > C Smith writes: > > > I was wondering if I could get some feedback on the biggest thing I > > have done as an amateur Python coder. > > Comments. > > You need a *lot* more comments. > > Like, every line or two of code should have a comment explaining what is > being accomplished. Seriously. Every line or two. > > Some blank lines wouldn't hurt either. > > Also it would be nice to define some of the terms you're using. What is > a blind? What does "in front" mean? What is a "muck hand"? > > -- > John Gordon Imagine what it must be like for a real medical doctor to > gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'. A "blind" is a required bet that the two people sitting to the left of the button have to make before a hand begins. The first player pays the small blind and the second player pays the big blind, which is double the small blind. For tournament games, the blinds increase periodically. Mucking a hand means to throw your cards away without revealing them. In professional Poker, you typically give them to the dealer. "In front" just refers to table position which determines play order. From gandalf23 at mail.com Tue Nov 4 19:38:45 2014 From: gandalf23 at mail.com (Kiuhnm) Date: Tue, 4 Nov 2014 16:38:45 -0800 (PST) Subject: simple download manager In-Reply-To: References: <5d9b7957-ee57-4cc4-b4eb-7a933bad1a5e@googlegroups.com> Message-ID: <6c915ca3-0b07-432a-96c9-4689697bce31@googlegroups.com> On Tuesday, November 4, 2014 4:10:59 PM UTC+1, Kiuhnm wrote: > On Tuesday, November 4, 2014 4:00:51 PM UTC+1, Chris Angelico wrote: > > On Wed, Nov 5, 2014 at 1:53 AM, Kiuhnm wrote: > > > I wish to automate the downloading from a particular site which has some ADs and which requires to click on a lot of buttons before the download starts. > > > > > > What library should I use to handle HTTP? > > > Also, I need to support big files (> 1 GB) so the library should hand the data to me chunk by chunk. > > > > You may be violating the site's terms of service, so be aware of what > > you're doing. > > > > This could be a really simple job (just figure out what the last HTTP > > query is, and replicate that), or it could be insanely complicated > > (crypto, JavaScript, and/or timestamped URLs could easily be > > involved). To start off, I would recommend not writing a single like > > of Python code, but just pulling up Mozilla Firefox with Firebug, or > > Google Chrome with in-built inspection tools, or some equivalent, and > > watching the exact queries that go through. Once you figure out what > > queries are happening, you can figure out how to do them in Python. > > > > ChrisA > > It'll be tricky. I'm sure of that, but if the browser can do it, so can I :) > Fortunately, there are no captchas. There are no captcha but the site is behind cloudflare (DDOS protection). Anyway, I now know what to do. To deal with cloudflare's javascript challenge I'm going to use jsdb, a neat little javascript interpreter. By the way, I'm using requests instead of urllib, but I need to figure out how to download and write to disk big files. From peterirbizon at gmail.com Tue Nov 4 21:07:58 2014 From: peterirbizon at gmail.com (Peter Irbizon) Date: Wed, 5 Nov 2014 03:07:58 +0100 Subject: detect mouse pointer type Message-ID: Hello, please how can I detect mouse pointer type? I would like to print every mouse pointer change (arrow, hand, ...) while moving my mouse over screen. How can I do this? (for now I need it for windows, but cross-platform solution is highly appreciated) Many thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gandalf23 at mail.com Tue Nov 4 21:05:12 2014 From: gandalf23 at mail.com (Kiuhnm) Date: Tue, 4 Nov 2014 18:05:12 -0800 (PST) Subject: check_output Message-ID: <85a6efa4-0634-40da-b861-1ba71a7457f1@googlegroups.com> When I call "subprocess.check_output()" I see the console window appear and disappear very quickly. Is there a way to stop the console from showing up at all? From gandalf23 at mail.com Tue Nov 4 21:07:48 2014 From: gandalf23 at mail.com (Kiuhnm) Date: Tue, 4 Nov 2014 18:07:48 -0800 (PST) Subject: check_output In-Reply-To: <85a6efa4-0634-40da-b861-1ba71a7457f1@googlegroups.com> References: <85a6efa4-0634-40da-b861-1ba71a7457f1@googlegroups.com> Message-ID: <8a346613-84ac-4999-8f17-ea928fc313d1@googlegroups.com> On Wednesday, November 5, 2014 3:05:32 AM UTC+1, Kiuhnm wrote: > When I call "subprocess.check_output()" I see the console window appear and disappear very quickly. Is there a way to stop the console from showing up at all? shell=True does the trick! From rosuav at gmail.com Tue Nov 4 21:37:22 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Nov 2014 13:37:22 +1100 Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: <0f2j5a5habfaknvme41qfe0g09onmtles9@4ax.com> References: <0f2j5a5habfaknvme41qfe0g09onmtles9@4ax.com> Message-ID: On Wed, Nov 5, 2014 at 1:30 PM, Dennis Lee Bieber wrote: > "machine code" typically implies an instruction set specific to that > machine... ALL computers operate in BINARY logic (a bit only holds 0 or 1). > How you get those bits into the computer is irrelevant. Bah, those zeroes and ones are just an abstraction! They work in voltages. Actually, those voltages are just an abstraction. They work in electrons. Not to mention that electrons are really abstractions too, in their own way... ChrisA From maxhowl86 at gmail.com Tue Nov 4 22:15:30 2014 From: maxhowl86 at gmail.com (Max Nathaniel Ho) Date: Tue, 4 Nov 2014 19:15:30 -0800 (PST) Subject: What is the difference between these two? (Assigning functions to variables) Message-ID: <79948f2a-df75-4161-8b78-450a0ba9f16b@googlegroups.com> Example 1 def compose_greet_func(): def get_message(): return "Hello there!" return get_message greet = compose_greet_func() print greet() Example 2 def greet(name): return "hello "+name greet_someone = greet print greet_someone("John" In Example 1, the function compoe_greet_func is assigned to the variable greet, and () is included at the end of the function. However, in Example 2, the function greet is assigned to the variable greet_someone but () is excluded at the end of the function. Does the () matter when assigning functions to variables? Thank you! From maxhowl86 at gmail.com Tue Nov 4 22:17:35 2014 From: maxhowl86 at gmail.com (Max Nathaniel Ho) Date: Tue, 4 Nov 2014 19:17:35 -0800 (PST) Subject: What is the difference between these two? (Assigning functions to variables) In-Reply-To: <79948f2a-df75-4161-8b78-450a0ba9f16b@googlegroups.com> References: <79948f2a-df75-4161-8b78-450a0ba9f16b@googlegroups.com> Message-ID: <3de3eb9f-f0ae-494d-973f-0b9829af54d7@googlegroups.com> Just to be clear, I was referring to these two lines greet = compose_greet_func() greet_someone = greet On Wednesday, November 5, 2014 11:15:46 AM UTC+8, Max Nathaniel Ho wrote: > Example 1 > > def compose_greet_func(): > def get_message(): > return "Hello there!" > > return get_message > > greet = compose_greet_func() > print greet() > > > Example 2 > > def greet(name): > return "hello "+name > > greet_someone = greet > print greet_someone("John" > > In Example 1, the function compoe_greet_func is assigned to the variable greet, and () is included at the end of the function. > > However, in Example 2, the function greet is assigned to the variable greet_someone but () is excluded at the end of the function. > > Does the () matter when assigning functions to variables? > > Thank you! From wuwei23 at gmail.com Wed Nov 5 00:28:43 2014 From: wuwei23 at gmail.com (alex23) Date: Wed, 05 Nov 2014 15:28:43 +1000 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: Message-ID: On 11/04/2014 08:52 AM, Roberto Mart?nez wrote: >> I am trying to replace dinamically the __call__ method of an object >> using setattr. >> Example: >> >> $ cat testcall.py >> class A: >> def __init__(self): >> setattr(self, '__call__', self.newcall) >> >> def __call__(self): >> print("OLD") >> >> def newcall(self): >> print("NEW") >> >> a=A() >> a() >> >> I expect to get "NEW" instead of "OLD", but in Python 3.4 I get "OLD". Given that special methods can only be replaced on the class and not the instance, you could create a new version of the class within __init__ and assign it to the instance: class A: def __init__(self, call_method=None): if call_method: methods = {'__call__': call_method} self.__class__ = type('Custom_A', (A,), ) def __call__(self): return 'original' >> a = A() >> a() "old" >> b = A(lambda self: 'new') >> b() "new" From cs at zip.com.au Wed Nov 5 00:59:40 2014 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 5 Nov 2014 16:59:40 +1100 Subject: What is the difference between these two? (Assigning functions to variables) In-Reply-To: <3de3eb9f-f0ae-494d-973f-0b9829af54d7@googlegroups.com> References: <3de3eb9f-f0ae-494d-973f-0b9829af54d7@googlegroups.com> Message-ID: <20141105055940.GA67315@cskk.homeip.net> On 04Nov2014 19:17, Max Nathaniel Ho wrote: >Just to be clear, I was referring to these two lines > >greet = compose_greet_func() > >greet_someone = greet Please don't top-post. Thanks. Your first assignment: greet = compose_greet_func() _calls_ (runs) the compose_greet_func and assigns its return value to greet. Your second assignment: greet_someone = greet assigns the current value of "greet", whatever that is, to "greet_someone". No function is called. Cheers, Cameron Simpson From illusiontechniques at gmail.com Wed Nov 5 01:23:39 2014 From: illusiontechniques at gmail.com (C Smith) Date: Tue, 4 Nov 2014 22:23:39 -0800 Subject: Code review In-Reply-To: <19b75713-78cd-4dad-976d-096653c058de@googlegroups.com> References: <19b75713-78cd-4dad-976d-096653c058de@googlegroups.com> Message-ID: >Jean-Michel wrote: >replace > if left_to_act is None: > left_to_act = [] > self.left_to_act = left_to_act >by > self.left_to_act = left_to_act or [] I read that with 2.7 that I had to initialize class variables to immutable types. I think because I was working with the lists before they had been altered and were still empty lists. I will mess around tomorrow with the classes you suggested as I have yet to make use of decorators. Thanks. I will work on putting some more comments in as well. On Tue, Nov 4, 2014 at 4:09 PM, wrote: > On Tuesday, November 4, 2014 12:35:32 PM UTC-8, John Gordon wrote: >> C Smith writes: >> >> > I was wondering if I could get some feedback on the biggest thing I >> > have done as an amateur Python coder. >> >> Comments. >> >> You need a *lot* more comments. >> >> Like, every line or two of code should have a comment explaining what is >> being accomplished. Seriously. Every line or two. >> >> Some blank lines wouldn't hurt either. >> >> Also it would be nice to define some of the terms you're using. What is >> a blind? What does "in front" mean? What is a "muck hand"? >> >> -- >> John Gordon Imagine what it must be like for a real medical doctor to >> gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'. > > A "blind" is a required bet that the two people sitting to the left of the button have to make before a hand begins. The first player pays the small blind and the second player pays the big blind, which is double the small blind. For tournament games, the blinds increase periodically. > > Mucking a hand means to throw your cards away without revealing them. In professional Poker, you typically give them to the dealer. > > "In front" just refers to table position which determines play order. > -- > https://mail.python.org/mailman/listinfo/python-list From cs at zip.com.au Wed Nov 5 01:39:22 2014 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 5 Nov 2014 17:39:22 +1100 Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: <39ed3434-2d1c-4d74-b20d-db8b346f1c7d@googlegroups.com> References: <39ed3434-2d1c-4d74-b20d-db8b346f1c7d@googlegroups.com> Message-ID: <20141105063922.GA62888@cskk.homeip.net> On 04Nov2014 11:24, sohcahtoa82 at gmail.com wrote: >On Tuesday, November 4, 2014 10:51:53 AM UTC-8, ast wrote: >> a ?crit dans le message de >> news:e5c95792-f81f-42b4-9996-5545f560781d at googlegroups.com... >> On Tuesday, November 4, 2014 8:49:36 AM UTC-8, fran?ai s wrote: >> >I can't think of any reason why someone would WANT >> >to program in binary/hex machine code. >> >> It happens if you design yourself a specialized microcoded >> machine, also known as a number cruncher and you dont >> want to developp assembly tools to program it. So you >> have to fill a memory with 0 and 1 >> It's sometimes the work of electronic engineers, chip >> designers. > >Well, yeah, that's pretty obvious, but I think that's a bit outside the scope of this discussion. The OP didn't mention designing a chip. Bah! He asked if there were lower levels than binary. Ergo: chip design! (And microcode, the intermediate layer. Or one of the layers, depending where you draw the line.) Should we stop before we reach the quantum foam of spacetime? Cheers, Cameron Simpson From dieter at handshake.de Wed Nov 5 01:40:03 2014 From: dieter at handshake.de (dieter) Date: Wed, 05 Nov 2014 07:40:03 +0100 Subject: pkcs7 signing References: <545911CD.1060300@chamonix.reportlab.co.uk> Message-ID: <87bnomi20s.fsf@handshake.de> Robin Becker writes: > Is there a way to do pkcs7 / 12 signing with python. Have you checked whether "OpenSSL" supports this kind of signing? If it does, then you likely can use this via several Python wrappings for "OpenSSL". From vek.m1234 at gmail.com Wed Nov 5 00:58:10 2014 From: vek.m1234 at gmail.com (Veek M) Date: Wed, 05 Nov 2014 12:28:10 +0630 Subject: Python, VIM: namespace, scope, life of a python object stuck in a << HERE Message-ID: If i have two functions: function! foo() python3 << HERE import mylib pass HERE function! bar() python3 << HERE import mylib pass HERE The src says: 1. Python interpreter main program 3. Implementation of the Vim module for Python So, is the python interpreter embedded in vim AND additionally, are separate extensions to python provided (wrapper functions for the VIM API). Mixed bindings? How many times is mylib compiled to bytecode and loaded? Does each vimscript function get its own mylib - can I instantiate something and expect it to be visible in the other function? I have a bunch of leader (\)-functions that share similar code and act on the same buffer so I wanted to know if I could reuse that data-structure. How many times is the interpreter loaded into memory: once obviously at vim runtime. From rosuav at gmail.com Wed Nov 5 02:09:51 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Nov 2014 18:09:51 +1100 Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: <20141105063922.GA62888@cskk.homeip.net> References: <39ed3434-2d1c-4d74-b20d-db8b346f1c7d@googlegroups.com> <20141105063922.GA62888@cskk.homeip.net> Message-ID: On Wed, Nov 5, 2014 at 5:39 PM, Cameron Simpson wrote: > Bah! He asked if there were lower levels than binary. Ergo: chip design! > (And microcode, the intermediate layer. Or one of the layers, depending > where you draw the line.) Should we stop before we reach the quantum foam of > spacetime? Certainly not. We keep going below electrons, and find ourselves in Quantumland. It's like Wonderland, only... uhh... actually, it's just like Wonderland. Pick up a book called "Alice in Quantumland" by Robert Gilmore - it's worth reading. ChrisA From maxhowl86 at gmail.com Wed Nov 5 02:33:34 2014 From: maxhowl86 at gmail.com (Max Nathaniel Ho) Date: Tue, 4 Nov 2014 23:33:34 -0800 (PST) Subject: What is the difference between these two? (Assigning functions to variables) In-Reply-To: References: <3de3eb9f-f0ae-494d-973f-0b9829af54d7@googlegroups.com> Message-ID: On Wednesday, November 5, 2014 2:00:08 PM UTC+8, Cameron Simpson wrote: > On 04Nov2014 19:17, Max Nathaniel Ho wrote: > >Just to be clear, I was referring to these two lines > > > >greet = compose_greet_func() > > > >greet_someone = greet > > Please don't top-post. Thanks. > > Your first assignment: > > greet = compose_greet_func() > > _calls_ (runs) the compose_greet_func and assigns its return value to greet. > > Your second assignment: > > greet_someone = greet > > assigns the current value of "greet", whatever that is, to "greet_someone". No > function is called. > > Cheers, > Cameron Simpson Apologies about the top posting. Ahh okay, thank you for your explanation From __peter__ at web.de Wed Nov 5 02:44:13 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Nov 2014 08:44:13 +0100 Subject: Python, VIM: namespace, scope, life of a python object stuck in a << HERE References: Message-ID: Veek M wrote: > If i have two functions: > > function! foo() > python3 << HERE > import mylib > pass > HERE > > function! bar() > python3 << HERE > import mylib > pass > HERE > > The src says: > > 1. Python interpreter main program > 3. Implementation of the Vim module for Python > > So, is the python interpreter embedded in vim AND additionally, are > separate extensions to python provided (wrapper functions for the VIM > API). Mixed bindings? > > How many times is mylib compiled to bytecode and loaded? Does each > vimscript function get its own mylib - can I instantiate something and > expect it to be visible in the other function? I have a bunch of leader > (\)-functions that share similar code and act on the same buffer so I > wanted to know if I could reuse that data-structure. How many times is the > interpreter loaded into memory: once obviously at vim runtime. I'm not a vim user and I only got to work something similar with Python 2. I put print "hello" into mylib.py and saw when it was printed with the following script: function! Foo() python << HERE import sys sys.path.append(".") import mylib HERE endfunction function! Bar() python << HERE import mylib HERE endfunction :so vimscript.txt :call Foo() --> hello :call Bar() --> (nothing) Conclusion: both functions share the same Python interpreter. With a function containing import os print os.getpid() you can also see that the Python interpreter runs in the same process as vim. From jeanmichel at sequans.com Wed Nov 5 04:48:01 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 5 Nov 2014 10:48:01 +0100 (CET) Subject: Code review In-Reply-To: Message-ID: <1201991867.2902893.1415180881716.JavaMail.root@sequans.com> ----- Original Message ----- > From: "C Smith" > I read that with 2.7 that I had to initialize class variables to > immutable types. I think because I was working with the lists before > they had been altered and were still empty lists. I will mess around > tomorrow with the classes you suggested as I have yet to make use of > decorators. Thanks. The problem you referring too is probably the default value in *function definition*. Never write class Foo(object): def __init__(self, bar=[]): self.bar = bar The empty list is evaluated at the function definition and will be shared by all instances of the class. What you can do is class Foo(object): def __init__(self, bar=None): # None is immutable self.bar = bar or [] On a completely unrelated topic: I think you are using too much of default values for you arguments. I tend to use them only for keeping something backward compatible. Otherwise, use positional arguments, remember that explicit is better than implicit. Rememer your Table class: class Table(object): def __init__(self,bigblind=20,PLAYERNUM=0,pot=0,PLAYERORDER=None, hand_done=0, left_to_act=None,cost_to_play=0,in_hand=None,last_raise=0,cards_in_play=None,round='preflop'): You do not need to to pass all attribute initializers to your init method. For instance PLAYERNUM, which should be lowercase by the way, is clearly not intended to be set at the Table creation, it is something changed when filling seats. Actually, since you've created your table this way: table1=Table(bingblind=1) It probably means that your table __init__ method should look like: def __init__(self, bigblind): self.bigblind= bigblind self.hand_one = False self.left_to_act = [] # etc... By the way, avoid using directly 1 and 0 for coding booleans, use True and False (see hand_one attribute). JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From robin at reportlab.com Wed Nov 5 05:14:21 2014 From: robin at reportlab.com (Robin Becker) Date: Wed, 05 Nov 2014 10:14:21 +0000 Subject: pkcs7 signing In-Reply-To: <87bnomi20s.fsf@handshake.de> References: <545911CD.1060300@chamonix.reportlab.co.uk> <87bnomi20s.fsf@handshake.de> Message-ID: <5459F87D.90909@chamonix.reportlab.co.uk> On 05/11/2014 06:40, dieter wrote: > Robin Becker writes: > >> Is there a way to do pkcs7 / 12 signing with python. > > Have you checked whether "OpenSSL" supports this kind of signing? > If it does, then you likely can use this via several Python wrappings > for "OpenSSL". > I checked that the openssl library does have a call for this, however, I cannot see this exposed in either the cryptography or py2crypto packages. The code may be in there, but I don't see it obviously exposed. I think m2crypto might do the job, but building it for windows is a pain and I probably have to build it 6 times ie 32 & 64 bits x 2.7 3.3 & 3.4. There are pre-built versions of openssl, but that's also a moving target right now. -- Robin Becker From hexumg at gmail.com Wed Nov 5 05:44:35 2014 From: hexumg at gmail.com (Eugene) Date: Wed, 05 Nov 2014 13:44:35 +0300 Subject: Regex substitution trouble References: <8c1c1b7f-d121-4f3d-adf9-8262ddd8f102@googlegroups.com> Message-ID: massi_srb at msn.com wrote: > Hi everyone, > > I'm not really sure if this is the right place to ask about regular > expressions, but since I'm usin python I thought I could give a try :-) > Here is the problem, I'm trying to write a regex in order to substitute > all the occurences in the form $"somechars" with another string. This is > what I wrote: > > newstring = re.sub(ur"""(?u)(\$\"[\s\w]+\")""", subst, oldstring) > > This works pretty well, but it has a problem, I would need it also to > handle the case in which the internal string contains the double quotes, > but only if preceeded by a backslash, that is something like > $"somechars_with\\"doublequotes". Can anyone help me to correct it? > > Thanks in advance! Hi! Next snippet works for me: re.sub(r'\$"([\s\w]+(\\")*[\s\w]+)+"', 'noop', r'$"te\"sts\"tri\"ng"') From webmailgroups at gmail.com Wed Nov 5 06:00:16 2014 From: webmailgroups at gmail.com (Ivan Evstegneev) Date: Wed, 5 Nov 2014 13:00:16 +0200 Subject: Understanding "help" command description syntax - explanation needed Message-ID: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> Hello everyone, I'm a Python beginner and just getting familiar with it. (I need it for my EE B.Sc. project) For the learning purposes I use IDLE and (Learning Python by written by Mark Lutz). Let's say that I have some earlier experience with C language, but still Python is a different one ))) Anyway, the question I would like to ask is about understanding "help" contents. It may look to obvious and even a dumb question, but still I need your help. Here is a brief background with example in order to introduce my problem in more clear way: Suppose I get some list created: >>>L=[i for i in range(1,15,2)] As it can be seen, this is the odd numbers list: [1, 3, 5, 7, 9, 11, 13] Supppose I need to check the occurrence of number 7, in this case I'll just write: >>>L.index(7) The result is :3 So here is the question itself: If I use the help command to check the "range" command I get this info: range(stop) -> range object range(start, stop[, step]) -> range object As you've seen in my example I used range(1,15,2). But this knowledge I got from googling a couple of sites. I still can't understand the "help" command description. For instance, how do I need to understand that (start,stop[,step]) it's just a three numbers? What do those brackets--> [,] mean? The same about "str.replace" command, where I get this: S.replace(old, new[, count]) - using this description I can't really understand how to write the "replace" function parameters. So I googled it up and found this example in order to get more clear understanding of command use. str = "this is string example....wow!!! this is really string" print str.replace("is", "was") print str.replace("is", "was", 3) The result: thwas was string example....wow!!! thwas was really string thwas was string example....wow!!! thwas is really string But still how do I know that those "old, new" are the strings and [,count] just a number? I mean, it was more naturally(as a baginner) to me to write str.replace(is,was[,3]) and that's all. Finally, as for my opinion, this is a lame way to learn "what a command do" by constantly googling it for examples. I need to get more familiar with "help", but the main problem, is that I couldn't find any suitable explanations/tutorials about "help" syntax and etc. (maybe didn't search well). Any explanations/links will be greatly appreciated. I need some help for "help" ^_^ Thanks in advance, Ivan. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Wed Nov 5 06:55:00 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 5 Nov 2014 12:55:00 +0100 (CET) Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> Message-ID: <88543346.5460.1415188500802.JavaMail.root@sequans.com> ---- Original Message ----- > From: "Ivan Evstegneev" > To: python-list at python.org > Sent: Wednesday, 5 November, 2014 12:00:16 PM > Subject: Understanding "help" command description syntax - explanation needed > So here is the question itself: > > If I use the help command to check the ?range? command I get this > info: > > > > range(stop) -> range object > > range(start, stop[, step]) -> range object With python 2.7, when I type help(range), I get """ Help on built-in function range in module __builtin__: range(...) range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. """ range([start,] stop[, step]) tells you how to call the range function, there's a start, stop and step argument. The purpose of these arguments are given by the longer description. brackets [] means that the argument is optional. Though there's nothing wrong with googling the function for help, I'm doing it all the time. Actually, the python documentation is a better place to get help on a particular function, just make sure you hit the correct version, for either python 2 or 3: https://docs.python.org/2/library/functions.html#range I'm using python's help function only when working offline. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From lordvital21 at gmail.com Wed Nov 5 06:58:33 2014 From: lordvital21 at gmail.com (lordvital21 at gmail.com) Date: Wed, 5 Nov 2014 03:58:33 -0800 (PST) Subject: I need algorithm for my task Message-ID: <50a7df31-ee6c-45f5-9dd8-6ac895ec46cf@googlegroups.com> I have line 'pythonpythonpyth'. How do I know which word is the foundation line?. Other examples: "pythonpythonpyth" is python "DOLORIUMD" is DOLORIUM "HELLOLHELLO" is HELLOL "thewordword" is thewordword I need to know whether the word in the text is repeated and get it. This will be the key. From breamoreboy at yahoo.co.uk Wed Nov 5 07:04:01 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 05 Nov 2014 12:04:01 +0000 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: <88543346.5460.1415188500802.JavaMail.root@sequans.com> References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <88543346.5460.1415188500802.JavaMail.root@sequans.com> Message-ID: On 05/11/2014 11:55, Jean-Michel Pichavant wrote: > ---- Original Message ----- >> From: "Ivan Evstegneev" >> To: python-list at python.org >> Sent: Wednesday, 5 November, 2014 12:00:16 PM >> Subject: Understanding "help" command description syntax - explanation needed >> So here is the question itself: >> >> If I use the help command to check the ?range? command I get this >> info: >> >> >> >> range(stop) -> range object >> >> range(start, stop[, step]) -> range object > > With python 2.7, when I type help(range), I get > > """ > Help on built-in function range in module __builtin__: > > range(...) > range([start,] stop[, step]) -> list of integers > > Return a list containing an arithmetic progression of integers. > range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. > When step is given, it specifies the increment (or decrement). > For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! > These are exactly the valid indices for a list of 4 elements. > """ > > range([start,] stop[, step]) tells you how to call the range function, there's a start, stop and step argument. > The purpose of these arguments are given by the longer description. > > brackets [] means that the argument is optional. > > Though there's nothing wrong with googling the function for help, I'm doing it all the time. > Actually, the python documentation is a better place to get help on a particular function, just make sure you hit the correct version, for either python 2 or 3: > > https://docs.python.org/2/library/functions.html#range > > I'm using python's help function only when working offline. > > JM > There is an issue on the bug tracker about the difference between help for range between Python 2 and 3, see http://bugs.python.org/issue22785 -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From webmailgroups at gmail.com Wed Nov 5 07:13:35 2014 From: webmailgroups at gmail.com (Ivan Evstegneev) Date: Wed, 5 Nov 2014 14:13:35 +0200 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: <88543346.5460.1415188500802.JavaMail.root@sequans.com> References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <88543346.5460.1415188500802.JavaMail.root@sequans.com> Message-ID: <000501cff8f1$ed99cc40$c8cd64c0$@gmail.com> Firtst of all thanks for reply. >>brackets [] means that the argument is optional. That's what I'm talking about (asking actually), where do you know it from? I mean, if there are some resources, which explain all these syntax abbreviations? The general concept. Like this one(just for example): class bytearray([source[, encoding[, errors]]]) --- What does it mean? Is that I can use it in optional way? Like: class bytearray(source) or class bytearray(encoding) ? or just write down all three of them? In which format do I do so? Sincerely, Ivan. -----Original Message----- From: Jean-Michel Pichavant [mailto:jeanmichel at sequans.com] Sent: Wednesday, November 5, 2014 13:55 To: Ivan Evstegneev Cc: python-list at python.org Subject: Re: Understanding "help" command description syntax - explanation needed ---- Original Message ----- > From: "Ivan Evstegneev" > To: python-list at python.org > Sent: Wednesday, 5 November, 2014 12:00:16 PM > Subject: Understanding "help" command description syntax - explanation > needed So here is the question itself: > > If I use the help command to check the ?range? command I get this > info: > > > > range(stop) -> range object > > range(start, stop[, step]) -> range object With python 2.7, when I type help(range), I get """ Help on built-in function range in module __builtin__: range(...) range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. """ range([start,] stop[, step]) tells you how to call the range function, there's a start, stop and step argument. The purpose of these arguments are given by the longer description. brackets [] means that the argument is optional. Though there's nothing wrong with googling the function for help, I'm doing it all the time. Actually, the python documentation is a better place to get help on a particular function, just make sure you hit the correct version, for either python 2 or 3: https://docs.python.org/2/library/functions.html#range I'm using python's help function only when working offline. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From rosuav at gmail.com Wed Nov 5 07:16:16 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Nov 2014 23:16:16 +1100 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> Message-ID: On Wed, Nov 5, 2014 at 10:00 PM, Ivan Evstegneev wrote: > range(start, stop[, step]) -> range object > > For instance, how do I need to understand that (start,stop[,step]) it?s > just a three numbers? > > What do those brackets--> [,] mean? The docs for range() in Python 3 do need improvement, as Mark said, although there's a bit more info than you see there. The exact text varies from one version to another, but underneath that first line should be something like: "Return a virtual sequence of numbers from start to stop by step." That should tell you a bit more, at least. As to the brackets, they're a common convention meaning "optional". This is much bigger than Python, so it's not actually explained anywhere. (I've no idea where someone would go to try to find info on these sorts of conventions. It's a little hard to do a Google search for symbols and their usages. But that's what mailing lists like this are for.) You can create a range object with two arguments (start and stop) or three (start, stop, and step). When an argument is optional, it usually has a default, and in this case, the default step is 1 - every integer will be included. Don't be afraid to ask questions. There are plenty of people here who know both Python and C (I'm one of them), and we're happy to help out. And hey, you might find you can contribute a better piece of help text for something, and then we can make it better for every future wonderer :) ChrisA From larry.martell at gmail.com Wed Nov 5 07:16:50 2014 From: larry.martell at gmail.com (Larry Martell) Date: Wed, 5 Nov 2014 07:16:50 -0500 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: <000501cff8f1$ed99cc40$c8cd64c0$@gmail.com> References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <88543346.5460.1415188500802.JavaMail.root@sequans.com> <000501cff8f1$ed99cc40$c8cd64c0$@gmail.com> Message-ID: On Wed, Nov 5, 2014 at 7:13 AM, Ivan Evstegneev wrote: > Firtst of all thanks for reply. > >>>brackets [] means that the argument is optional. > > That's what I'm talking about (asking actually), where do you know it from? I know it because I've been a programmer for 39 years. From rosuav at gmail.com Wed Nov 5 07:20:55 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Nov 2014 23:20:55 +1100 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: <000501cff8f1$ed99cc40$c8cd64c0$@gmail.com> References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <88543346.5460.1415188500802.JavaMail.root@sequans.com> <000501cff8f1$ed99cc40$c8cd64c0$@gmail.com> Message-ID: On Wed, Nov 5, 2014 at 11:13 PM, Ivan Evstegneev wrote: > That's what I'm talking about (asking actually), where do you know it from? > I mean, if there are some resources, which explain all these syntax abbreviations? The general concept. > > > Like this one(just for example): > class bytearray([source[, encoding[, errors]]]) --- What does it mean? > Is that I can use it in optional way? > Like: class bytearray(source) or class bytearray(encoding) ? > or just write down all three of them? > In which format do I do so? With consecutive defaults, like that, it's written as a nested series. You have three optional parts: the first is "source[, encoding[, errors]]", the second (completely inside that) is ", encoding[, errors]", and the third (also inside) is ", errors". The first one gives you two options: class bytearray() class bytearray(source[, encoding[, errors]]) Then that gives you two more options: class bytearray(source) class bytearray(source, encoding[, errors]) Which itself gives two options: class bytearray(source, encoding) class bytearray(source, encoding, errors) So what you actually have is four real, usable options: class bytearray() class bytearray(source) class bytearray(source, encoding) class bytearray(source, encoding, errors) Does that make sense? You're allowed to provide no options, or anywhere up to three, but they have to be the first N options. In this particular case, it doesn't make sense to provide the later options without also providing the earlier ones. The encoding and errors parameters affect how source is interpreted, and errors affects how the encoding copes with stuff it can't handle, so it wouldn't make sense to provide either without source, or source and errors without encoding. That's why it's written as a nested set of optional sections, rather than as a series of stand-alone options. ChrisA From rosuav at gmail.com Wed Nov 5 07:26:29 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Nov 2014 23:26:29 +1100 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: <000501cff8f1$ed99cc40$c8cd64c0$@gmail.com> References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <88543346.5460.1415188500802.JavaMail.root@sequans.com> <000501cff8f1$ed99cc40$c8cd64c0$@gmail.com> Message-ID: On Wed, Nov 5, 2014 at 11:13 PM, Ivan Evstegneev wrote: > That's what I'm talking about (asking actually), where do you know it from? > I mean, if there are some resources, which explain all these syntax abbreviations? The general concept. The best way to find clues about what the conventions mean is to find something that codifies them in some way. Like this: http://docopt.org/ That's talking about command-line arguments to an application, but a lot of the notations are the same. ChrisA From rosuav at gmail.com Wed Nov 5 07:29:31 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Nov 2014 23:29:31 +1100 Subject: I need algorithm for my task In-Reply-To: <50a7df31-ee6c-45f5-9dd8-6ac895ec46cf@googlegroups.com> References: <50a7df31-ee6c-45f5-9dd8-6ac895ec46cf@googlegroups.com> Message-ID: On Wed, Nov 5, 2014 at 10:58 PM, wrote: > I have line 'pythonpythonpyth'. How do I know which word is the foundation line?. > Other examples: > "pythonpythonpyth" is python > "DOLORIUMD" is DOLORIUM > "HELLOLHELLO" is HELLOL > "thewordword" is thewordword > > I need to know whether the word in the text is repeated and get it. This will be the key. This sounds like it's probably homework, so I won't actually give you the code, just a starting hint. Python lets you slice a string to get back a substring. Start with a really simple algorithm like "see if the first N letters are also the next N letters and so on until you pass the end of the string", then word that up into Python code. Later on, you can look into making it less naive, but start simple and work up from there. ChrisA From webmailgroups at gmail.com Wed Nov 5 07:31:56 2014 From: webmailgroups at gmail.com (Ivan Evstegneev) Date: Wed, 5 Nov 2014 14:31:56 +0200 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> Message-ID: <000601cff8f4$7dc40220$794c0660$@gmail.com> Chris, You got my point exactly. ^_^ This is not about a "range" command itself, but those conventions. Thanks. Larry, >> That's what I'm talking about (asking actually), where do you know it from? >>I know it because I've been a programmer for 39 years. I didn't intend to offence anyone here. Just asked a questions ^_^ -----Original Message----- From: Python-list [mailto:python-list-bounces+webmailgroups=gmail.com at python.org] On Behalf Of Chris Angelico Sent: Wednesday, November 5, 2014 14:16 Cc: python-list at python.org Subject: Re: Understanding "help" command description syntax - explanation needed On Wed, Nov 5, 2014 at 10:00 PM, Ivan Evstegneev wrote: > range(start, stop[, step]) -> range object > > For instance, how do I need to understand that (start,stop[,step]) > it?s just a three numbers? > > What do those brackets--> [,] mean? The docs for range() in Python 3 do need improvement, as Mark said, although there's a bit more info than you see there. The exact text varies from one version to another, but underneath that first line should be something like: "Return a virtual sequence of numbers from start to stop by step." That should tell you a bit more, at least. As to the brackets, they're a common convention meaning "optional". This is much bigger than Python, so it's not actually explained anywhere. (I've no idea where someone would go to try to find info on these sorts of conventions. It's a little hard to do a Google search for symbols and their usages. But that's what mailing lists like this are for.) You can create a range object with two arguments (start and stop) or three (start, stop, and step). When an argument is optional, it usually has a default, and in this case, the default step is 1 - every integer will be included. Don't be afraid to ask questions. There are plenty of people here who know both Python and C (I'm one of them), and we're happy to help out. And hey, you might find you can contribute a better piece of help text for something, and then we can make it better for every future wonderer :) ChrisA -- https://mail.python.org/mailman/listinfo/python-list From __peter__ at web.de Wed Nov 5 07:36:17 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Nov 2014 13:36:17 +0100 Subject: I need algorithm for my task References: <50a7df31-ee6c-45f5-9dd8-6ac895ec46cf@googlegroups.com> Message-ID: lordvital21 at gmail.com wrote: > I have line 'pythonpythonpyth'. How do I know which word is the foundation > line?. Other examples: > "pythonpythonpyth" is python > "DOLORIUMD" is DOLORIUM > "HELLOLHELLO" is HELLOL > "thewordword" is thewordword > > I need to know whether the word in the text is repeated and get it. This > will be the key. A simple approach that might work (I didn't implement it to verify): Look for other occurences of the first letter. If there are none you have the "foundation", if there are any, split the line before them and check if the rest of the line can be constructed as a (possibly truncated) repetition of the beginning. For fifafofifaf you'd have to check fi fafofifaf --> false fifa fofifaf --> false fifafo fifaf --> true so we don't care about fifafofi faf fifafofifa f From rosuav at gmail.com Wed Nov 5 07:41:01 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Nov 2014 23:41:01 +1100 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: <000601cff8f4$7dc40220$794c0660$@gmail.com> References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <000601cff8f4$7dc40220$794c0660$@gmail.com> Message-ID: On Wed, Nov 5, 2014 at 11:31 PM, Ivan Evstegneev wrote: >>> That's what I'm talking about (asking actually), where do you know it from? > >>>I know it because I've been a programmer for 39 years. > > I didn't intend to offence anyone here. Just asked a questions ^_^ Don't worry about offending people. Even if you do annoy one or two, there'll be plenty of us who know to be patient :) And I don't think Larry was actually offended; it's just that some questions don't really have easy answers - imagine someone asking a great mathematician "But how do you KNOW that 2 + 2 is 4? Where's it written down?"... all he can say is "It is". ChrisA From wxjmfauth at gmail.com Wed Nov 5 08:54:20 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Wed, 5 Nov 2014 05:54:20 -0800 (PST) Subject: Idle on Mac issues In-Reply-To: <90cc9fbb-3c11-4e2b-bad2-5ee7fe51a7bc@googlegroups.com> References: <90cc9fbb-3c11-4e2b-bad2-5ee7fe51a7bc@googlegroups.com> Message-ID: <68efbcb9-0e51-4a0a-8a2e-ee9c3f649315@googlegroups.com> Le mardi 4 novembre 2014 13:44:16 UTC+1, Rustom Mody a ?crit?: > I seem to be stuck with some issues of Idle on macs. > The page https://www.python.org/download/mac/tcltk > seems to talk only of Tcl/Tk versions 8.5 > > Macports seem to have at 8.6 > https://www.macports.org/ports.php?by=library&substr=tcl > > With a direct download of Tcl/Tk there are some security warnings that prevent it from installing. > > Using whatever Tcl/Tk comes with python means many things dont work: > - The options menu wont open > - Various keyboard shortcuts dont work > > Any suggestions/directions? > > [Me: A non Mac-er with Mac-ers in my class!] (From a previous thead: IDLE for teaching purpose.) For your information, on Windows, IDLE is also not working. jmf From invalid at invalid.invalid Wed Nov 5 10:05:43 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 5 Nov 2014 15:05:43 +0000 (UTC) Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? References: Message-ID: On 2014-11-05, Dennis Lee Bieber wrote: > "machine code" typically implies an instruction set specific > to that machine... ALL computers operate in BINARY logic (a bit only > holds 0 or 1). How you get those bits into the computer is > irrelevant. Just to muddy the water... _Most_ parts of most computers operate in binary. Portions of some parts (e.g. some NAND flash) use ternary, quaternary, or octal. IIRC, four-state transistor cells are pretty common at the moment, but some vendor(s) are working with 8-state cells. -- Grant Edwards grant.b.edwards Yow! Hold the MAYO & pass at the COSMIC AWARENESS ... gmail.com From denismfmcmahon at gmail.com Wed Nov 5 10:19:39 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Wed, 5 Nov 2014 15:19:39 +0000 (UTC) Subject: I need algorithm for my task References: <50a7df31-ee6c-45f5-9dd8-6ac895ec46cf@googlegroups.com> Message-ID: On Wed, 05 Nov 2014 03:58:33 -0800, lordvital21 wrote: > I have line 'pythonpythonpyth'. How do I know which word is the > foundation line?. > Other examples: > "pythonpythonpyth" is python "DOLORIUMD" is DOLORIUM "HELLOLHELLO" is > HELLOL "thewordword" is thewordword > > I need to know whether the word in the text is repeated and get it. This > will be the key. Well, the way you describe it: So first you want to check if the first letter is also the second letter Then you want to check if the first 2 letters are also the 3rd and 4th Then you want to check if the first 3 letters are also the 4th-6th Then you want to check if the first 4 letters are also the 5th-8th So generally you want to check if the first n letters are also the second n letters, increasing n by 1 at a time until you reach your terminating condition. So what is your terminating condition? I can see two possibilities. You run out of letters in the second section, or you find a match. Here are a few more hints to help get you started: A string is a list of characters. A list can be sliced. You can measure the length of a list. You can compare the lengths of two lists. You can compare two lists. You can get the length of a string. The maximum length of a repeated word in a string can not be more than half the length of the string. However, the examples you give do not match the way you describe it. The examples you give assume the first word ends when the letter that started it is found again. -- Denis McMahon, denismfmcmahon at gmail.com From rosuav at gmail.com Wed Nov 5 10:21:55 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Nov 2014 02:21:55 +1100 Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: References: Message-ID: On Thu, Nov 6, 2014 at 2:05 AM, Grant Edwards wrote: > On 2014-11-05, Dennis Lee Bieber wrote: > >> "machine code" typically implies an instruction set specific >> to that machine... ALL computers operate in BINARY logic (a bit only >> holds 0 or 1). How you get those bits into the computer is >> irrelevant. > > Just to muddy the water... > > _Most_ parts of most computers operate in binary. Portions of some > parts (e.g. some NAND flash) use ternary, quaternary, or octal. IIRC, > four-state transistor cells are pretty common at the moment, but some > vendor(s) are working with 8-state cells. Dragging this back to some semblance of reality: Whenever you write code, you're writing code for some kind of executor. No level of abstraction higher or lower truly matters; you just write to the level you're aiming at, and everything else is of educational curiosity only. I might write code for a Python executor one day, and for a C executor another, and then another day maybe I'm writing LaTeX code - that's a language, too, of a sort. If I build my own framework layer above the base executor, that's just added another type of executor to the pool, and now I can target that. Everything's abstractions around something, and *it doesn't matter*, because anyone can fiddle with any layer without disturbing the others. Those eight-state cells can be dropped in without breaking my Python code - that's the whole point of abstractions. They're doing their job. ChrisA From chaselton at gmail.com Wed Nov 5 10:23:47 2014 From: chaselton at gmail.com (Cyd Haselton) Date: Wed, 5 Nov 2014 09:23:47 -0600 Subject: Build Question: How to Add -Wl, --option Before Objects In Setup.py? In-Reply-To: References: Message-ID: On Sun, Nov 2, 2014 at 3:38 PM, Ned Deily wrote: > In article > , > Cyd Haselton wrote: >> Just checking: is sincos() the same as sin() and cos()? Nm output for >> my toolchain's libm does show sin() and cos() just not sincos() > > See, this is what you get when you ask for free help: bad info. Silly me...what was I thinking? > sincos > isn't the same, as a little of googling informs me. But, as the thread > starting here indicates: > I did a fairly exhaustive search for the sincos() error code I was getting and that link did not turn up for me at all. Instead I found a reference that seemed to imply that such a macro should be implemented but it was not implemented in GCC-4.8.0. Then again, the link you found doesn't seem to indicate which version of GCC has this feature...maybe it is versions later than 4.8.0... > https://sourceware.org/ml/binutils/2010-04/msg00219.html > > gcc can do an optimization that turns a pair of sin() and cos() calls > with the same arguments into a single call to sincos(). And there is > such a pair in Python's complexobject.c. As the thread explains, there > are some platforms where sin() and cos() are implemented but not > sincos(). As suggested in the thread, one approach is to give options > to gcc to avoid the optimizations: > > CFLAGS='-fno-builtin-sin -fno-builtin-cos' > > That does seem to result in a libpython with no references to sincos. Sounds good...I'll try it if bootstrapping 4.9.0 goes south. > > -- > Ned Deily, > nad at acm.org > > -- > https://mail.python.org/mailman/listinfo/python-list From denismfmcmahon at gmail.com Wed Nov 5 10:38:09 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Wed, 5 Nov 2014 15:38:09 +0000 (UTC) Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? References: Message-ID: On Tue, 04 Nov 2014 21:30:06 -0500, Dennis Lee Bieber wrote: > If you have an old system with front-panel toggle switches, you set the > switches for binary values, and then push the "enter" switch. You've booted a PDP-8 then ;) -- Denis McMahon, denismfmcmahon at gmail.com From larry.martell at gmail.com Wed Nov 5 10:56:57 2014 From: larry.martell at gmail.com (Larry Martell) Date: Wed, 5 Nov 2014 10:56:57 -0500 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <000601cff8f4$7dc40220$794c0660$@gmail.com> Message-ID: On Wed, Nov 5, 2014 at 7:41 AM, Chris Angelico wrote: > On Wed, Nov 5, 2014 at 11:31 PM, Ivan Evstegneev > wrote: >>>> That's what I'm talking about (asking actually), where do you know it from? >> >>>>I know it because I've been a programmer for 39 years. >> >> I didn't intend to offence anyone here. Just asked a questions ^_^ > > Don't worry about offending people. Exactly. This is the internet - it's all about annoying people ;-) > Even if you do annoy one or two, > there'll be plenty of us who know to be patient :) And I don't think > Larry was actually offended; it's just that some questions don't > really have easy answers - imagine someone asking a great > mathematician "But how do you KNOW that 2 + 2 is 4? Where's it written > down?"... all he can say is "It is". Yeah, I'm on a lot of lists and lately I've seen a lot of 'I'm not a programmer, but I want to write code and I need someone to tell me how." Gets to you after a while. From rosuav at gmail.com Wed Nov 5 11:13:46 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Nov 2014 03:13:46 +1100 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <000601cff8f4$7dc40220$794c0660$@gmail.com> Message-ID: On Thu, Nov 6, 2014 at 2:56 AM, Larry Martell wrote: >> And I don't think >> Larry was actually offended; it's just that some questions don't >> really have easy answers - imagine someone asking a great >> mathematician "But how do you KNOW that 2 + 2 is 4? Where's it written >> down?"... all he can say is "It is". > > Yeah, I'm on a lot of lists and lately I've seen a lot of 'I'm not a > programmer, but I want to write code and I need someone to tell me > how." Gets to you after a while. Too true. Those same people are unlikely to go to a gathering of civil engineers and say "I'm no expert, but I want to build a bridge and I need someone to tell me how", yet somehow it's expected to be possible with software. ChrisA From ethan at stoneleaf.us Wed Nov 5 11:26:52 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 05 Nov 2014 08:26:52 -0800 Subject: Real-world use of Counter Message-ID: <545A4FCC.4090503@stoneleaf.us> I'm looking for real-world uses of collections.Counter, specifically to see if anyone has been surprised by, or had to spend extra-time debugging, issues with the in-place operators. Background: Most Python data types will cause a TypeError to be raised if unusable types are passed in: --> {'a': 0}.update(5) TypeError: 'int' object is not iterable --> [1, 2, 3].extend(3.14) TypeError: 'float' object is not iterable --> from collections import Counter --> Counter() + [1, 2, 3] TypeError: unsupported operand type(s) for +: 'Counter' and 'list' Most Counter in-place methods also behave this way: --> c /= [1, 2, 3] TypeError: unsupported operand type(s) for /=: 'Counter' and 'list' However, in the case of a handful of Counter in-place methods (+=, -=, &=, and |=), this is what happens instead: --> c = Counter() --> c += [1, 2, 3] AttributeError: 'list' object has no attribute 'items' Even worse (in my opinion) is the case of an empty Counter `and`ed with an incompatible type: --> c &= [1, 2, 3] --> No error is raised at all. In order to avoid unnecessary code churn (the fix itself is quite simple), the maintainer of the collections module wants to know if anybody has actually been affected by these inconsistencies, and if so, whether it was a minor inconvenience, or a compelling use-case. So, if this has bitten you, now is the time to speak up! :) -- ~Ethan~ From skip.montanaro at gmail.com Wed Nov 5 11:44:46 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Wed, 5 Nov 2014 10:44:46 -0600 Subject: Misunderstanding buffering - flushing isn't Message-ID: I've been developing a little web server. The request handler subclasses SimpleHTTPRequestHandler. It has a do_GET method which figures out what work to actually do, then ends with this: def do_GET(self): ... sys.stdout.flush() sys.stderr.flush() As it's still being actively developed, I've been dumping all sorts of diagnostic prints to stdout and stderr. I've been running it directly in a terminal window (this is an openSuSE system), but wanted to capture stdout and stderr for post-mortem analysis, so I wrote this little shell script: #!/bin/bash PORT=${1:-8008} BASE=$(dirname $0) echo port=$PORT pid=$$ > ${PORT}.stdout while true ; do python ${BASE}/httpserver.py $PORT >> ${PORT}.stdout 2> ${PORT}.stderr sleep 1 done I figured everything would be flushed to the respective .stdout and .stderr files at the end of every request, but that appears not to be the case. Do I have to run the python command with the -u flag to guarantee each request's output is immediately available in the output file at the end of each request? Thx, Skip From skip.montanaro at gmail.com Wed Nov 5 12:06:05 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Wed, 5 Nov 2014 11:06:05 -0600 Subject: Misunderstanding buffering - flushing isn't In-Reply-To: References: Message-ID: On Wed, Nov 5, 2014 at 10:44 AM, Skip Montanaro wrote: > I figured everything would be flushed to the respective .stdout and > .stderr files at the end of every request, but that appears not to be > the case. I stand corrected. I added print ">> request finished" to the end of do_GET (just before the flush() calls). I see that in the output files after the request finishes. Maybe I was just dreaming... S From irmen.NOSPAM at xs4all.nl Wed Nov 5 12:25:44 2014 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 05 Nov 2014 18:25:44 +0100 Subject: pkcs7 signing In-Reply-To: References: <545911CD.1060300@chamonix.reportlab.co.uk> <87bnomi20s.fsf@handshake.de> Message-ID: <545a5d97$0$2934$e4fe514c@news.xs4all.nl> On 5-11-2014 11:14, Robin Becker wrote: > On 05/11/2014 06:40, dieter wrote: >> Robin Becker writes: >> >>> Is there a way to do pkcs7 / 12 signing with python. >> >> Have you checked whether "OpenSSL" supports this kind of signing? >> If it does, then you likely can use this via several Python wrappings >> for "OpenSSL". >> > I checked that the openssl library does have a call for this, however, I cannot see this > exposed in either the cryptography or py2crypto packages. The code may be in there, but > I don't see it obviously exposed. I think m2crypto might do the job, but building it for > windows is a pain and I probably have to build it 6 times ie 32 & 64 bits x 2.7 3.3 & > 3.4. There are pre-built versions of openssl, but that's also a moving target right now. If you've got no luck with a direct openssl library, you can also call the openssl.exe binary and capture its results back into Python. You'll have to install something on windows to get that executable though. Irmen From irmen.NOSPAM at xs4all.nl Wed Nov 5 12:29:45 2014 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 05 Nov 2014 18:29:45 +0100 Subject: Misunderstanding buffering - flushing isn't In-Reply-To: References: Message-ID: <545a5e88$0$2882$e4fe514c@news.xs4all.nl> On 5-11-2014 17:44, Skip Montanaro wrote: > As it's still being actively developed, I've been dumping all sorts of > diagnostic prints to stdout and stderr. Any reason you're not using the logging module and get it all nicely dumped into a log file instead? (asks he who regularly inserts prints himself when doing a debugging task) Irmen From __peter__ at web.de Wed Nov 5 12:34:40 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Nov 2014 18:34:40 +0100 Subject: Real-world use of Counter References: <545A4FCC.4090503@stoneleaf.us> Message-ID: Ethan Furman wrote: > I'm looking for real-world uses of collections.Counter, specifically to > see if anyone has been surprised by, or had to spend extra-time debugging, > issues with the in-place operators. > > Background: > > Most Python data types will cause a TypeError to be raised if unusable > types are passed in: > > --> {'a': 0}.update(5) > TypeError: 'int' object is not iterable > > --> [1, 2, 3].extend(3.14) > TypeError: 'float' object is not iterable > > --> from collections import Counter > --> Counter() + [1, 2, 3] > TypeError: unsupported operand type(s) for +: 'Counter' and 'list' > > Most Counter in-place methods also behave this way: > > --> c /= [1, 2, 3] > TypeError: unsupported operand type(s) for /=: 'Counter' and 'list' > > However, in the case of a handful of Counter in-place methods (+=, -=, &=, > and |=), this is what happens instead: > > --> c = Counter() > --> c += [1, 2, 3] > AttributeError: 'list' object has no attribute 'items' > > Even worse (in my opinion) is the case of an empty Counter `and`ed with an > incompatible type: > > --> c &= [1, 2, 3] > --> > > No error is raised at all. > > In order to avoid unnecessary code churn (the fix itself is quite simple), > the maintainer of the collections module wants to know if anybody has > actually been affected by these inconsistencies, and if so, whether it was > a minor inconvenience, or a compelling use-case. > > So, if this has bitten you, now is the time to speak up! :) Some more: >>> Counter(a=1, b=2) Counter({'b': 2, 'a': 1}) >>> Counter(a=1, b=2, iterable=3) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3.4/collections/__init__.py", line 462, in __init__ self.update(iterable, **kwds) File "/usr/lib/python3.4/collections/__init__.py", line 542, in update _count_elements(self, iterable) TypeError: 'int' object is not iterable This is just the first oddity I came up with. I expect that the possibilities to break Python-coded classes are unlimited, as a result of the -- for me -- greatest gift of Python, namely: duck-typing. I hate the sum() implementation, not because I ever plan to "add" strings, but because it tests against bad style. Consenting adults, where are you? In particular for the &= fix, would >>> c = Counter([1, 2]) >>> c &= [1, 2, 3] >>> c Counter({1: 1, 2: 1}) still be allowed? If not, are there other places where a sequence might pretend to be a mapping? FTR, as I'm not exactly a power-user of Counter, I think I have used only the initializer with one positional iterable, and most_common(), and thus never been bitten by any of the above pitfalls. From python at mrabarnett.plus.com Wed Nov 5 12:53:23 2014 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 05 Nov 2014 17:53:23 +0000 Subject: I need algorithm for my task In-Reply-To: <50a7df31-ee6c-45f5-9dd8-6ac895ec46cf@googlegroups.com> References: <50a7df31-ee6c-45f5-9dd8-6ac895ec46cf@googlegroups.com> Message-ID: <545A6413.1060608@mrabarnett.plus.com> On 2014-11-05 11:58, lordvital21 at gmail.com wrote: > I have line 'pythonpythonpyth'. How do I know which word is the foundation line?. > Other examples: > "pythonpythonpyth" is python > "DOLORIUMD" is DOLORIUM > "HELLOLHELLO" is HELLOL > "thewordword" is thewordword > > I need to know whether the word in the text is repeated and get it. This will be the key. > Consider the first example. If the foundation is the first 1 character 'p' and you repeat it enough times you'll get 'pppppppppppppppp'. This is the same length as the line. Does it match the line? No. OK. If the foundation is the first 2 characters 'py' and you repeat it enough times you'll get 'pypypypypypypypy'. This is the same length as the line. Does it match the line? No. OK. If the foundation is the first 3 characters 'py' and you repeat it enough times you'll get 'pytpytpytpytpytpyt'. This is longer than as the line, so truncate it to 'pytpytpytpytpytpy'. Does it match the line? No. OK. Continue in this vein until you'll get a match. (The foundation might in fact be the entire line.) From skip.montanaro at gmail.com Wed Nov 5 12:54:21 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Wed, 5 Nov 2014 11:54:21 -0600 Subject: Misunderstanding buffering - flushing isn't In-Reply-To: <545a5e88$0$2882$e4fe514c@news.xs4all.nl> References: <545a5e88$0$2882$e4fe514c@news.xs4all.nl> Message-ID: On Wed, Nov 5, 2014 at 11:29 AM, Irmen de Jong wrote: > Any reason you're not using the logging module and get it all nicely dumped into a log > file instead? I'm an old fart. What can I say? BITD, (as Irmen is well aware, being about as old as I am in Python years), print was all we had. (We also walked uphill to school in both directions, in the snow.) While I use the logging module in other contexts, I never really liked it, and generally use it grudgingly. Skip From python at mrabarnett.plus.com Wed Nov 5 12:56:45 2014 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 05 Nov 2014 17:56:45 +0000 Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: <0f2j5a5habfaknvme41qfe0g09onmtles9@4ax.com> References: <0f2j5a5habfaknvme41qfe0g09onmtles9@4ax.com> Message-ID: <545A64DD.5090006@mrabarnett.plus.com> On 2014-11-05 02:30, Dennis Lee Bieber wrote: > On Tue, 4 Nov 2014 13:45:32 -0300, fran?ai s > declaimed the following: > >>I intend to write in lowest level of computer programming as a hobby. >> >>It is true that is impossible write in binary code, the lowest level >>of programming that you can write is in hex code? >> >>What is the lowest level of programming computers that you can write ? >> >>Is binary code? >> >>Is hex code? >> >>Is another machine code? Honestly do not know if it is true that there >>is another machine code beyond the binary and hex code. >> >>Is Assembly? > > Meaningless question -- it all relies upon HOW THE CODE GETS INTO > MEMORY. > > NOT TO MENTION: "binary" and "hex" are just notations. They both > represent a set of bits, but hex uses one character to encode 4 bits while > > binary needs one character for each bit. > > 0xA5 is the SAME as '101001010'b (note: the notation differs with > whatever system you use to enter them -- 0xA5 in C is 16#A5# in Ada, and > 'A5'h in some obsolete systems.. > I've also seen $A3 and 0A3h (it needs to start with a digit in the range 0..9). > If you have an old system with front-panel toggle switches, you set the > switches for binary values, and then push the "enter" switch. > > "machine code" typically implies an instruction set specific to that > machine... ALL computers operate in BINARY logic (a bit only holds 0 or 1). > How you get those bits into the computer is irrelevant. > From rosuav at gmail.com Wed Nov 5 13:03:49 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Nov 2014 05:03:49 +1100 Subject: Misunderstanding buffering - flushing isn't In-Reply-To: References: <545a5e88$0$2882$e4fe514c@news.xs4all.nl> Message-ID: On Thu, Nov 6, 2014 at 4:54 AM, Skip Montanaro wrote: > I'm an old fart. What can I say? BITD, (as Irmen is well aware, being > about as old as I am in Python years), print was all we had. (We also > walked uphill to school in both directions, in the snow.) While I use > the logging module in other contexts, I never really liked it, and > generally use it grudgingly. I have nothing against print... as long as it's a function. I don't like the arcane notations shoehorned into the print statement (the >> syntax always trips me up, I'm never sure whether to put it at the beginning or the end - it's ugly either way), but the function behaves nicely. ChrisA From cmferras at estudiantes.uci.cu Wed Nov 5 13:05:15 2014 From: cmferras at estudiantes.uci.cu (C@rlos) Date: Wed, 5 Nov 2014 13:05:15 -0500 (CST) Subject: I need algorithm for my task In-Reply-To: <545A6413.1060608@mrabarnett.plus.com> Message-ID: <1962053862.5573720.1415210715670.JavaMail.zimbra@estudiantes.uci.cu> I thing this work: stg='pythonpython' foundationline=stg[ 0:( stg [ 1: ].index( stg[ 0 ])+1 ) ] On 2014-11-05 11:58, lordvital21 at gmail.com wrote: > I have line 'pythonpythonpyth'. How do I know which word is the foundation line?. > Other examples: > "pythonpythonpyth" is python > "DOLORIUMD" is DOLORIUM > "HELLOLHELLO" is HELLOL > "thewordword" is thewordword > > I need to know whether the word in the text is repeated and get it. This will be the key. > Consider the first example. If the foundation is the first 1 character 'p' and you repeat it enough times you'll get 'pppppppppppppppp'. This is the same length as the line. Does it match the line? No. OK. If the foundation is the first 2 characters 'py' and you repeat it enough times you'll get 'pypypypypypypypy'. This is the same length as the line. Does it match the line? No. OK. If the foundation is the first 3 characters 'py' and you repeat it enough times you'll get 'pytpytpytpytpytpyt'. This is longer than as the line, so truncate it to 'pytpytpytpytpytpy'. Does it match the line? No. OK. Continue in this vein until you'll get a match. (The foundation might in fact be the entire line.) -- https://mail.python.org/mailman/listinfo/python-list III Escuela Internacional de Invierno en la UCI del 17 al 28 de febrero del 2014. Ver www.uci.cu -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Wed Nov 5 13:49:01 2014 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 05 Nov 2014 18:49:01 +0000 Subject: I need algorithm for my task In-Reply-To: <1962053862.5573720.1415210715670.JavaMail.zimbra@estudiantes.uci.cu> References: <1962053862.5573720.1415210715670.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: <545A711D.5080306@mrabarnett.plus.com> On 2014-11-05 18:05, C at rlos wrote: > I thing this work: > > stg='pythonpython' > foundationline=stg[ 0:( stg [ 1: ].index( stg[ 0 ])+1 ) ] > It doesn't work for the final example or "barbaz". From wxjmfauth at gmail.com Wed Nov 5 14:07:50 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Wed, 5 Nov 2014 11:07:50 -0800 (PST) Subject: I need algorithm for my task In-Reply-To: <50a7df31-ee6c-45f5-9dd8-6ac895ec46cf@googlegroups.com> References: <50a7df31-ee6c-45f5-9dd8-6ac895ec46cf@googlegroups.com> Message-ID: <6ee4fb35-da11-49e3-b982-cd45d0b898e8@googlegroups.com> Le mercredi 5 novembre 2014 12:58:44 UTC+1, lordv... at gmail.com a ?crit?: > I have line 'pythonpythonpyth'. How do I know which word is the foundation line?. > Other examples: > "pythonpythonpyth" is python > "DOLORIUMD" is DOLORIUM > "HELLOLHELLO" is HELLOL > "thewordword" is thewordword > > I need to know whether the word in the text is repeated and get it. This will be the key. >From your examples: impossible, unsolvable. [*] [*] unless using an "external" list of words. From wxjmfauth at gmail.com Wed Nov 5 14:29:15 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Wed, 5 Nov 2014 11:29:15 -0800 (PST) Subject: I need algorithm for my task In-Reply-To: <6ee4fb35-da11-49e3-b982-cd45d0b898e8@googlegroups.com> References: <50a7df31-ee6c-45f5-9dd8-6ac895ec46cf@googlegroups.com> <6ee4fb35-da11-49e3-b982-cd45d0b898e8@googlegroups.com> Message-ID: Le mercredi 5 novembre 2014 20:08:03 UTC+1, wxjm... at gmail.com a ?crit?: > Le mercredi 5 novembre 2014 12:58:44 UTC+1, lordv... at gmail.com a ?crit?: > > I have line 'pythonpythonpyth'. How do I know which word is the foundation line?. > > Other examples: > > "pythonpythonpyth" is python > > "DOLORIUMD" is DOLORIUM > > "HELLOLHELLO" is HELLOL > > "thewordword" is thewordword > > > > I need to know whether the word in the text is repeated and get it. This will be the key. > > From your examples: impossible, unsolvable. [*] > > [*] unless using an "external" list of words. Mea culpa. Sorry, I was wrong. (I "missread" one example). From neilc at norwich.edu Wed Nov 5 16:19:56 2014 From: neilc at norwich.edu (Neil D. Cerutti) Date: Wed, 05 Nov 2014 16:19:56 -0500 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <000601cff8f4$7dc40220$794c0660$@gmail.com> Message-ID: On 11/5/2014 7:41 AM, Chris Angelico wrote: > On Wed, Nov 5, 2014 at 11:31 PM, Ivan Evstegneev > wrote: >>>> That's what I'm talking about (asking actually), where do you know it from? >> >>>> I know it because I've been a programmer for 39 years. >> >> I didn't intend to offence anyone here. Just asked a questions ^_^ > > Don't worry about offending people. Even if you do annoy one or two, > there'll be plenty of us who know to be patient :) And I don't think > Larry was actually offended; it's just that some questions don't > really have easy answers - imagine someone asking a great > mathematician "But how do you KNOW that 2 + 2 is 4? Where's it written > down?"... all he can say is "It is". But it *can* be interesting to try and do otherwise. http://en.wikipedia.org/wiki/Principia_Mathematica -- Neil Cerutti From tjreedy at udel.edu Wed Nov 5 16:34:10 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 05 Nov 2014 16:34:10 -0500 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: <000601cff8f4$7dc40220$794c0660$@gmail.com> References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <000601cff8f4$7dc40220$794c0660$@gmail.com> Message-ID: On 11/5/2014 7:31 AM, Ivan Evstegneev wrote: > You got my point exactly. ^_^ This is not about a "range" command > itself, but those conventions. The Language Manual 1. Introduction has a section on the grammar notation conventions. The Library Manual 1. Introduction does not. I would agree that it should. Someone could open an issue. Ivan, the help(ob) results sometimes assume that you have read the doc and only need a reminder about the function signature. I strongly recommend that you read most of the first 5 chapter of the Library manual, especially 2 and 4. -- Terry Jan Reedy From gheskett at wdtv.com Wed Nov 5 16:40:50 2014 From: gheskett at wdtv.com (Gene Heskett) Date: Wed, 5 Nov 2014 16:40:50 -0500 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> Message-ID: <201411051640.50608.gheskett@wdtv.com> On Wednesday 05 November 2014 10:56:57 Larry Martell did opine And Gene did reply: > On Wed, Nov 5, 2014 at 7:41 AM, Chris Angelico wrote: > > On Wed, Nov 5, 2014 at 11:31 PM, Ivan Evstegneev > > > > wrote: > >>>> That's what I'm talking about (asking actually), where do you know > >>>> it from? > >>>> > >>>>I know it because I've been a programmer for 39 years. > >> > >> I didn't intend to offence anyone here. Just asked a questions ^_^ > > > > Don't worry about offending people. > > Exactly. This is the internet - it's all about annoying people ;-) > > > Even if you do annoy one or two, > > there'll be plenty of us who know to be patient :) And I don't think > > Larry was actually offended; it's just that some questions don't > > really have easy answers - imagine someone asking a great > > mathematician "But how do you KNOW that 2 + 2 is 4? Where's it > > written down?"... all he can say is "It is". > > Yeah, I'm on a lot of lists and lately I've seen a lot of 'I'm not a > programmer, but I want to write code and I need someone to tell me > how." Gets to you after a while. +1000, and its not just this list Larry. It seems we have a pandemic. 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 US V Castleman, SCOTUS, Mar 2014 is grounds for Impeaching SCOTUS From joel.goldstick at gmail.com Wed Nov 5 17:31:31 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 5 Nov 2014 17:31:31 -0500 Subject: detect mouse pointer type In-Reply-To: References: Message-ID: On Tue, Nov 4, 2014 at 9:07 PM, Peter Irbizon wrote: > Hello, > please how can I detect mouse pointer type? I would like to print every > mouse pointer change (arrow, hand, ...) while moving my mouse over screen. > How can I do this? (for now I need it for windows, but cross-platform > solution is highly appreciated) > Those events happen in the browser. I suspect you could do this with javascript. Can't do it on the backend. > Many thanks. > > -- > https://mail.python.org/mailman/listinfo/python-list > -- Joel Goldstick http://joelgoldstick.com From cs at zip.com.au Wed Nov 5 17:27:35 2014 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 6 Nov 2014 09:27:35 +1100 Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: References: Message-ID: <20141105222735.GA51461@cskk.homeip.net> On 05Nov2014 15:38, Denis McMahon wrote: >On Tue, 04 Nov 2014 21:30:06 -0500, Dennis Lee Bieber wrote: >> If you have an old system with front-panel toggle switches, you >set the >> switches for binary values, and then push the "enter" switch. > >You've booted a PDP-8 then ;) Not me, but I have booted a PDP-11. Same deal:-) Our kernels had a patch in the idle loop that updated a specific memory address with a regularly changing bit pattern (therefore the change rate slowed down when the machine was busy). Post boot we'd set the memory view toggle swithces to that address and be treated to a beautiful Cylon-like shuttling pattern of red lights indiciating business. Cheers, Cameron Simpson The most likely way for the world to be destroyed, most experts agree, is by accident. That's where we come in; we're computer professionals. We cause accidents. - Nathaniel Borenstein From glicerinu at gmail.com Wed Nov 5 17:42:48 2014 From: glicerinu at gmail.com (Marc Aymerich) Date: Wed, 5 Nov 2014 23:42:48 +0100 Subject: detect mouse pointer type In-Reply-To: References: Message-ID: On Wed, Nov 5, 2014 at 11:31 PM, Joel Goldstick wrote: > On Tue, Nov 4, 2014 at 9:07 PM, Peter Irbizon > wrote: > > Hello, > > please how can I detect mouse pointer type? I would like to print every > > mouse pointer change (arrow, hand, ...) while moving my mouse over > screen. > > How can I do this? (for now I need it for windows, but cross-platform > > solution is highly appreciated) > > > Those events happen in the browser. I suspect you could do this with > javascript. Can't do it on the backend. > Back in the day we used to have desktop applications other than the web browser. But this was even before cloud computing began to emerge ;) > -- > Marc -------------- next part -------------- An HTML attachment was scrubbed... URL: From drsalists at gmail.com Wed Nov 5 19:04:25 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Wed, 5 Nov 2014 16:04:25 -0800 Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: <20141105063922.GA62888@cskk.homeip.net> References: <39ed3434-2d1c-4d74-b20d-db8b346f1c7d@googlegroups.com> <20141105063922.GA62888@cskk.homeip.net> Message-ID: On Tue, Nov 4, 2014 at 10:39 PM, Cameron Simpson wrote: > Bah! He asked if there were lower levels than binary. Ergo: chip design! > (And microcode, the intermediate layer. Or one of the layers, depending > where you draw the line.) Should we stop before we reach the quantum foam of > spacetime? Last I heard, Intel (and others?) had stopped using microcode, to get a performance boost. That means CPU's are not field-updatable in the event of a problem, but most people would just buy another computer anyway. From Charles at CharlesWeitzer.com Wed Nov 5 20:07:41 2014 From: Charles at CharlesWeitzer.com (Charles Weitzer) Date: Wed, 5 Nov 2014 17:07:41 -0800 Subject: Machine Learning Startup Hiring Message-ID: <000401cff95e$118318c0$34894a40$@CharlesWeitzer.com> My name is Charles Weitzer. I do recruiting with a focus on quantitative sciences. One of my clients is a machine learning startup located in Northern California. The founders include a successful veteran entrepreneur with a PhD in CS from Stanford, while the other founder is on the faculty at UC Berkeley. Their team has made unpublished discoveries in the field of Machine Learning and in other areas as well. My client would like to hire an extremely talented Senior Data Infrastructure Software Engineer as soon as possible. Their job description can be found below. This group is going to be the next big thing in terms of quantitative strategies and systems. They are rebuilding their current system and also designing a new system. You could work on either or both. I would love to speak with you or anyone else you might highly recommend about this opportunity. Thank you, Charles Weitzer CEO/Senior Recruiter Charles Weitzer and Associates, Inc. Global Financial Recruiting Services Email: Charles at CharlesWeitzer.com Phone: (USA) 510 558-9182 ********************************* Senior Data Infrastructure Software Engineer Fast-growing science and technology-driven startup seeks a Senior Data Infrastructure Software Engineer. You will be a core member working with the RnD, Software, Infrastructure, and Trading teams to develop, test, deploy, and manage research, operational and production software. The firm researches and deploys machine learning and statistical trading strategies that are designed to generate attractive returns without being dependent on the performance of the overall market. Join a team of people that includes a professor at a premier university as well as over ten PhDs and two MBAs from top schools, led by the founder and CEO of a successful Internet Infrastructure technology firm. We have a casual and collegial office environment, weekly catered lunches, and offer competitive benefits packages. Focus areas for the position include creating software infrastructure for our research department and production trading systems, implementing and automating back office and reporting systems, as well as supporting the next generation of our compute and storage hardware systems. We seek a candidate who can bring both development and operations skills to rework existing software infrastructure and guide test/automation of new and ongoing deployments. Qualifications: . Experience writing Python code in a *nix environment . Experience working with mission critical RDBMS, performance and fault tolerance . Industry experience as a software engineer . Automation deployment and virtualization (Ansible, KVM, Jenkins, etc.) . Experience with debugging and performance profiling, including the use of tools such as strace, valgrind, gdb, tcpdump, etc. Useful Skills (Desirable, but not required): . Monitor and network management (Nagios, Logstash, Graphite, Cacti, etc.) . Knowledge of distributed systems, cluster computing, and fault tolerance . Experience making commits on open-source technology . Familiarity with cluster management and job queuing systems (Chronos, Luigi, Oracle grid engine, Mesos, etc.) . Experience in operations for highly available services Please note that a background in finance is not required. ********************************* To apply for this position, please send your resume to Charles at CharlesWeitzer.com. Thank you, Charles Weitzer CEO/Senior Recruiter Charles Weitzer and Associates, Inc. Global Financial Recruiting Services Email: Charles at CharlesWeitzer.com Phone: (USA) 510 558-9182 From cs at zip.com.au Wed Nov 5 17:23:53 2014 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 6 Nov 2014 09:23:53 +1100 Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: References: Message-ID: <20141105222353.GA48666@cskk.homeip.net> On 05Nov2014 18:09, Chris Angelico wrote: >On Wed, Nov 5, 2014 at 5:39 PM, Cameron Simpson wrote: >> Bah! He asked if there were lower levels than binary. Ergo: chip design! >> (And microcode, the intermediate layer. Or one of the layers, depending >> where you draw the line.) Should we stop before we reach the quantum foam of >> spacetime? > >Certainly not. We keep going below electrons, and find ourselves in >Quantumland. It's like Wonderland, only... uhh... actually, it's just >like Wonderland. Pick up a book called "Alice in Quantumland" by >Robert Gilmore - it's worth reading. It is sitting of the shelf right here, awaiting my attention:-) Cheers, Cameron Simpson If this experiment we're doing works, then I will follow up and push it as hard as possible. And if it doesn't work, I will write a science-fiction novel where it does work. It's a win-win situation. - John Cramer on his experiment for possible cuasality violation From breamoreboy at yahoo.co.uk Wed Nov 5 21:14:41 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 06 Nov 2014 02:14:41 +0000 Subject: Misunderstanding buffering - flushing isn't In-Reply-To: References: <545a5e88$0$2882$e4fe514c@news.xs4all.nl> Message-ID: On 05/11/2014 17:54, Skip Montanaro wrote: > On Wed, Nov 5, 2014 at 11:29 AM, Irmen de Jong wrote: >> Any reason you're not using the logging module and get it all nicely dumped into a log >> file instead? > > I'm an old fart. What can I say? BITD, (as Irmen is well aware, being > about as old as I am in Python years), print was all we had. (We also > walked uphill to school in both directions, in the snow.) While I use > the logging module in other contexts, I never really liked it, and > generally use it grudgingly. > > Skip > My approach was much like yours but I was converted a couple of years ago. Sadly both the name of the author and the title of the article left, as the late, great Spike Milligan said in one of his books, "an indelible blank on my mind" :) However in an attempt to show that you can teach a fellow old fart new tricks could an article like this help http://fruch.github.io/2014/11/06/taming-the-logging-formatter/ ? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From davea at davea.name Wed Nov 5 21:24:57 2014 From: davea at davea.name (Dave Angel) Date: Wed, 5 Nov 2014 21:24:57 -0500 (EST) Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? References: Message-ID: fran?ai s Wrote in message: > I intend to write in lowest level of computer programming as a hobby. > > It is true that is impossible write in binary code, the lowest level > of programming that you can write is in hex code? > > What is the lowest level of programming computers that you can write ? > > Is binary code? > > Is hex code? > > Is another machine code? Honestly do not know if it is true that there > is another machine code beyond the binary and hex code. > > Is Assembly? > You have to start somewhere. The lowest practical level is called hardware. If you're going to ignore that, then you presumably have some particular hardware in mind. If you're talking the Intel Pentium, you've already skipped the lowest level, because Intel has already done it (microcode ) and sealed it inside the chip. Many years ago I wrote microcode for a living, and on some of our machines it was buried in ROM, while in others it was changeable and loaded at boot time. In any case, customers didn't usually get documentation or tools for changing it. There probably are still processors around that have changeable microcode available. You may ask what is Microcode? It's the code that tells the real hardware what to do with that binary "machine code" that people call machine code. You don't really think that there is hardware to do a trig function, do you? So once you pick a processor, if you can't write the microcode, what's the lowest level? Toggle switches is probably it, because anything else has gobs of software running before you hit your first key. Keyboards were once hardware, but probably any recent keyboard has more code in it than my satellite navigation program written in 1973. Of course toggle switches on the console are probably binary, but the first IBM machines had hex rotary switches on their console. There's no important difference between binary and hex; you do those conversions in your head while toggling stuff in. Now if you don't have a console then you have to go up a level, and use some form of console. We used punched paper tape as the next level up, and hex punched cards next. I suppose you'll have to use a console, with some kind of monitor echoing your keystrokes onto a screen. No tty for you? Next level up is to have some form of operating system running. You might even use a system call to output a character to your terminal. No machine language instruction for that. And so on. Assembly is a low level language that is pretty much translated, each line of text into one mahine instruction. Usually the printout can show the results in hex or octal, but you can trivially convert in your head to binary for those toggle switches or whatever. Or use the executable that your assembler and linker produce. But by now you're using lots of os services, reading and writing files, displaying stuff, printing to a dot matrix or daisy wheel printer. Pick your level, there are dozens, and I've used most of them. But the distinction between binary, octal, and hex is too minor to mention, except you specifically asked. HTH -- DaveA From davea at davea.name Wed Nov 5 21:37:15 2014 From: davea at davea.name (Dave Angel) Date: Wed, 5 Nov 2014 21:37:15 -0500 (EST) Subject: Understanding "help" command description syntax - explanation needed References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <000601cff8f4$7dc40220$794c0660$@gmail.com> Message-ID: Chris Angelico Wrote in message: > On Thu, Nov 6, 2014 at 2:56 AM, Larry Martell wrote: >>> And I don't think >>> Larry was actually offended; it's just that some questions don't >>> really have easy answers - imagine someone asking a great >>> mathematician "But how do you KNOW that 2 + 2 is 4? Where's it written >>> down?"... all he can say is "It is". >> >> Yeah, I'm on a lot of lists and lately I've seen a lot of 'I'm not a >> programmer, but I want to write code and I need someone to tell me >> how." Gets to you after a while. > > Too true. Those same people are unlikely to go to a gathering of civil > engineers and say "I'm no expert, but I want to build a bridge and I > need someone to tell me how", yet somehow it's expected to be possible > with software. > > ChrisA > Or I'm no expert but I need someone to show me how; build me one here in my front yard. -- DaveA From breamoreboy at yahoo.co.uk Wed Nov 5 21:52:42 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 06 Nov 2014 02:52:42 +0000 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <000601cff8f4$7dc40220$794c0660$@gmail.com> Message-ID: On 06/11/2014 02:37, Dave Angel wrote: > Chris Angelico Wrote in message: >> On Thu, Nov 6, 2014 at 2:56 AM, Larry Martell wrote: >>>> And I don't think >>>> Larry was actually offended; it's just that some questions don't >>>> really have easy answers - imagine someone asking a great >>>> mathematician "But how do you KNOW that 2 + 2 is 4? Where's it written >>>> down?"... all he can say is "It is". >>> >>> Yeah, I'm on a lot of lists and lately I've seen a lot of 'I'm not a >>> programmer, but I want to write code and I need someone to tell me >>> how." Gets to you after a while. >> >> Too true. Those same people are unlikely to go to a gathering of civil >> engineers and say "I'm no expert, but I want to build a bridge and I >> need someone to tell me how", yet somehow it's expected to be possible >> with software. >> >> ChrisA >> > > Or I'm no expert but I need someone to show me how; build me one > here in my front yard. > Against a requirements specification that changes on a daily basis, I want it delivered yesterday and no you can't have any more resources to help out, so don't ask :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From denismfmcmahon at gmail.com Wed Nov 5 22:14:16 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Thu, 6 Nov 2014 03:14:16 +0000 (UTC) Subject: I need algorithm for my task References: <1962053862.5573720.1415210715670.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: On Wed, 05 Nov 2014 18:49:01 +0000, MRAB wrote: > On 2014-11-05 18:05, C at rlos wrote: >> I thing this work: >> >> stg='pythonpython' >> foundationline=stg[ 0:( stg [ 1: ].index( stg[ 0 ])+1 ) ] >> > It doesn't work for the final example or "barbaz". I have two algorithms I've implemented. Still not sure exactly which algorithm he wants though. The first one is as he describes, in that the word is only reported if it's repeated, else report the whole string. The second algorithm reads up until the first letter is repeated, or reports the whole string if no repeat found. I did see a third algorithm suggested, I should add that and see what happens. OK, implemented the third algorithm (repeat first n chars of s int(n/len (s))+1 times, truncate to len(s) and compare with s), I also added another test case, now my test cases are: t = ["pythonpythonpyth", "DOLORIUMD", "HELLOLHELLO", "thewordword", "barbaz", "dibdibdobdibdibdob"] and my output is: $ ./words.py python DOLORIUMD HELLOLHELLO thewordword barbaz dib python DOLORIUM HELLOL thewordword bar dib python DOLORIUM HELLOL thewordword barbaz dibdibdob $ I wonder which of these three is actually the algorithm the OP wants. -- Denis McMahon, denismfmcmahon at gmail.com From rosuav at gmail.com Wed Nov 5 22:35:27 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Nov 2014 14:35:27 +1100 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <000601cff8f4$7dc40220$794c0660$@gmail.com> Message-ID: On Thu, Nov 6, 2014 at 1:52 PM, Mark Lawrence wrote: > Against a requirements specification that changes on a daily basis, I want > it delivered yesterday and no you can't have any more resources to help out, > so don't ask :) Or maybe "Look, I'll give you five bucks if you can have the whole thing done by tomorrow, okay?"... ChrisA From denismfmcmahon at gmail.com Wed Nov 5 22:36:40 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Thu, 6 Nov 2014 03:36:40 +0000 (UTC) Subject: I need algorithm for my task References: <1962053862.5573720.1415210715670.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: On Wed, 05 Nov 2014 18:49:01 +0000, MRAB wrote: > It doesn't work for the final example or "barbaz". Oh, and we really need a private "python homework answers" list where we can discuss the most pythonic solution we can think of for all these homework / coursework questions without showing the solutions to the students. I'm quite proud of a 2 line solution to the third algorithm that I implemented, although it might be considered as somewhat obfuscated code by some. ;) -- Denis McMahon, denismfmcmahon at gmail.com From rosuav at gmail.com Wed Nov 5 22:47:30 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Nov 2014 14:47:30 +1100 Subject: I need algorithm for my task In-Reply-To: References: <1962053862.5573720.1415210715670.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: On Thu, Nov 6, 2014 at 2:36 PM, Denis McMahon wrote: > On Wed, 05 Nov 2014 18:49:01 +0000, MRAB wrote: > >> It doesn't work for the final example or "barbaz". > > Oh, and we really need a private "python homework answers" list where we > can discuss the most pythonic solution we can think of for all these > homework / coursework questions without showing the solutions to the > students. > > I'm quite proud of a 2 line solution to the third algorithm that I > implemented, although it might be considered as somewhat obfuscated code > by some. ;) Fun way to handle that: You get access only when you demonstrate that you can write a (mostly-)working version yourself. ChrisA From denismfmcmahon at gmail.com Wed Nov 5 23:00:38 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Thu, 6 Nov 2014 04:00:38 +0000 (UTC) Subject: I need algorithm for my task References: <1962053862.5573720.1415210715670.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: On Thu, 06 Nov 2014 03:36:40 +0000, Denis McMahon wrote: > On Wed, 05 Nov 2014 18:49:01 +0000, MRAB wrote: > >> It doesn't work for the final example or "barbaz". > > Oh, and we really need a private "python homework answers" list where we > can discuss the most pythonic solution we can think of for all these > homework / coursework questions without showing the solutions to the > students. > I'm quite proud of a 2 line solution to the third algorithm that I > implemented, although it might be considered as somewhat obfuscated code > by some. ;) Even prouder of the 1 liner! In fact I'm going to post it, because I think any student who can walk his instructor through how my one-liner works deserves the marks. Of course, any student who presents this as a solution and is unable to walk their instructor through it should be failed for stupidity and plagiarism! t = ["pythonpythonpyth", "DOLORIUMD", "HELLOLHELLO", "thewordword", "barbaz", "dibdibdobdibdibdob"] def baseword(s): """find shortest sequence which repeats to generate s""" return s[0:["".join([s[0:x]for k in range(int(len(s)/x)+1)])[0:len (s)]for x in range(1,len(s)+1)].index(s)+1] for w in t: print(baseword(w)) p.s. I really want to be in the room when the instructor asks this student to come up in front of the class and explain how his solution works! -- Denis McMahon, denismfmcmahon at gmail.com From gheskett at wdtv.com Wed Nov 5 23:05:02 2014 From: gheskett at wdtv.com (Gene Heskett) Date: Wed, 5 Nov 2014 23:05:02 -0500 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> Message-ID: <201411052305.02610.gheskett@wdtv.com> On Wednesday 05 November 2014 21:52:42 Mark Lawrence did opine And Gene did reply: > On 06/11/2014 02:37, Dave Angel wrote: > > Chris Angelico Wrote in message: > >> On Thu, Nov 6, 2014 at 2:56 AM, Larry Martell wrote: > >>>> And I don't think > >>>> Larry was actually offended; it's just that some questions don't > >>>> really have easy answers - imagine someone asking a great > >>>> mathematician "But how do you KNOW that 2 + 2 is 4? Where's it > >>>> written down?"... all he can say is "It is". > >>> > >>> Yeah, I'm on a lot of lists and lately I've seen a lot of 'I'm not > >>> a programmer, but I want to write code and I need someone to tell > >>> me how." Gets to you after a while. > >> > >> Too true. Those same people are unlikely to go to a gathering of > >> civil engineers and say "I'm no expert, but I want to build a > >> bridge and I need someone to tell me how", yet somehow it's > >> expected to be possible with software. > >> > >> ChrisA > > > > Or I'm no expert but I need someone to show me how; build me one > > > > here in my front yard. > > Against a requirements specification that changes on a daily basis, I > want it delivered yesterday and no you can't have any more resources to > help out, so don't ask :) With, or without a toll booth and operator? 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 US V Castleman, SCOTUS, Mar 2014 is grounds for Impeaching SCOTUS From davea at davea.name Wed Nov 5 23:11:47 2014 From: davea at davea.name (Dave Angel) Date: Wed, 5 Nov 2014 23:11:47 -0500 (EST) Subject: Misunderstanding buffering - flushing isn't References: Message-ID: Skip Montanaro Wrote in message: > On Wed, Nov 5, 2014 at 10:44 AM, Skip Montanaro > wrote: >> I figured everything would be flushed to the respective .stdout and >> .stderr files at the end of every request, but that appears not to be >> the case. > > I stand corrected. I added > > print ">> request finished" > > to the end of do_GET (just before the flush() calls). I see that in > the output files after the request finishes. Maybe I was just > dreaming... > > S > Wild guess here. I've worked in environments where a newline would trigger a flush. To check that, try a trailing comma on the last print, which suppresses the newline. -- DaveA From rosuav at gmail.com Wed Nov 5 23:14:05 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Nov 2014 15:14:05 +1100 Subject: I need algorithm for my task In-Reply-To: References: <1962053862.5573720.1415210715670.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: On Thu, Nov 6, 2014 at 3:00 PM, Denis McMahon wrote: > def baseword(s): > """find shortest sequence which repeats to generate s""" > return s[0:["".join([s[0:x]for k in range(int(len(s)/x)+1)])[0:len > (s)]for x in range(1,len(s)+1)].index(s)+1] That's hardly a PEP-8 compliant line, but I can help out a bit. return s[0:[(s[0:x]*(len(s)//x+1))[0:len(s)]for x in range(1,len(s)+1)].index(s)+1] That's still 83 characters without indentation, but it's close now. I love the algorithm. Took me a bit of analysis (and inspection of partial results) to understand what your code's doing, but it's stupidly elegant and elegantly stupid. ChrisA From denismfmcmahon at gmail.com Wed Nov 5 23:39:38 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Thu, 6 Nov 2014 04:39:38 +0000 (UTC) Subject: I need algorithm for my task References: <1962053862.5573720.1415210715670.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: On Thu, 06 Nov 2014 15:14:05 +1100, Chris Angelico wrote: > On Thu, Nov 6, 2014 at 3:00 PM, Denis McMahon > wrote: >> def baseword(s): >> """find shortest sequence which repeats to generate s""" >> return s[0:["".join([s[0:x]for k in range(int(len(s)/x)+1)])[0:len >> (s)]for x in range(1,len(s)+1)].index(s)+1] > > That's hardly a PEP-8 compliant line, but I can help out a bit. > > return s[0:[(s[0:x]*(len(s)//x+1))[0:len(s)]for x in > range(1,len(s)+1)].index(s)+1] > > That's still 83 characters without indentation, but it's close now. l = len r = range but technically then it's no longer a one liner. > I love the algorithm. Took me a bit of analysis (and inspection of > partial results) to understand what your code's doing, but it's stupidly > elegant and elegantly stupid. :) Well yes, building that list is a stupid way to solve the problem, but I can't see another way to do it in one line. It's an implementation of my algorithm 3 (which I think you described) but working from the other end as it were. -- Denis McMahon, denismfmcmahon at gmail.com From rustompmody at gmail.com Thu Nov 6 01:00:48 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 5 Nov 2014 22:00:48 -0800 (PST) Subject: Real-world use of Counter In-Reply-To: References: Message-ID: On Wednesday, November 5, 2014 9:57:08 PM UTC+5:30, Ethan Furman wrote: > In order to avoid unnecessary code churn (the fix itself is quite simple), the maintainer of the collections module > wants to know if anybody has actually been affected by these inconsistencies, and if so, whether it was a minor > inconvenience, or a compelling use-case. > > So, if this has bitten you, now is the time to speak up! :) Not in direct answer to your specific question, but Counter generally. In studying (somewhat theoretically) the general world of collection data structures we see - sets -- neither order nor repetition - bags -- no order, repetition significant - lists -- both order and repetition Sometimes 'bag' is called 'multiset' However counter is a weird non-standard name that overloads an already overloaded term -- 'Counter' has a very standard meaning in programming and in hardware design. Yes changing the name is too code-churn causing. But a synonym Bag (or multiset) for Counter would be a pleasant addition for me. Calling a bag as counter is inappropriate for an analogous reason to why calling a dictionary as a 'hash' is inappropriate -- it confuses an implementation detail for fundamental semantics. -------- PS. I probably wont participate in this discussion hereafter because off-net for 2 weeks From wxjmfauth at gmail.com Thu Nov 6 01:31:23 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Wed, 5 Nov 2014 22:31:23 -0800 (PST) Subject: I need algorithm for my task In-Reply-To: References: <50a7df31-ee6c-45f5-9dd8-6ac895ec46cf@googlegroups.com> <6ee4fb35-da11-49e3-b982-cd45d0b898e8@googlegroups.com> Message-ID: <4308e4c5-878e-4687-a834-aeffe835a9b3@googlegroups.com> Le mercredi 5 novembre 2014 20:29:34 UTC+1, wxjm... at gmail.com a ?crit?: > Le mercredi 5 novembre 2014 20:08:03 UTC+1, wxjm... at gmail.com a ?crit?: > > Le mercredi 5 novembre 2014 12:58:44 UTC+1, lordv... at gmail.com a ?crit?: > > > I have line 'pythonpythonpyth'. How do I know which word is the foundation line?. > > > Other examples: > > > "pythonpythonpyth" is python > > > "DOLORIUMD" is DOLORIUM > > > "HELLOLHELLO" is HELLOL > > > "thewordword" is thewordword > > > > > > I need to know whether the word in the text is repeated and get it. This will be the key. > > > > From your examples: impossible, unsolvable. [*] > > > > [*] unless using an "external" list of words. > > Mea culpa. Sorry, I was wrong. (I "missread" one example). 2nd erratum (?) Thinking again. There is in my mind no solution. From orgnut at yahoo.com Thu Nov 6 02:16:30 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Wed, 05 Nov 2014 23:16:30 -0800 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: References: Message-ID: On 11/05/2014 03:00 AM, Ivan Evstegneev wrote: > Hello everyone, > > I?m a Python beginner and just getting familiar with it. (I need it for my EE B.Sc. project) > For the learning purposes I use IDLE and (Learning Python by written by Mark Lutz). > Let?s say that I have some earlier experience with C language, but still Python is a different > one ))) The Lutz book is an excellent and VERY thorough Python reference, but it is not very good as a beginner's tutorial. The standard Python.org tutorial can be a better starting point. Of course, there are a lot of other good sources as well -- both on-line and dead-tree versions. Try some googling. Also the Python Wiki has a lot of valuable links: https://wiki.python.org/moin/ -=- Larry -=- From jpiitula at ling.helsinki.fi Thu Nov 6 02:59:09 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 06 Nov 2014 09:59:09 +0200 Subject: I need algorithm for my task References: <1962053862.5573720.1415210715670.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: Denis McMahon writes: > On Thu, 06 Nov 2014 15:14:05 +1100, Chris Angelico wrote: > > On Thu, Nov 6, 2014 at 3:00 PM, Denis McMahon wrote: > >> def baseword(s): > >> """find shortest sequence which repeats to generate s""" > >> return s[0:["".join([s[0:x]for k in range(int(len(s)/x)+1)])[0:len > >> (s)]for x in range(1,len(s)+1)].index(s)+1] > > > > That's hardly a PEP-8 compliant line, but I can help out a bit. > > > > return s[0:[(s[0:x]*(len(s)//x+1))[0:len(s)]for x in > > range(1,len(s)+1)].index(s)+1] > > > > That's still 83 characters without indentation, but it's close now. > > l = len > r = range > > but technically then it's no longer a one liner. > > > I love the algorithm. Took me a bit of analysis (and inspection of > > partial results) to understand what your code's doing, but it's stupidly > > elegant and elegantly stupid. > > :) > > Well yes, building that list is a stupid way to solve the problem, but I > can't see another way to do it in one line. It's an implementation of my > algorithm 3 (which I think you described) but working from the other end > as it were. 70-character expression, even with the spaces: >>> x = 't?st?k?t?st?k?t?st?' >>> x[:min(k for k in range(len(x) + 1) if x == (x[:k] * len(x))[:len(x)])] 't?st?k?' From crk at godblessthe.us Wed Nov 5 18:14:34 2014 From: crk at godblessthe.us (Clayton Kirkwood) Date: Wed, 5 Nov 2014 15:14:34 -0800 Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: <20141105222735.GA51461@cskk.homeip.net> References: <20141105222735.GA51461@cskk.homeip.net> Message-ID: <022e01cff94e$44637dd0$cd2a7970$@us> Yeah, the 11 was mesmerizing. You didn't need no stinkin' program to see how busy the system was, you just checked the lights. You could really tell when somebody was compiling or link/loading. As I've done many times since those days, I am amazed how many users could be using the system simultaneously (yes, general editing, but still...) and it wasn't a quick machine by any stretch. We had a whopping 384K memory and big multi-platter disks with a whopping 65MB. Still think in terms of PIP sometimes... Clayton >-----Original Message----- >From: Python-list [mailto:python-list- >bounces+crk=godblessthe.us at python.org] On Behalf Of Cameron Simpson >Sent: Wednesday, November 05, 2014 2:28 PM >To: python-list at python.org >Subject: Re: [OFF-TOPIC] It is true that is impossible write in binary >code, the lowest level of programming that you can write is in hex code? > >On 05Nov2014 15:38, Denis McMahon wrote: >>On Tue, 04 Nov 2014 21:30:06 -0500, Dennis Lee Bieber wrote: >>> If you have an old system with front-panel toggle switches, you >>set the >>> switches for binary values, and then push the "enter" switch. >> >>You've booted a PDP-8 then ;) > >Not me, but I have booted a PDP-11. Same deal:-) > >Our kernels had a patch in the idle loop that updated a specific memory >address with a regularly changing bit pattern (therefore the change rate >slowed down when the machine was busy). Post boot we'd set the memory >view toggle swithces to that address and be treated to a beautiful >Cylon-like shuttling pattern of red lights indiciating business. > >Cheers, >Cameron Simpson > >The most likely way for the world to be destroyed, most experts agree, >is by accident. That's where we come in; we're computer professionals. >We cause >accidents. - Nathaniel Borenstein >-- >https://mail.python.org/mailman/listinfo/python-list From nomail at invalid.com Thu Nov 6 03:32:20 2014 From: nomail at invalid.com (ast) Date: Thu, 6 Nov 2014 09:32:20 +0100 Subject: Moving a window on the screen Message-ID: <545b321a$0$2396$426a34cc@news.free.fr> Hi Why the following program doesn't work ? for x in range(0, 100, 10): fen.geometry("200x200+%d+10" % x) time.sleep(0.5) where fen is a window (fen = Tk()) The fen window goes from it's initial location to the last one but we dont see all the intermediate steps thx From rosuav at gmail.com Thu Nov 6 03:57:39 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Nov 2014 19:57:39 +1100 Subject: Moving a window on the screen In-Reply-To: <545b321a$0$2396$426a34cc@news.free.fr> References: <545b321a$0$2396$426a34cc@news.free.fr> Message-ID: On Thu, Nov 6, 2014 at 7:32 PM, ast wrote: > The fen window goes from it's initial location to the last one > but we dont see all the intermediate steps You usually don't want to use time.sleep() in a GUI program. Try doing the same thing, but with an event loop delay call instead; often, the display won't update until you go back to the main loop. ChrisA From wxjmfauth at gmail.com Thu Nov 6 03:57:23 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Thu, 6 Nov 2014 00:57:23 -0800 (PST) Subject: I need algorithm for my task In-Reply-To: References: <1962053862.5573720.1415210715670.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: Le jeudi 6 novembre 2014 08:59:22 UTC+1, Jussi Piitulainen a ?crit?: > Denis McMahon writes: > > On Thu, 06 Nov 2014 15:14:05 +1100, Chris Angelico wrote: > > > On Thu, Nov 6, 2014 at 3:00 PM, Denis McMahon wrote: > > >> def baseword(s): > > >> """find shortest sequence which repeats to generate s""" > > >> return s[0:["".join([s[0:x]for k in range(int(len(s)/x)+1)])[0:len > > >> (s)]for x in range(1,len(s)+1)].index(s)+1] > > > > > > That's hardly a PEP-8 compliant line, but I can help out a bit. > > > > > > return s[0:[(s[0:x]*(len(s)//x+1))[0:len(s)]for x in > > > range(1,len(s)+1)].index(s)+1] > > > > > > That's still 83 characters without indentation, but it's close now. > > > > l = len > > r = range > > > > but technically then it's no longer a one liner. > > > > > I love the algorithm. Took me a bit of analysis (and inspection of > > > partial results) to understand what your code's doing, but it's stupidly > > > elegant and elegantly stupid. > > > > :) > > > > Well yes, building that list is a stupid way to solve the problem, but I > > can't see another way to do it in one line. It's an implementation of my > > algorithm 3 (which I think you described) but working from the other end > > as it were. > > 70-character expression, even with the spaces: > > >>> x = 't?st?k?t?st?k?t?st?' > >>> x[:min(k for k in range(len(x) + 1) if x == (x[:k] * len(x))[:len(x)])] > 't?st?k?' Well. Congratulations. From __peter__ at web.de Thu Nov 6 04:15:20 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Nov 2014 10:15:20 +0100 Subject: Moving a window on the screen References: <545b321a$0$2396$426a34cc@news.free.fr> Message-ID: ast wrote: > Why the following program doesn't work ? > > for x in range(0, 100, 10): > fen.geometry("200x200+%d+10" % x) > time.sleep(0.5) > > > where fen is a window (fen = Tk()) > > The fen window goes from it's initial location to the last one > but we dont see all the intermediate steps As Chris says, using sleep() with a gui program usually doesn't work. While the script is sleeping the event loop doesn't run and consequently the user will not see any updates of the program's state. Instead of sleeping you have to schedule events that trigger a callback and then go back to the event loop. Such a callback may schedule another invocation of itself, thus giving you the desired effect: import tkinter as tk root = tk.Tk() xpositions = iter(range(0, 100, 10)) def move_next(): try: x = next(xpositions) except StopIteration: pass else: root.geometry("200x200+%d+10" % x) root.after(500, move_next) # have tkinter call move_next again # in about 500 milliseconds root.after_idle(move_next) root.mainloop() From nomail at invalid.com Thu Nov 6 04:18:08 2014 From: nomail at invalid.com (ast) Date: Thu, 6 Nov 2014 10:18:08 +0100 Subject: Moving a window on the screen In-Reply-To: References: <545b321a$0$2396$426a34cc@news.free.fr> Message-ID: <545b3cd8$0$2306$426a34cc@news.free.fr> "Chris Angelico" a ?crit dans le message de news:mailman.15536.1415264262.18130.python-list at python.org... > You usually don't want to use time.sleep() in a GUI program. Try doing > the same thing, but with an event loop delay call instead; often, the > display won't update until you go back to the main loop. Ok, thx, it works now with: import tkinter fen = tkinter.Tk() x=0 def moveW(): global x fen.geometry("200x200+%d+10" % x) x = x + 10 if (x < 1200): fen.after(50, moveW) moveW() From tjreedy at udel.edu Thu Nov 6 04:25:16 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 06 Nov 2014 04:25:16 -0500 Subject: Moving a window on the screen In-Reply-To: References: <545b321a$0$2396$426a34cc@news.free.fr> Message-ID: On 11/6/2014 3:57 AM, Chris Angelico wrote: > On Thu, Nov 6, 2014 at 7:32 PM, ast wrote: >> The fen window goes from it's initial location to the last one >> but we dont see all the intermediate steps > > You usually don't want to use time.sleep() in a GUI program. Try doing > the same thing, but with an event loop delay call instead; often, the > display won't update until you go back to the main loop. import tkinter as tk root = tk.Tk() x = 0 def march(): global x print(x) root.geometry("200x200+%d+%d" % (x,x)) x += 10 if x < 200: root.after(300, march) march() root.mainloop() -- Terry Jan Reedy From c.joydeep at gmail.com Thu Nov 6 05:13:40 2014 From: c.joydeep at gmail.com (Jaydip Chakrabarty) Date: Thu, 6 Nov 2014 10:13:40 +0000 (UTC) Subject: wxPython Boxsizers Message-ID: Hello, I am new to Python. I am learning boxsizer. I want to put two buttons on my panel. One at top right corner and one at bottom right corner. How do I achieve this? Thanks From info at egenix.com Thu Nov 6 05:19:50 2014 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Thu, 06 Nov 2014 11:19:50 +0100 Subject: ANN: eGenix ThreadLock Distribution 2.13.0.1 Message-ID: <545B4B46.6050801@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com ThreadLock Distribution Version 2.13.0.1 eGenix is making a ThreadLock binary distribution available to simplify the setup for users of our mxODBC Plone/Zope database adapter. This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-ThreadLock-Distribution-2.13.0.1.html ________________________________________________________________________ INTRODUCTION Several people have approached us about a problem they are facing with installing our mxODBC database adapter for Plone and Zope: http://www.egenix.com/products/zope/mxODBCZopeDA/ The adapter product has dependencies on * ThreadLock * Products.ZSQLMethods The Products.ZSQLMethods package is a pure Python package, so it installs fine on all platforms. ThreadLock comes with a Python C extension, so buildout needs to either find egg files for the platforms or have a compiler installed to build the C extensions. On Unix platforms, installing a compiler is fairly straight forward, but on Windows setting up compilers for Python is difficult and the ThreadLock entry on PyPI only comes with egg files for Python 2.6 on Windows. ________________________________________________________________________ SOLUTION To overcome this problem, we have taken the ThreadLock package and created an internal setup to have it compiled by our build farm. You can now use these buildout configuration settings to pull the egg files from our indexes. For UCS2 Python builds (16-bit Unicode on Unix, Python for Windows): -------------------------------------------------------------------- [buildout] ... find-links = ... https://downloads.egenix.com/python/index/ucs2/ eggs = ... ThreadLock [versions] ... ThreadLock = 2.13.0.1 For UCS4 Python builds (32-bit Unicode on Unix): -------------------------------------------------------------------- [buildout] ... find-links = ... https://downloads.egenix.com/python/index/ucs4/ eggs = ... ThreadLock [versions] ... ThreadLock = 2.13.0.1 Available binaries ------------------ We provide egg files for Linux x86 and x64, Windows x86 and x64 as well as the source package as fallback solution. The binaries were compiled with Python 2.4, 2.5, 2.6 and 2.7. Version number -------------- Note that we have added a build number to the package version. This allows us to issue updates to the package builds should these be necessary and also makes sure that your buildout will use the packages from our indexes instead of PyPI or other indexes. ________________________________________________________________________ ABOUT THE EGENIX MXODBC PLONE/ZOPE DATABASE ADAPTER The eGenix mxODBC Zope DA allows you to easily connect your Zope or Plone CMS installation to just about any database backend on the market today, giving you the reliability of the commercially supported eGenix product mxODBC and the flexibility of the ODBC standard as middle-tier architecture. The mxODBC Zope Database Adapter is highly portable, just like Zope itself and provides a high performance interface to all your ODBC data sources, using a single well-supported interface on Windows, Linux, Mac OS X, FreeBSD and other platforms. This makes it ideal for deployment in ZEO Clusters and Zope hosting environments where stability and high performance are a top priority, establishing an excellent basis and scalable solution for your Plone CMS. Product page: http://www.egenix.com/products/zope/mxODBCZopeDA/ ________________________________________________________________________ MORE INFORMATION For more information on the eGenix ThreadLock distribution, the eGenix mxODBC Zope DA, licensing and download instructions, please write to sales at egenix.com. Enjoy, -- -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Nov 06 2014) >>> Python Projects, Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope/Plone.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2014-10-24: Released eGenix pyOpenSSL 0.13.5 ... http://egenix.com/go63 ::::: Try our mxODBC.Connect Python Database Interface for free ! :::::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From joel.goldstick at gmail.com Thu Nov 6 05:31:01 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 6 Nov 2014 05:31:01 -0500 Subject: wxPython Boxsizers In-Reply-To: References: Message-ID: On Thu, Nov 6, 2014 at 5:13 AM, Jaydip Chakrabarty wrote: > Hello, > > I am new to Python. I am learning boxsizer. I want to put two buttons on > my panel. One at top right corner and one at bottom right corner. How do > I achieve this? > > Thanks First, what version of python. What is boxsizer? Show some code of what you have tried. > -- > https://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick http://joelgoldstick.com From breamoreboy at yahoo.co.uk Thu Nov 6 05:41:14 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 06 Nov 2014 10:41:14 +0000 Subject: wxPython Boxsizers In-Reply-To: References: Message-ID: On 06/11/2014 10:13, Jaydip Chakrabarty wrote: > Hello, > > I am new to Python. I am learning boxsizer. I want to put two buttons on > my panel. One at top right corner and one at bottom right corner. How do > I achieve this? > > Thanks > Probably best asked here https://groups.google.com/forum/#!forum/wxpython-users also available as http://news.gmane.org/gmane.comp.python.wxpython -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From python at mrabarnett.plus.com Thu Nov 6 06:32:53 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 06 Nov 2014 11:32:53 +0000 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: <201411052305.02610.gheskett@wdtv.com> References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <201411052305.02610.gheskett@wdtv.com> Message-ID: <545B5C65.2090403@mrabarnett.plus.com> On 2014-11-06 04:05, Gene Heskett wrote: > On Wednesday 05 November 2014 21:52:42 Mark Lawrence did opine > And Gene did reply: >> On 06/11/2014 02:37, Dave Angel wrote: >> > Chris Angelico Wrote in message: >> >> On Thu, Nov 6, 2014 at 2:56 AM, Larry Martell > wrote: >> >>>> And I don't think >> >>>> Larry was actually offended; it's just that some questions don't >> >>>> really have easy answers - imagine someone asking a great >> >>>> mathematician "But how do you KNOW that 2 + 2 is 4? Where's it >> >>>> written down?"... all he can say is "It is". >> >>> >> >>> Yeah, I'm on a lot of lists and lately I've seen a lot of 'I'm not >> >>> a programmer, but I want to write code and I need someone to tell >> >>> me how." Gets to you after a while. >> >> >> >> Too true. Those same people are unlikely to go to a gathering of >> >> civil engineers and say "I'm no expert, but I want to build a >> >> bridge and I need someone to tell me how", yet somehow it's >> >> expected to be possible with software. >> >> >> >> ChrisA >> > >> > Or I'm no expert but I need someone to show me how; build me one >> > >> > here in my front yard. >> >> Against a requirements specification that changes on a daily basis, I >> want it delivered yesterday and no you can't have any more resources to >> help out, so don't ask :) > With, or without a toll booth and operator? > Both, make it configurable. In fact, make the length configurable too, in case I want to use it across another river. From c.joydeep at gmail.com Thu Nov 6 08:50:37 2014 From: c.joydeep at gmail.com (Joy Deep) Date: Thu, 6 Nov 2014 05:50:37 -0800 (PST) Subject: wxPython Boxsizers In-Reply-To: References: Message-ID: I am using Python 2.7.6 Here is the code I am trying: import wx class MyFrame(wx.Frame): def __init__(self, *args, **kid's): wx.Frame.__init__(self, *args, **kwds) self.button_1 = wx.Button(self, wx.ID_ANY, "button_1") self.button_2 = wx.Button(self, wx.ID_ANY, "button_2") sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer_1.Add(self.button_1, 0, wx.ALL | wx.ALIGN_RIGHT, 1) sizer_1.Add(self.button_2, 0, wx.ALL | wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM, 1) self.SetSizer(sizer_1) sizer_1.Fit(self) self.Layout() if __name__ == "__main__": app = wx.PySimpleApp(0) frame_1 = MyFrame(None, wx.ID_ANY, "") frame_1.Show() app.MainLoop() Thanks. On Thursday, November 6, 2014 4:01:53 PM UTC+5:30, Joel Goldstick wrote: > On Thu, Nov 6, 2014 at 5:13 AM, Jaydip Chakrabarty wrote: > > Hello, > > > > I am new to Python. I am learning boxsizer. I want to put two buttons on > > my panel. One at top right corner and one at bottom right corner. How do > > I achieve this? > > > > Thanks > > First, what version of python. What is boxsizer? Show some code of > what you have tried. > > -- > > https://mail.python.org/mailman/listinfo/python-list > > > > -- > Joel Goldstick > http://joelgoldstick.com From akbari.farshad at gmail.com Thu Nov 6 09:49:46 2014 From: akbari.farshad at gmail.com (farshad akbari) Date: Thu, 6 Nov 2014 06:49:46 -0800 (PST) Subject: Python 3.4.2 + PyQt4 + PyCharm 3.4.1 In-Reply-To: References: Message-ID: On Saturday, November 1, 2014 3:11:54 PM UTC+3:30, Juan Christian wrote: > No one here uses PyCharm and Qt? =/ > > > On Wed, Oct 29, 2014 at 8:45 PM, Juan Christian wrote: > > It only occurs whule using PyCharm I tried it via pure terminal and everything works... =/ > > > > > On Tue, Oct 28, 2014 at 7:45 PM, Juan Christian wrote: > > > Python 3.4.2 Windows x64 > PyQt4 4.11.2 Py3.4 Qt4.8.6 (x64) > > PyCharm 3.4.1 Pro Edition > > > > > So, PyCharm works 100% with everything here but PyQt. > > > I have this folder structure: > > > Disk C: > > PyQt4 > >> Lib/site-packages/PyQt4/(tons of files here) > > > > Python34 (normal/default installation) > > > --- > > > I tried copying the 'PyQt4' folder to my 'Python34/Lib/site-packages' folder but when I try to code something Qt related on PyCharm I get this issue: > > > > Some skeletons failed to generate: 19 modules failed in 1 interpreter. Details... > > > > Failed modules > > > Python 3.4.2? > PyQt4.QAxContainer > PyQt4.Qsci > PyQt4.QtCore > PyQt4.QtDeclarative > PyQt4.QtDesigner > PyQt4.QtGui > PyQt4.QtHelp > PyQt4.QtMultimedia > PyQt4.QtNetwork > PyQt4.QtOpenGL > PyQt4.QtScript > PyQt4.QtScriptTools > PyQt4.QtSql > PyQt4.QtSvg > PyQt4.QtTest > PyQt4.QtWebKit > PyQt4.QtXml > PyQt4.QtXmlPatterns > PyQt4.phonon > > > Generation of skeletons for the modules above will be tried again when the modules are updated or a new version of generator is available. > > > And PyCharm tells me that my 'import PyQt4.ANYTHING_HERE import *' has 'Unresolved references'. > > > --- > > > When I try to install the PyQt4 via the installer, in the default location (C:/Python34) I get an even 'worse' error, whenever PyCharm try to update the skeletons or something like that (that is, whenever I open a file there...), I get tons and tons of the same error, 'Error while accessing memory at address XXXX', and 'python.exe' stops working. i have this problem too, and it's so annoying. From juan0christian at gmail.com Thu Nov 6 10:00:03 2014 From: juan0christian at gmail.com (Juan Christian) Date: Thu, 06 Nov 2014 15:00:03 +0000 Subject: Python 3.4.2 + PyQt4 + PyCharm 3.4.1 References: Message-ID: Resolved, kinda. Just use PySide instead of PyQt. Remove everything PyQt related from PyCharm and install PySide using the PyCharm plugins window. PySide has access to all modules and packages that PyQt has, but now you need to import like "from PySide.<**> import *". On Thu, Nov 6, 2014 at 12:50 farshad akbari wrote: > On Saturday, November 1, 2014 3:11:54 PM UTC+3:30, Juan Christian wrote: > > No one here uses PyCharm and Qt? =/ > > > > > > On Wed, Oct 29, 2014 at 8:45 PM, Juan Christian > wrote: > > > > It only occurs whule using PyCharm I tried it via pure terminal and > everything works... =/ > > > > > > > > > > On Tue, Oct 28, 2014 at 7:45 PM, Juan Christian > wrote: > > > > > > Python 3.4.2 Windows x64 > > PyQt4 4.11.2 Py3.4 Qt4.8.6 (x64) > > > > PyCharm 3.4.1 Pro Edition > > > > > > > > > > So, PyCharm works 100% with everything here but PyQt. > > > > > > I have this folder structure: > > > > > > Disk C: > > > PyQt4 > > >> Lib/site-packages/PyQt4/(tons of files here) > > > > > > > Python34 (normal/default installation) > > > > > > --- > > > > > > I tried copying the 'PyQt4' folder to my 'Python34/Lib/site-packages' > folder but when I try to code something Qt related on PyCharm I get this > issue: > > > > > > > > Some skeletons failed to generate: 19 modules failed in 1 interpreter. > Details... > > > > > > > > Failed modules > > > > > > Python 3.4.2 > > PyQt4.QAxContainer > > PyQt4.Qsci > > PyQt4.QtCore > > PyQt4.QtDeclarative > > PyQt4.QtDesigner > > PyQt4.QtGui > > PyQt4.QtHelp > > PyQt4.QtMultimedia > > PyQt4.QtNetwork > > PyQt4.QtOpenGL > > PyQt4.QtScript > > PyQt4.QtScriptTools > > PyQt4.QtSql > > PyQt4.QtSvg > > PyQt4.QtTest > > PyQt4.QtWebKit > > PyQt4.QtXml > > PyQt4.QtXmlPatterns > > PyQt4.phonon > > > > > > Generation of skeletons for the modules above will be tried again when > the modules are updated or a new version of generator is available. > > > > > > And PyCharm tells me that my 'import PyQt4.ANYTHING_HERE import *' has > 'Unresolved references'. > > > > > > --- > > > > > > When I try to install the PyQt4 via the installer, in the default > location (C:/Python34) I get an even 'worse' error, whenever PyCharm try to > update the skeletons or something like that (that is, whenever I open a > file there...), I get tons and tons of the same error, 'Error while > accessing memory at address XXXX', and 'python.exe' stops working. > > i have this problem too, > and it's so annoying. > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wrw at mac.com Thu Nov 6 09:19:10 2014 From: wrw at mac.com (William Ray Wing) Date: Thu, 06 Nov 2014 09:19:10 -0500 Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: <022e01cff94e$44637dd0$cd2a7970$@us> References: <20141105222735.GA51461@cskk.homeip.net> <022e01cff94e$44637dd0$cd2a7970$@us> Message-ID: > On Nov 5, 2014, at 6:14 PM, Clayton Kirkwood wrote: > > Yeah, the 11 was mesmerizing. You didn't need no stinkin' program to see how > busy the system was, you just checked the lights. You could really tell when > somebody was compiling or link/loading. As I've done many times since those > days, I am amazed how many users could be using the system simultaneously > (yes, general editing, but still...) and it wasn't a quick machine by any > stretch. We had a whopping 384K memory and big multi-platter disks with a > whopping 65MB. Still think in terms of PIP sometimes? > And TECO. . . > Clayton From invalid at invalid.invalid Thu Nov 6 10:22:45 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 6 Nov 2014 15:22:45 +0000 (UTC) Subject: Python has arrived! Message-ID: According to http://www.theregister.co.uk/2014/11/06/hackers_use_gmail_drafts_as_dead_drops_to_control_malware_bots: "Attacks occur in two phases. Hackers first infect a targeted machine via simple malware that installs Python onto the device, [...]" -- Grant Edwards grant.b.edwards Yow! I always have fun at because I'm out of my gmail.com mind!!! From ian.g.kelly at gmail.com Thu Nov 6 10:51:20 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 6 Nov 2014 08:51:20 -0700 Subject: Real-world use of Counter In-Reply-To: References: Message-ID: On Nov 6, 2014 1:06 AM, "Rustom Mody" wrote: > In studying (somewhat theoretically) the general world of > collection data structures we see > - sets -- neither order nor repetition > - bags -- no order, repetition significant > - lists -- both order and repetition > > Sometimes 'bag' is called 'multiset' > However counter is a weird non-standard name that overloads > an already overloaded term -- 'Counter' has a very standard meaning in programming and in hardware design. "Bag" is also nonstandard. Other nonstandard names for the same type include list, heap, bunch, sample, weighted set, occurrence set and fireset. Knuth uses multiset, so let's stick with that. As for Counter already having meanings in CS, the Python Counter is compatible with those. > Calling a bag as counter is inappropriate for an analogous reason > to why calling a dictionary as a 'hash' is inappropriate -- > it confuses an implementation detail for fundamental semantics. I've never liked the term "bag". In addition to being nonstandard it's also very nonintuitive. "Multiset" is fine, except that it implies the collection is a type of set, which the Python Counter is not. The name "Counter" describes the intended use case, not the implementation, so I think it's fine. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jtim.arnold at gmail.com Thu Nov 6 11:37:00 2014 From: jtim.arnold at gmail.com (Tim) Date: Thu, 6 Nov 2014 08:37:00 -0800 (PST) Subject: help with creating dict from string Message-ID: hi, I have strings coming in with this format: '[one=two, three=four five, six, seven=eight]' and I want to create from that string, this dictionary: {'one':'two', 'three':'four five', 'six':True, 'seven':'eight'} These are option strings, with each key-value pair separated by commas. Where there is a value, the key-value pair is separated by '='. This is how I started (where s is the string): s = s.replace('[','').replace(']','') s = [x.split('=') for x in s.split(',')] [['one', 'two'], [' three', 'four five'], [' six'], [' seven', 'eight']] I know I can iterate and strip each item, fixing single-element keys as I go. I just wondered if I'm missing something more elegant. If it wasn't for the leading spaces and the boolean key, the dict() constructor would have been sweet. thanks for any ideas, --Tim From mbg1708 at planetmail.com Thu Nov 6 12:24:31 2014 From: mbg1708 at planetmail.com (mbg1708 at planetmail.com) Date: Thu, 6 Nov 2014 09:24:31 -0800 (PST) Subject: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? In-Reply-To: References: Message-ID: <2aa4c06d-bcd9-4b74-8ff0-8e10c55c2986@googlegroups.com> On Tuesday, 4 November 2014 16:49:36 UTC, fran?ai s wrote: > I intend to write in lowest level of computer programming as a hobby. > > It is true that is impossible write in binary code, the lowest level > of programming that you can write is in hex code? > > What is the lowest level of programming computers that you can write ? > > Is binary code? > > Is hex code? > > Is another machine code? Honestly do not know if it is true that there > is another machine code beyond the binary and hex code. > > Is Assembly? If you want a really brilliant (and simple) book about the process of designing, structuring and building programs in assembly language, I'd recommend finding a copy of a book called A Programmer's Notebook written by David M Cortesi. The context is out of date (8080/Z-80 assembly programs for CP/M), but the overall structure of each chapter is brilliant: the development of decent designs, followed by a discussion of possible approaches to programming, followed by a detailed discussion of the development of the assembly language, and finally a final assembly code listing. One advantage of this book is that the 8080/Z-80 instruction set and the interface to CP/M are both relatively simple to grasp (compared with modern CPUs and modern OSs). That said, the lessons from this book translate to any assembly programming task. Good luck. From __peter__ at web.de Thu Nov 6 12:40:44 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Nov 2014 18:40:44 +0100 Subject: help with creating dict from string References: Message-ID: Tim wrote: > hi, I have strings coming in with this format: > > '[one=two, three=four five, six, seven=eight]' > > and I want to create from that string, this dictionary: > {'one':'two', 'three':'four five', 'six':True, 'seven':'eight'} > > These are option strings, with each key-value pair separated by commas. > Where there is a value, the key-value pair is separated by '='. > > This is how I started (where s is the string): > s = s.replace('[','').replace(']','') > s = [x.split('=') for x in s.split(',')] > > [['one', 'two'], [' three', 'four five'], [' six'], [' seven', > [['eight']] > > I know I can iterate and strip each item, fixing single-element keys as I > go. > > I just wondered if I'm missing something more elegant. If it wasn't for > the leading spaces and the boolean key, the dict() constructor would have > been sweet. Not everything has to be a one-liner ;) If it works I don't think something >>> s = '[one=two, three=four five, six, seven=eight]' >>> def fix(pair): ... key, eq, value = pair.partition("=") ... return key.strip(), value if eq else True ... >>> dict(fix(t) for t in s.strip("[]").split(",")) {'three': 'four five', 'seven': 'eight', 'one': 'two', 'six': True} is particularly inelegant. Are you sure that your grammar is not more complex than your example, e. g. that "," cannot occur in the values? From jtim.arnold at gmail.com Thu Nov 6 14:18:46 2014 From: jtim.arnold at gmail.com (Tim) Date: Thu, 6 Nov 2014 11:18:46 -0800 (PST) Subject: help with creating dict from string In-Reply-To: References: Message-ID: On Thursday, November 6, 2014 12:41:10 PM UTC-5, Peter Otten wrote: > Tim wrote: > > > hi, I have strings coming in with this format: > > > > '[one=two, three=four five, six, seven=eight]' > > > > and I want to create from that string, this dictionary: > > {'one':'two', 'three':'four five', 'six':True, 'seven':'eight'} > > > > snip > > Not everything has to be a one-liner ;) If it works I don't think something > > >>> s = '[one=two, three=four five, six, seven=eight]' > >>> def fix(pair): > ... key, eq, value = pair.partition("=") > ... return key.strip(), value if eq else True > ... > >>> dict(fix(t) for t in s.strip("[]").split(",")) > {'three': 'four five', 'seven': 'eight', 'one': 'two', 'six': True} > > is particularly inelegant. Are you sure that your grammar is not more > complex than your example, e. g. that "," cannot occur in the values? hi Peter, I definitely wouldn't say that is inelegant :-) I had never used the partition method and I didn't realize (or maybe remember) that strip could take a string of characters, not just one. Oh yes, I am positive about the grammar--no commas are allowed in the values. I think your solution is pretty elegant. Thanks for your help! --Tim From john_ladasky at sbcglobal.net Thu Nov 6 15:21:07 2014 From: john_ladasky at sbcglobal.net (John Ladasky) Date: Thu, 6 Nov 2014 12:21:07 -0800 (PST) Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> Message-ID: On Tuesday, November 4, 2014 11:12:31 AM UTC-8, Ethan Furman wrote: > If you really absolutely positively have to have the signature be correct for each instance, you may to either look at a > function creating factory, a class creating factory, or a meta-class. +1. Overriding __call__() within the class definition, over and over again, with different function, looks awkward to me. From versalytics at gmail.com Thu Nov 6 17:09:18 2014 From: versalytics at gmail.com (versalytics at gmail.com) Date: Thu, 6 Nov 2014 22:09:18 +0000 Subject: =?utf-8?Q?Re:_help_with_creating_dict_from_string?= In-Reply-To: References: , Message-ID: <545bf2af.50996b0a.368c.ffffe5c0@mx.google.com> On Thursday, November 6, 2014 12:41:10 PM UTC-5, Peter Otten wrote: > Tim wrote: > > > hi, I have strings coming in with this format: > > > > '[one=two, three=four five, six, seven=eight]' > > > > and I want to create from that string, this dictionary: > > {'one':'two', 'three':'four five', 'six':True, 'seven':'eight'} > > > > snip > > Not everything has to be a one-liner ;) If it works I don't think something > > >>> s = '[one=two, three=four five, six, seven=eight]' > >>> def fix(pair): > ... key, eq, value = pair.partition("=") > ... return key.strip(), value if eq else True > ... > >>> dict(fix(t) for t in s.strip("[]").split(",")) > {'three': 'four five', 'seven': 'eight', 'one': 'two', 'six': True} > > is particularly inelegant. Are you sure that your grammar is not more > complex than your example, e. g. that "," cannot occur in the values? hi Peter, I definitely wouldn't say that is inelegant :-) I had never used the partition method and I didn't realize (or maybe remember) that strip could take a string of characters, not just one. Oh yes, I am positive about the grammar--no commas are allowed in the values. I think your solution is pretty elegant. Thanks for your help! --Tim -- This is a very clever solution. I just came across the need for something similar. Good question, excellent solution. Thank you! -------------- next part -------------- An HTML attachment was scrubbed... URL: From ccylily1314 at gmail.com Thu Nov 6 20:42:26 2014 From: ccylily1314 at gmail.com (Darren Chen) Date: Thu, 6 Nov 2014 17:42:26 -0800 (PST) Subject: I need algorithm for my task In-Reply-To: References: <50a7df31-ee6c-45f5-9dd8-6ac895ec46cf@googlegroups.com> Message-ID: Probably homework, you are a good man ! From sturla.molden at gmail.com Thu Nov 6 22:45:19 2014 From: sturla.molden at gmail.com (Sturla Molden) Date: Fri, 7 Nov 2014 03:45:19 +0000 (UTC) Subject: Python has arrived! References: Message-ID: <1661847952437024668.827511sturla.molden-gmail.com@news.gmane.org> Grant Edwards wrote: > According to > http://www.theregister.co.uk/2014/11/06/hackers_use_gmail_drafts_as_dead_drops_to_control_malware_bots: > > "Attacks occur in two phases. Hackers first infect a targeted > machine via simple malware that installs Python onto the device, > [...]" > A virus that runs on Python. It had to happen sooner or later. From steve+comp.lang.python at pearwood.info Thu Nov 6 23:18:01 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 07 Nov 2014 15:18:01 +1100 Subject: [Python-Dev] Dinamically set __call__ method References: <545919B6.7040007@stoneleaf.us> Message-ID: <545c47fa$0$13005$c3e8da3$5496439d@news.astraweb.com> Roberto Mart?nez wrote: > Yikes, I didn't realize the difference in inheritance. > > The thing with this is tricky. I need the change in the instance, not in > the class, because I have multiple instances and all of them must have > different implementations of __call__. > > The workaround of calling a different method inside __call__ is not valid > for my case because I want to change the *signature* of the function also > -for introspection reasons. This is somewhat of a code smell. It's a bit whiffy, which doesn't *necessarily* mean it is off, only that it could be. You should think hard about your use-case and consider alternative strategies. Like, the strategy design pattern :-) The real problem here is that the individual functions have different signatures. If they had the same signature, then you could bake that into the __call__ method and simply call a per-instance method: class X: # Variation on the strategy design pattern. def __call__(self, spam, eggs=12): method = getattr(self, 'my_custom_method', None) if method is None: # Default behaviour. ... else: return method(self, spam, eggs) Then simply add a `my_custom_method` function to the individual instances. The different functions would provide different algorithms (implementations) for the same task, with the same interface. This is exactly the problem with the Strategy design pattern is supposed to solve. But the smelly part here is that your custom functions take different signatures, which suggests that they aren't providing different algorithms for the same task. Different signatures means that they are *not* interchangeable, that they have different calling conventions and presumably do different things: # This only works in Python 2 with "classic (old-style) classes" a, b, c = [X() for i in range(3)] a.__call__ = lambda self: self.spam + 1 b.__call__ = lambda self, x, y: (self.eggs or x)*y c.__call__ = lambda self, value: setattr(self, "spam", value) That's a strong violation of the expectation that any two instances of the same class should be more or less interchangeable, with at most a few exceptional cases (e.g. you can't swap the int instance 0 for the instance 2 in the expression x/2). But it's not *always* wrong, functions themselves are all instances of FunctionType, and every instance does something different when called. E.g. while you could swap math.sin for math.cos, since both take the same parameters, you cannot swap math.sin for len. Nevertheless, I urge you strongly to think hard about what problem you are really trying to solve. "Dynamically override __call__" is just a means to an end. Perhaps there is something less magically you can do to solve the problem? Is there some way to ensure that all the instances have the same interface? This might be easy, given that they can store per-instance state. If instance "a" needs an extra parameter that other instances don't, perhaps it can take it from an instance attribute instead of an argument. -- Steven From ian.g.kelly at gmail.com Thu Nov 6 23:43:00 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 6 Nov 2014 21:43:00 -0700 Subject: Python has arrived! In-Reply-To: <1661847952437024668.827511sturla.molden-gmail.com@news.gmane.org> References: <1661847952437024668.827511sturla.molden-gmail.com@news.gmane.org> Message-ID: On Nov 6, 2014 10:47 PM, "Sturla Molden" wrote: > > Grant Edwards wrote: > > According to > > http://www.theregister.co.uk/2014/11/06/hackers_use_gmail_drafts_as_dead_drops_to_control_malware_bots : > > > > "Attacks occur in two phases. Hackers first infect a targeted > > machine via simple malware that installs Python onto the device, > > [...]" > > > > A virus that runs on Python. It had to happen sooner or later. It's not a Python virus. The infection vector can be anything. The interesting part is that they're using browser automation to open a real-time, encrypted, virtually undetectable and untraceable channel to the malware over a port (443) that is frequently used and very rarely blocked, via a host (gmail.com) that is also frequently used and rarely blocked (and there would likely be plenty of alternatives to choose from if it were), and without needing to create any sort of server on the target machine. The fact that Python is involved is incidental. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Fri Nov 7 00:05:00 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 6 Nov 2014 22:05:00 -0700 Subject: Real-world use of Counter In-Reply-To: References: Message-ID: On Nov 6, 2014 10:51 AM, "Ian Kelly" wrote: > > On Nov 6, 2014 1:06 AM, "Rustom Mody" wrote: > > Calling a bag as counter is inappropriate for an analogous reason > > to why calling a dictionary as a 'hash' is inappropriate -- > > it confuses an implementation detail for fundamental semantics. > > I've never liked the term "bag". In addition to being nonstandard it's also very nonintuitive. "Multiset" is fine, except that it implies the collection is a type of set, which the Python Counter is not. I was thinking about this today, and it seems to me that the Python Counter is not really even a multiset. * The size of a multiset would be the count of all the elements; the len of a Counter is only the number of keys. * The multiplicity of an element in a multiset is restricted to the natural numbers; the count of an element in a Counter can be any integer, even negative. * In a Counter, a key with a count of 0 is a distinct state from a key not being present at all; in the latter case the element is not in the Counter, while in the former case it *is* in the Counter. These states are also distinct for the purpose of equality. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Fri Nov 7 00:47:44 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 07 Nov 2014 16:47:44 +1100 Subject: Understanding "help" command description syntax - explanation needed References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <000601cff8f4$7dc40220$794c0660$@gmail.com> Message-ID: <545c5d01$0$12989$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > On Wed, Nov 5, 2014 at 11:31 PM, Ivan Evstegneev > wrote: >>>> That's what I'm talking about (asking actually), where do you know it >>>> from? >> >>>>I know it because I've been a programmer for 39 years. >> >> I didn't intend to offence anyone here. Just asked a questions ^_^ > > Don't worry about offending people. Even if you do annoy one or two, > there'll be plenty of us who know to be patient :) And I don't think > Larry was actually offended; it's just that some questions don't > really have easy answers - imagine someone asking a great > mathematician "But how do you KNOW that 2 + 2 is 4? Where's it written > down?"... all he can say is "It is". An ordinary mathematician will say: "Hold up two fingers. Count them, and you get one, two. Now hold up another two fingers. Count them, and you will get two again. Hold them together, count the lot, and you get one, two, three, four. Therefore, 2+2 = 4." A good mathematician might start with the empty set, ? = {}. [Aside: if the symbol looks like a small box, try changing your font -- it is supposed to be a circle with a slash through it. Lucinda Typewriter has the glyph for '\N{EMPTY SET}'.] That empty set represents zero. Take the set of all empty sets, {?} = {{}}, which represents one. Now we know how to count: after any number, represented by some set, the *next* number is represented by the simplest set containing the previous set. Having defined counting, the good mathematician can define addition, and go on to prove that 2+2 = 4. This is, essentially, a proof of Peano Arithmetic (PA), which one can take as effectively the basic arithmetic of counting fingers, sheep or sticks. But a *great* mathematician will say, "Hmmm, actually, we don't *know* that 2+2 equals 4, because we cannot prove that arithmetic is absolutely consistent. If arithmetic is not consistent, then we might simultaneously prove that 2+2 = 4 and 2+2 ? 4, which is unlikely but not inconceivable." Fields medallist Vladimir Voevodsky is a great mathematician, and he apparently believes that the consistency of Peano Arithmetic is still an open question. http://m-phi.blogspot.com.au/2011/05/voevodsky-consistency-of-pa-is-open.html Another way to look at this, not necessarily Voevodsky's approach, is to note that the existing proofs of PA's consistency are *relative* proofs of PA. E.g. they rely on the consistency of some other formal system, such as the Zermelo-Frankel axioms (ZF). If ZF is consistent, so is PA, but we don't know that ZF is consistent... -- Steven From rosuav at gmail.com Fri Nov 7 01:25:44 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 7 Nov 2014 17:25:44 +1100 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: <545c5d01$0$12989$c3e8da3$5496439d@news.astraweb.com> References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <000601cff8f4$7dc40220$794c0660$@gmail.com> <545c5d01$0$12989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Nov 7, 2014 at 4:47 PM, Steven D'Aprano wrote: > But a *great* mathematician will say, "Hmmm, actually, we don't *know* that > 2+2 equals 4, because we cannot prove that arithmetic is absolutely > consistent. If arithmetic is not consistent, then we might simultaneously > prove that 2+2 = 4 and 2+2 ? 4, which is unlikely but not inconceivable." > And the mother of a young child will say "It just is. Now eat your greens." ChrisA From ccylily1314 at gmail.com Fri Nov 7 01:50:29 2014 From: ccylily1314 at gmail.com (Darren Chen) Date: Thu, 6 Nov 2014 22:50:29 -0800 (PST) Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <88543346.5460.1415188500802.JavaMail.root@sequans.com> <000501cff8f1$ed99cc40$c8cd64c0$@gmail.com> Message-ID: <57af10d4-3891-4eec-8c46-5fa625ebe591@googlegroups.com> ? 2014?11?5????UTC+8??8?17?11??Larry.... at gmail.com??? > On Wed, Nov 5, 2014 at 7:13 AM, Ivan Evstegneev wrote: > > Firtst of all thanks for reply. > > > >>>brackets [] means that the argument is optional. > > > > That's what I'm talking about (asking actually), where do you know it from? > > I know it because I've been a programmer for 39 years. that's awesome?? From dieter at handshake.de Fri Nov 7 01:59:56 2014 From: dieter at handshake.de (dieter) Date: Fri, 07 Nov 2014 07:59:56 +0100 Subject: [Python-Dev] Dinamically set __call__ method References: <545919B6.7040007@stoneleaf.us> Message-ID: <87a943qyvn.fsf@handshake.de> John Ladasky writes: > On Tuesday, November 4, 2014 11:12:31 AM UTC-8, Ethan Furman wrote: > >> If you really absolutely positively have to have the signature be correct for each instance, you may to either look at a >> function creating factory, a class creating factory, or a meta-class. > > +1. Overriding __call__() within the class definition, over and over again, with different function, looks awkward to me. A possibility to get the original approach implemented looks like: make "__call__" a descriptor on the class which looks up the real method on the instance. From hayesstw at telkomsa.net Thu Nov 6 23:54:54 2014 From: hayesstw at telkomsa.net (Steve Hayes) Date: Fri, 07 Nov 2014 06:54:54 +0200 Subject: Python has arrived! References: Message-ID: On Thu, 6 Nov 2014 15:22:45 +0000 (UTC), Grant Edwards wrote: >According to http://www.theregister.co.uk/2014/11/06/hackers_use_gmail_drafts_as_dead_drops_to_control_malware_bots: > > "Attacks occur in two phases. Hackers first infect a targeted > machine via simple malware that installs Python onto the device, > [...]" > 404: Page not found -- Steve Hayes from Tshwane, South Africa Web: http://www.khanya.org.za/stevesig.htm Blog: http://khanya.wordpress.com E-mail - see web page, or parse: shayes at dunelm full stop org full stop uk From HeinzSchmitz at gmx.net Fri Nov 7 04:10:14 2014 From: HeinzSchmitz at gmx.net (Heinz Schmitz) Date: Fri, 07 Nov 2014 10:10:14 +0100 Subject: Python has arrived! References: Message-ID: <4s2p5al5v8ms7cq0cpvq2oscqg0sm8lk1j@4ax.com> Steve Hayes wrote: >>According to http://www.theregister.co.uk/2014/11/06/hackers_use_gmail_drafts_as_dead_drops_to_control_malware_bots: >> >> "Attacks occur in two phases. Hackers first infect a targeted >> machine via simple malware that installs Python onto the device, >> [...]" >[Fri, 07 Nov 2014 06:54:54 +0200] >404: Page not found 2014-11-07 10:06 MEZ -> Page found. Regards, H. From greg.ewing at canterbury.ac.nz Fri Nov 7 04:15:39 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Fri, 07 Nov 2014 22:15:39 +1300 Subject: Python has arrived! In-Reply-To: References: Message-ID: Steve Hayes wrote: > On Thu, 6 Nov 2014 15:22:45 +0000 (UTC), Grant Edwards > wrote: > >>According to http://www.theregister.co.uk/2014/11/06/hackers_use_gmail_drafts_as_dead_drops_to_control_malware_bots: > > 404: Page not found Works if you remove the spurious colon from the end of the url. -- Greg From cl at isbd.net Fri Nov 7 04:36:51 2014 From: cl at isbd.net (cl at isbd.net) Date: Fri, 7 Nov 2014 09:36:51 +0000 Subject: Understanding "help" command description syntax - explanation needed References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <88543346.5460.1415188500802.JavaMail.root@sequans.com> <000501cff8f1$ed99cc40$c8cd64c0$@gmail.com> <57af10d4-3891-4eec-8c46-5fa625ebe591@googlegroups.com> Message-ID: Darren Chen wrote: > ? 2014?11?5????UTC+8??8?17?11??Larry.... at gmail.com??? > > On Wed, Nov 5, 2014 at 7:13 AM, Ivan Evstegneev wrote: > > > Firtst of all thanks for reply. > > > > > >>>brackets [] means that the argument is optional. > > > > > > That's what I'm talking about (asking actually), where do you know it from? > > > > I know it because I've been a programmer for 39 years. > > that's awesome?? Well I started in 1971 or thereabouts. -- Chris Green ? From bob.martin at excite.com Fri Nov 7 07:17:07 2014 From: bob.martin at excite.com (Bob Martin) Date: Fri, 07 Nov 2014 12:17:07 GMT Subject: Understanding "help" command description syntax - explanation needed References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <88543346.5460.1415188500802.JavaMail.root@sequans.com> <000501cff8f1$ed99cc40$c8cd64c0$@gmail.com> <57af10d4-3891-4eec-8c46-5fa625ebe591@googlegroups.com> Message-ID: in 730867 20141107 093651 cl at isbd.net wrote: >Darren Chen wrote: >> ??? 2014???11???5????????????UTC+8??????8???17???11??????Larry.... at gmail.com????????? >> > On Wed, Nov 5, 2014 at 7:13 AM, Ivan Evstegneev wrote: >> > > Firtst of all thanks for reply. >> > > >> > >>>brackets [] means that the argument is optional. >> > > >> > > That's what I'm talking about (asking actually), where do you know it from? >> > >> > I know it because I've been a programmer for 39 years. >> >> that's awesome?????? > >Well I started in 1971 or thereabouts. 1959 for me ;-) From stephane at wirtel.be Fri Nov 7 07:25:57 2014 From: stephane at wirtel.be (=?utf-8?q?St=C3=A9phane?= Wirtel) Date: Fri, 07 Nov 2014 13:25:57 +0100 Subject: Python @ FOSDEM 2015 - Call =?utf-8?q?For=C2=A0Proposals?= Message-ID: * Please forward this CfP to anyone who may be interested in participating. * Hi all, This is the official call for sessions for the `Python Devroom` at `FOSDEM 2015` . FOSDEM is the Free and Open source Software Developers' European Meeting, a free and non-commercial two-day week-end that offers open source contributors a place to meet, share ideas and collaborate. It's the biggest event in Europe with +5000 hackers, +400 speakers. For this edition, Python will be represented by its Community. If you want to discuss with a lot of Python Users, it's the place to be ! Like every year, `FOSDEM 2015` will take place on 31st January and 1st February in Brussels (Belgium). We will have a room in the K building (80 seats) of the University Libre of Brussels, with a VGA video project and Wireless Internet. This devroom will be open all day Saturday, 31st January. Call for Proposals is open until 1st December 2014. You can watch the talks from the last edition 2014: https://www.youtube.com/playlist?list=PLUgTyq9ZstaI3t2XKhPjvnm-QBJTQySjD Important dates =============== * Submission deadlines: 2014-12-01 * Acceptance notifications: 2014-12-15 Pratical ======== * The duration for talks will be 30 minutes, including presentations and questions & answers. * Presentations can be recorded and streamed, sending your proposal implies giving permission to be recorded. * A mailing list for the Python devroom is available for discussions about devroom organisation. You can register at this address: https://lists.fosdem.org/listinfo/python-devroom How to submit ============= All submissions are made in the Pentabarf event planning tool at https://penta.fosdem.org/submission/FOSDEM15 When submitting your talk in Pentabarf, make sure to select the 'Python devroom' as the 'Track'. Of course, If you already have an account, please reuse it. Questions & Volunteers ====================== Any questions, and volunteers, please mail to info at python-fosdem.org. Thank you for submitting your sessions and see you soon in Brussels to talk Python and/or have some nice Belgian Beers. For this edition, there will be organized a dinner with the Python Community. If you want to keep informed for this edition, you can follow our twitter account @PythonFOSDEM . FOSDEM 2015: http://fosdem.org/2015 Python Devroom: http://python-fosdem.org Thank you, Best regards, The Team Python @ FOSDEM -- St?phane Wirtel - http://wirtel.be - @matrixise From davea at davea.name Fri Nov 7 07:42:44 2014 From: davea at davea.name (Dave Angel) Date: Fri, 7 Nov 2014 07:42:44 -0500 (EST) Subject: Understanding "help" command description syntax - explanation needed References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <88543346.5460.1415188500802.JavaMail.root@sequans.com> <000501cff8f1$ed99cc40$c8cd64c0$@gmail.com> <57af10d4-3891-4eec-8c46-5fa625ebe591@googlegroups.com> Message-ID: Bob Martin Wrote in message: > in 730867 20141107 093651 cl at isbd.net wrote: >>Darren Chen wrote: >>> ??? 2014???11???5????????????UTC+8??????8???17???11??????Larry.... at gmail.com????????? >>> > On Wed, Nov 5, 2014 at 7:13 AM, Ivan Evstegneev wrote: >>> > > Firtst of all thanks for reply. >>> > > >>> > >>>brackets [] means that the argument is optional. >>> > > >>> > > That's what I'm talking about (asking actually), where do you know it from? >>> > >>> > I know it because I've been a programmer for 39 years. >>> >>> that's awesome?????? >> >>Well I started in 1971 or thereabouts. > > 1959 for me ;-) > Approximately 1968 for me. I wrote programs in 1967, but didn't get to run them till 1968. -- DaveA From steve+comp.lang.python at pearwood.info Fri Nov 7 07:52:22 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 07 Nov 2014 23:52:22 +1100 Subject: Understanding "help" command description syntax - explanation needed References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <88543346.5460.1415188500802.JavaMail.root@sequans.com> <000501cff8f1$ed99cc40$c8cd64c0$@gmail.com> <57af10d4-3891-4eec-8c46-5fa625ebe591@googlegroups.com> Message-ID: <545cc087$0$12982$c3e8da3$5496439d@news.astraweb.com> Dave Angel wrote: > Approximately 1968 for me. I wrote programs in 1967, but didn't > get to run them till 1968. I once used a compiler that slow too. -- Steven From ethan at stoneleaf.us Fri Nov 7 07:58:44 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 07 Nov 2014 04:58:44 -0800 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: <87a943qyvn.fsf@handshake.de> References: <545919B6.7040007@stoneleaf.us> <87a943qyvn.fsf@handshake.de> Message-ID: <545CC204.2010301@stoneleaf.us> On 11/06/2014 10:59 PM, dieter wrote: > John Ladasky writes: >> On Tuesday, November 4, 2014 11:12:31 AM UTC-8, Ethan Furman wrote: >> >>> If you really absolutely positively have to have the signature be correct for each instance, you may to either look at a >>> function creating factory, a class creating factory, or a meta-class. >> >> +1. Overriding __call__() within the class definition, over and over again, with different function, looks awkward to me. > > A possibility to get the original approach implemented looks like: > > make "__call__" a descriptor on the class which looks up the real > method on the instance. This still wouldn't get the signatrue correct, though. -- ~Ethan~ From larry.martell at gmail.com Fri Nov 7 08:03:43 2014 From: larry.martell at gmail.com (Larry Martell) Date: Fri, 7 Nov 2014 08:03:43 -0500 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: <545cc087$0$12982$c3e8da3$5496439d@news.astraweb.com> References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <88543346.5460.1415188500802.JavaMail.root@sequans.com> <000501cff8f1$ed99cc40$c8cd64c0$@gmail.com> <57af10d4-3891-4eec-8c46-5fa625ebe591@googlegroups.com> <545cc087$0$12982$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Nov 7, 2014 at 7:52 AM, Steven D'Aprano wrote: > Dave Angel wrote: > >> Approximately 1968 for me. I wrote programs in 1967, but didn't >> get to run them till 1968. > > > I once used a compiler that slow too. Yeah, I think it was made by Intermetrics. Or maybe Borland. From wrw at mac.com Fri Nov 7 10:03:49 2014 From: wrw at mac.com (William Ray Wing) Date: Fri, 07 Nov 2014 10:03:49 -0500 Subject: Understanding "help" command description syntax - explanation needed In-Reply-To: References: <000001cff8e7$af51ef30$0df5cd90$@gmail.com> <88543346.5460.1415188500802.JavaMail.root@sequans.com> <000501cff8f1$ed99cc40$c8cd64c0$@gmail.com> <57af10d4-3891-4eec-8c46-5fa625ebe591@googlegroups.com> Message-ID: <6D364C90-47FF-4ADC-8EDA-032888C7BA88@mac.com> On Nov 7, 2014, at 7:42 AM, Dave Angel wrote: > > Bob Martin Wrote in message: >> in 730867 20141107 093651 cl at isbd.net wrote: >>> Darren Chen wrote: >>>> ??? 2014???11???5????????????UTC+8??????8???17???11??????Larry.... at gmail.com????????? >>>>> On Wed, Nov 5, 2014 at 7:13 AM, Ivan Evstegneev wrote: >>>>>> Firtst of all thanks for reply. >>>>>> >>>>>>>> brackets [] means that the argument is optional. >>>>>> >>>>>> That's what I'm talking about (asking actually), where do you know it from? >>>>> >>>>> I know it because I've been a programmer for 39 years. >>>> But, to get back to the OP?s original question. The earliest manuals that I remember looking at (from DEC, remember them) all had sections in the front that listed the typological conventions used throughout the manual. Those included the use of square brackets to indicate optional arguments. Eventually some of those conventions, including [ ] and the use of a fixed width font to indicate screen output, became so wide spread as to be simply part of the cultural context. A fair number of ?Introduction to . . .? programming books still have such a section. Bill >>>> that's awesome?????? >>> >>> Well I started in 1971 or thereabouts. >> >> 1959 for me ;-) >> > > Approximately 1968 for me. I wrote programs in 1967, but didn't > get to run them till 1968. > -- > DaveA > > -- > https://mail.python.org/mailman/listinfo/python-list From thomas.lehmann at teamaol.com Fri Nov 7 10:18:15 2014 From: thomas.lehmann at teamaol.com (thomas.lehmann at teamaol.com) Date: Fri, 7 Nov 2014 07:18:15 -0800 (PST) Subject: bdist_rpm with --requires and version Message-ID: <92de50e7-e430-42a3-b10b-9e0b851ceb71@googlegroups.com> Hi, using the RPM build I wonder how I can require a certain version of another RPM like: Working: python setup.py bdist_rpm --requires=another-package But how to? ... python setup.py bdist_rpm --requires=another-package>=2.1 Of course this will generate a "=2.1" file which is of course not wanted. How to do it right? From r.voigtlaender at gmail.com Fri Nov 7 10:39:27 2014 From: r.voigtlaender at gmail.com (=?ISO-8859-1?Q?Robert_Voigtl=E4nder?=) Date: Fri, 7 Nov 2014 07:39:27 -0800 (PST) Subject: generating 2D bit array variants with specific algorythm Message-ID: <0e6787f9-88d6-423a-8410-7578fa83d61c@googlegroups.com> Hi, I need to generate all variants of a 2D array with variable dimension sizes which fit a specific rule. (up to 200*1000) The rules are: - Values are only 0 or 1 - the sum of each line bust be 1 - only valid results must be generated (generating all and only returning the valid results takes to long; that's what I tried already) So for a 2x2 array these would be the valid results: 10 01 01 10 10 10 01 01 Must be possible with nested loops and a counter per line. But I don't get it. Can someone help? Thanks Robert From p.f.moore at gmail.com Fri Nov 7 10:46:36 2014 From: p.f.moore at gmail.com (Paul Moore) Date: Fri, 7 Nov 2014 15:46:36 +0000 Subject: Call for information - What assumptions can I make about Unix users' access to Windows? Message-ID: I'm in the process of developing an automated solution to allow users to quickly set up a Windows box so that it can be used to compile Python extensions and build wheels. While it can obviously be used by Windows developers who want to quickly set up a box, my main target is Unix developers who want to provide wheels for Windows users. To that end, I'd like to get an idea of what sort of access to Windows a typical Unix developer would have. I'm particularly interested in whether Windows XP/Vista is still in use, and whether you're likely to already have Python and/or any development tools installed. Ideally, a clean Windows 7 or later virtual machine is the best environment, but I don't know if it's reasonable to assume that. Another alternative is to have an Amazon EC2 AMI prebuilt, and users can just create an instance based on it. That seems pretty easy to do from my perspective but I don't know if the connectivity process (remote desktop) is a problem for Unix developers. Any feedback would be extremely useful. I'm at a point where I can pretty easily set up any of these options, but if they don't turn out to actually be usable by the target audience, it's a bit of a waste of time! :-) Thanks, Paul From donald at stufft.io Fri Nov 7 10:49:26 2014 From: donald at stufft.io (Donald Stufft) Date: Fri, 7 Nov 2014 10:49:26 -0500 Subject: [Distutils] Call for information - What assumptions can I make about Unix users' access to Windows? In-Reply-To: References: Message-ID: <9DE4D646-1948-4FF9-9F88-68755493B43B@stufft.io> > On Nov 7, 2014, at 10:46 AM, Paul Moore wrote: > > I'm in the process of developing an automated solution to allow users > to quickly set up a Windows box so that it can be used to compile > Python extensions and build wheels. While it can obviously be used by > Windows developers who want to quickly set up a box, my main target is > Unix developers who want to provide wheels for Windows users. > > To that end, I'd like to get an idea of what sort of access to Windows > a typical Unix developer would have. I'm particularly interested in > whether Windows XP/Vista is still in use, and whether you're likely to > already have Python and/or any development tools installed. Ideally, a > clean Windows 7 or later virtual machine is the best environment, but > I don't know if it's reasonable to assume that. > > Another alternative is to have an Amazon EC2 AMI prebuilt, and users > can just create an instance based on it. That seems pretty easy to do > from my perspective but I don't know if the connectivity process > (remote desktop) is a problem for Unix developers. > > Any feedback would be extremely useful. I'm at a point where I can > pretty easily set up any of these options, but if they don't turn out > to actually be usable by the target audience, it's a bit of a waste of > time! :-) > > Thanks, > Paul > _______________________________________________ > Distutils-SIG maillist - Distutils-SIG at python.org > https://mail.python.org/mailman/listinfo/distutils-sig As an *nix user I have a Windows 7 VM on my OS X machine that I can also dual boot into which I mostly use for playing games that won?t play on my OS X box natively. It does not have Python or any development tooling installed on it. I also have access to the cloud(tm) which is where I normally spin up a whatever-the-most-recent-looking-name Windows Server. --- Donald Stufft PGP: 7C6B 7C5D 5E2B 6356 A926 F04F 6E3C BCE9 3372 DCFA From joel.goldstick at gmail.com Fri Nov 7 10:51:35 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 7 Nov 2014 10:51:35 -0500 Subject: generating 2D bit array variants with specific algorythm In-Reply-To: <0e6787f9-88d6-423a-8410-7578fa83d61c@googlegroups.com> References: <0e6787f9-88d6-423a-8410-7578fa83d61c@googlegroups.com> Message-ID: On Fri, Nov 7, 2014 at 10:39 AM, Robert Voigtl?nder wrote: > Hi, > > I need to generate all variants of a 2D array with variable dimension sizes which fit a specific rule. (up to 200*1000) > > The rules are: > - Values are only 0 or 1 > - the sum of each line bust be 1 > - only valid results must be generated (generating all and only returning the valid results takes to long; that's what I tried already) > > So for a 2x2 array these would be the valid results: > > 10 > 01 > > 01 > 10 > > 10 > 10 > > 01 > 01 > > > Must be possible with nested loops and a counter per line. But I don't get it. > > Can someone help? is this valid: 1011 What I mean is do you throw away the carry or does each row have only one zero? > > Thanks > Robert > -- > https://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick http://joelgoldstick.com From r.voigtlaender at gmail.com Fri Nov 7 11:02:54 2014 From: r.voigtlaender at gmail.com (=?ISO-8859-1?Q?Robert_Voigtl=E4nder?=) Date: Fri, 7 Nov 2014 08:02:54 -0800 (PST) Subject: generating 2D bit array variants with specific algorythm In-Reply-To: References: <0e6787f9-88d6-423a-8410-7578fa83d61c@googlegroups.com> Message-ID: > 1011 > What I mean is do you throw away the carry or does each row have only one zero? Not sure what you mean. Each row must have one 1. The rest must be 0. No combinations not fitting this rule must be generated. From wichert at wiggy.net Fri Nov 7 11:17:18 2014 From: wichert at wiggy.net (Wichert Akkerman) Date: Fri, 7 Nov 2014 17:17:18 +0100 Subject: [Distutils] Call for information - What assumptions can I make about Unix users' access to Windows? In-Reply-To: References: Message-ID: <4678CD6F-D645-4C04-85E5-1D94E72A590D@wiggy.net> > On 07 Nov 2014, at 16:46, Paul Moore wrote: > > I'm in the process of developing an automated solution to allow users > to quickly set up a Windows box so that it can be used to compile > Python extensions and build wheels. While it can obviously be used by > Windows developers who want to quickly set up a box, my main target is > Unix developers who want to provide wheels for Windows users. > > To that end, I'd like to get an idea of what sort of access to Windows > a typical Unix developer would have. In my case: none. The only form of Windows I have are VMs I grab from modern.ie to test things with various IE versions. Those are all throw-away instances that are never used for anything other than IE testing. Wichert. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Nov 7 11:29:30 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Nov 2014 17:29:30 +0100 Subject: generating 2D bit array variants with specific algorythm References: <0e6787f9-88d6-423a-8410-7578fa83d61c@googlegroups.com> Message-ID: Robert Voigtl?nder wrote: > Hi, > > I need to generate all variants of a 2D array with variable dimension > sizes which fit a specific rule. (up to 200*1000) > > The rules are: > - Values are only 0 or 1 > - the sum of each line bust be 1 > - only valid results must be generated (generating all and only returning > the valid results takes to long; that's what I tried already) > > So for a 2x2 array these would be the valid results: > > 10 > 01 > > 01 > 10 > > 10 > 10 > > 01 > 01 > > > Must be possible with nested loops and a counter per line. But I don't get > it. > > Can someone help? Have a look at itertools.product(). If you need to code it in Python -- the documentation has an example implementation. from itertools import product def f(n): rows = [[0] * n for i in range(n)] for i, row in enumerate(rows): row[i] = 1 rows = [tuple(row) for row in rows] return list(product(rows, repeat=n)) if __name__ == "__main__": from pprint import pprint pprint(f(2)) print("---") pprint(f(3)) However, n**n is growing quite fast; you'll soon reach the limits of what is feasible in Python. Maybe numpy has something to offer to push these limits a bit. An optimisation would be to store the position of the 1, i. e. 01 10 00 11 for n=2. If you reorder these you get 0, 1, 2, 3. I think I'm seeing a pattern... From nomail at invalid.com Fri Nov 7 11:40:29 2014 From: nomail at invalid.com (ast) Date: Fri, 7 Nov 2014 17:40:29 +0100 Subject: generating 2D bit array variants with specific algorythm In-Reply-To: References: <0e6787f9-88d6-423a-8410-7578fa83d61c@googlegroups.com> Message-ID: <545cf60a$0$27511$426a34cc@news.free.fr> "Robert Voigtl?nder" a ?crit dans le message de news:e5c93b46-a32b-4eca-a00d-f7dd2b4bb8ee at googlegroups.com... >> 1011 >> What I mean is do you throw away the carry or does each row have only one zero? > > Not sure what you mean. Each row must have one 1. The rest must be 0. > No combinations not fitting this rule must be generated. OK exactly one 1 per line, others are 0 I understood sum modulo 2 = 1, so an odd number of 1 as joel ;) From nomail at invalid.com Fri Nov 7 11:57:10 2014 From: nomail at invalid.com (ast) Date: Fri, 7 Nov 2014 17:57:10 +0100 Subject: generating 2D bit array variants with specific algorythm In-Reply-To: <0e6787f9-88d6-423a-8410-7578fa83d61c@googlegroups.com> References: <0e6787f9-88d6-423a-8410-7578fa83d61c@googlegroups.com> Message-ID: <545cf9f0$0$2913$426a34cc@news.free.fr> "Robert Voigtl?nder" a ?crit dans le message de news:0e6787f9-88d6-423a-8410-7578fa83d61c at googlegroups.com... Let be L the number of lines and C the numbers of column You solve your problem just with counting on base C On base C, a number may be represented with N(L-1)N(L-2) ... N(0)N(0) where N(i) goes from 0 to C-1 N(i) is associated with line i of your array. Lines are numbered from 0 if N(i) == j, then bit in column j of line i is 1 and all others 0, columns are numbered from 0 For example, with an array of 2 lines and 3 colums 00 --> 100 < line 1 100 < line 0 01 -> 100 010 02 -> 100 001 10 -> 010 100 11 -> 010 010 12 -> 010 001 20 -> 001 100 21 -> 001 010 22 -> 001 001 From nomail at invalid.com Fri Nov 7 11:58:41 2014 From: nomail at invalid.com (ast) Date: Fri, 7 Nov 2014 17:58:41 +0100 Subject: generating 2D bit array variants with specific algorythm In-Reply-To: <545cf9f0$0$2913$426a34cc@news.free.fr> References: <0e6787f9-88d6-423a-8410-7578fa83d61c@googlegroups.com> <545cf9f0$0$2913$426a34cc@news.free.fr> Message-ID: <545cfa4e$0$5110$426a34cc@news.free.fr> "ast" a ?crit dans le message de news:545cf9f0$0$2913$426a34cc at news.free.fr... > On base C, a number may be represented with > > N(L-1)N(L-2) ... N(1)N(0) where N(i) goes from 0 to C-1 From Steve.Dower at microsoft.com Fri Nov 7 12:05:47 2014 From: Steve.Dower at microsoft.com (Steve Dower) Date: Fri, 7 Nov 2014 17:05:47 +0000 Subject: [Distutils] Call for information - What assumptions can I make about Unix users' access to Windows? In-Reply-To: <851tpf54y5.fsf@benfinney.id.au> References: <851tpf54y5.fsf@benfinney.id.au> Message-ID: <5d041f9c5799466da8037b3d33be7959@DM2PR0301MB0734.namprd03.prod.outlook.com> Ben Finney wrote: > Paul Moore writes: > >> To that end, I'd like to get an idea of what sort of access to Windows >> a typical Unix developer would have. [?] Ideally, a clean Windows 7 or >> later virtual machine is the best environment, but I don't know if >> it's reasonable to assume that. > > It's difficult to say what ?a typical Unix developer? is. But a significant use > case is going to be ?no legal access to any MS Windows instance?. > > The restrictions of the license terms make MS Windows an unacceptable risk on > any machine I'm responsible for. Just out of interest, which restrictions would those be? I may be able to raise them with one of our lawyers and get some clarification. > It has been many years since I've even had a colleague who has a MS Windows > instance, and I am not sure where I'd go for one if the need arose. > > If I was required to provide packages for MS Windows, the only viable solutions > would be those that don't involve me obtaining an MS Windows instance myself. Does this prevent you from creating a VM on a cloud provider on your own account? As far as Microsoft Azure is concerned, this is well within the license restrictions (at least for Windows Server right now), and all providers giving you access to Windows should be bundling in a license fee, which makes it about as legit as possible. Simply giving you "share time" on someone else's copy of Windows is much more of a grey area as far as licensing is concerned. If the licensing is a real issue, I'm in a position where I can have a positive impact on fixing it, so any info you can provide me (on- or off-list) about your concerns is valuable. Cheers, Steve From p.f.moore at gmail.com Fri Nov 7 12:13:22 2014 From: p.f.moore at gmail.com (Paul Moore) Date: Fri, 7 Nov 2014 17:13:22 +0000 Subject: [Distutils] Call for information - What assumptions can I make about Unix users' access to Windows? In-Reply-To: <851tpf54y5.fsf@benfinney.id.au> References: <851tpf54y5.fsf@benfinney.id.au> Message-ID: On 7 November 2014 16:52, Ben Finney wrote: > If I was required to provide packages for MS Windows, the only viable > solutions would be those that don't involve me obtaining an MS Windows > instance myself. For that usage, an Amazon EC2 AMI sounds ideal, as the license costs are covered by the AWS costs (which are zero, if you're on the free usage tier). Paul From p.f.moore at gmail.com Fri Nov 7 12:21:15 2014 From: p.f.moore at gmail.com (Paul Moore) Date: Fri, 7 Nov 2014 17:21:15 +0000 Subject: [Distutils] Call for information - What assumptions can I make about Unix users' access to Windows? In-Reply-To: <85wq773p7a.fsf@benfinney.id.au> References: <851tpf54y5.fsf@benfinney.id.au> <85wq773p7a.fsf@benfinney.id.au> Message-ID: On 7 November 2014 17:17, Ben Finney wrote: > Paul Moore writes: > >> On 7 November 2014 16:52, Ben Finney wrote: >> > If I was required to provide packages for MS Windows, the only viable >> > solutions would be those that don't involve me obtaining an MS Windows >> > instance myself. >> >> For that usage [?] the license costs [?] > > I didn't mention monetary costs at all. My understanding is that > changing the cost doesn't in any way affect the terms of the license one > is bound by. Sorry, I misunderstood you. As Steve said, it would be necessary to understand the restrictions you're working under to be able to comment. Paul From p.f.moore at gmail.com Fri Nov 7 13:08:12 2014 From: p.f.moore at gmail.com (Paul Moore) Date: Fri, 7 Nov 2014 18:08:12 +0000 Subject: [Distutils] Call for information - What assumptions can I make about Unix users' access to Windows? In-Reply-To: <85sihu52lg.fsf@benfinney.id.au> References: <851tpf54y5.fsf@benfinney.id.au> <5d041f9c5799466da8037b3d33be7959@DM2PR0301MB0734.namprd03.prod.outlook.com> <85sihu52lg.fsf@benfinney.id.au> Message-ID: On 7 November 2014 17:42, Ben Finney wrote: >> Does this prevent you from creating a VM on a cloud provider on your >> own account? > > If I need to accept restrictions such as the above, I don't see that the > location of the instance (nor the fees charged) has any affect on these > concerns. The risks discussed above are not mitigated. Thanks for the clarification. Given what you say, I don't see any way that I can offer a solution you'd be willing to accept - I suspect the only viable option for you would be support for cross-compilation using mingw/ggg, which I'm not able to offer. For now, I guess, that simply means I'll have to consider you (and anyone else for whom even running a Windows system is unacceptable) outside of my target audience. Paul From davea at davea.name Fri Nov 7 14:34:11 2014 From: davea at davea.name (Dave Angel) Date: Fri, 7 Nov 2014 14:34:11 -0500 (EST) Subject: generating 2D bit array variants with specific algorythm References: <0e6787f9-88d6-423a-8410-7578fa83d61c@googlegroups.com> Message-ID: Robert Voigtl?nder Wrote in message: > Hi, > > I need to generate all variants of a 2D array with variable dimension sizes which fit a specific rule. (up to 200*1000) > > The rules are: > - Values are only 0 or 1 > - the sum of each line bust be 1 > - only valid results must be generated (generating all and only returning the valid results takes to long; that's what I tried already) > > So for a 2x2 array these would be the valid results: > > 10 > 01 > > 01 > 10 > > 10 > 10 > > 01 > 01 > > > Must be possible with nested loops and a counter per line. But I don't get it. If the matrix is m by n, then there are 2**n possibilities for each row. But only n of them are legal by your rules. So your problem is just a matter of counting in base n, all the possible m digit numbers. -- DaveA From vek.m1234 at gmail.com Fri Nov 7 05:16:19 2014 From: vek.m1234 at gmail.com (Veek M) Date: Fri, 07 Nov 2014 16:46:19 +0630 Subject: How do i reduce this to a single function - the code is largely similar, just a direction of search toggle. Message-ID: def jump_to_blockD(self): end = len(self.b) row, col = self.w.cursor while row <= end: try: new_col = self.b[row].index('def') self.w.cursor = row, new_col break except ValueError: pass row += 1 def jump_to_blockU(self): end = 0 row, col = self.w.cursor while row >= end: try: new_col = self.b[row].rindex('def') self.w.cursor = row, new_col break except ValueError: pass row -= 1 From greg.ewing at canterbury.ac.nz Fri Nov 7 16:13:12 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 08 Nov 2014 10:13:12 +1300 Subject: generating 2D bit array variants with specific algorythm In-Reply-To: <0e6787f9-88d6-423a-8410-7578fa83d61c@googlegroups.com> References: <0e6787f9-88d6-423a-8410-7578fa83d61c@googlegroups.com> Message-ID: Robert Voigtl?nder wrote: > I need to generate all variants of a 2D array with variable dimension sizes > which fit a specific rule. (up to 200*1000) Um... you realise there are 200**1000 solutions for the 200x1000 case? Are you sure that's really what you want? -- Greg From joel.goldstick at gmail.com Fri Nov 7 16:18:37 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 7 Nov 2014 16:18:37 -0500 Subject: How do i reduce this to a single function - the code is largely similar, just a direction of search toggle. In-Reply-To: References: Message-ID: On Fri, Nov 7, 2014 at 5:16 AM, Veek M wrote: > def jump_to_blockD(self): > end = len(self.b) > row, col = self.w.cursor > while row <= end: > try: > new_col = self.b[row].index('def') > self.w.cursor = row, new_col > break > except ValueError: > pass > row += 1 > > def jump_to_blockU(self): > end = 0 > row, col = self.w.cursor > while row >= end: > try: > new_col = self.b[row].rindex('def') > self.w.cursor = row, new_col > break > except ValueError: > pass > row -= 1 > > > > -- > https://mail.python.org/mailman/listinfo/python-list add a direction parameter to the call, and test direction to change the while test, and row increment/decrement -- Joel Goldstick http://joelgoldstick.com From denismfmcmahon at gmail.com Fri Nov 7 17:22:47 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Fri, 7 Nov 2014 22:22:47 +0000 (UTC) Subject: How do i reduce this to a single function - the code is largely similar, just a direction of search toggle. References: Message-ID: On Fri, 07 Nov 2014 21:22:22 +0630, Veek M wrote: > Veek M wrote: > > >> new_col = self.b[row].index('def') self.w.cursor = row, >> new_col > >> new_col = self.b[row].rindex('def') >> self.w.cursor = row, new_col > > There's also the different methods index vs rindex. yes, those fall under point 2 of my earlier post. "something" and "something else" would be the complete means of calculating the value to assign to variable. -- Denis McMahon, denismfmcmahon at gmail.com From rosuav at gmail.com Fri Nov 7 17:31:26 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 8 Nov 2014 09:31:26 +1100 Subject: How do i reduce this to a single function - the code is largely similar, just a direction of search toggle. In-Reply-To: References: Message-ID: On Fri, Nov 7, 2014 at 9:16 PM, Veek M wrote: > def jump_to_blockD(self): > end = len(self.b) > row, col = self.w.cursor > while row <= end: > try: > new_col = self.b[row].index('def') > self.w.cursor = row, new_col > break > except ValueError: > pass > row += 1 > > def jump_to_blockU(self): > end = 0 > row, col = self.w.cursor > while row >= end: > try: > new_col = self.b[row].rindex('def') > self.w.cursor = row, new_col > break > except ValueError: > pass > row -= 1 Start by translating this into for loops, rather than while, and then it'll be much easier to put all the differences in the signature. Tell me if this translation is faithful: def jump_to_blockD(self): for row in range(self.w.cursor[0], len(self.b)+1, 1): try: new_col = self.b[row].index('def') self.w.cursor = row, new_col break except ValueError: pass def jump_to_blockU(self): for row in range(self.w.cursor[0], -1, -1): try: new_col = self.b[row].rindex('def') self.w.cursor = row, new_col break except ValueError: pass Try those two, see if they function the same as your original code. If they do, you should be able to figure out how to merge them, in their new form. ChrisA From steve+comp.lang.python at pearwood.info Fri Nov 7 19:28:52 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 08 Nov 2014 11:28:52 +1100 Subject: Call for information - What assumptions can I make about Unix users' access to Windows? References: Message-ID: <545d63c5$0$12981$c3e8da3$5496439d@news.astraweb.com> Paul Moore wrote: > To that end, I'd like to get an idea of what sort of access to Windows > a typical Unix developer would have. I'm particularly interested in > whether Windows XP/Vista is still in use, and whether you're likely to > already have Python and/or any development tools installed. Ideally, a > clean Windows 7 or later virtual machine is the best environment, but > I don't know if it's reasonable to assume that. I don't think that there is such a beast as a "typical Unix developer", since Unix covers such a wide range. In very rough order of decreasing market share, there is Linux (not actually a form of Unix, but in practice people gloss over that technicality), Apple OS X, FreeBSD, OpenBSD, various commercial Unixes which still exist, and so on. They tend to attract very different sorts of people, although if they had anything in common it would probably be a dislike or rejection of Windows, so you can probably safely assume that the average Unix/Linux/Mac user has little access to Windows. Speaking for myself, I have effectively no access to Windows. Once a year I manage to borrow a laptop with Windows 7 so I can do my taxes, but it has no development tools on it. I also have access to a Windows 2000 VM for work purposes, but I don't have admin rights to it and it too has no development tools on it. > Another alternative is to have an Amazon EC2 AMI prebuilt, and users > can just create an instance based on it. That seems pretty easy to do > from my perspective but I don't know if the connectivity process > (remote desktop) is a problem for Unix developers. If it uses a standard protocol like RDP or VNC, there shouldn't be a problem, most Unixes have clients for these. I use rdesktop to talk to the Win2000 VM at work all the time, and I can even do so over an ssh tunnel if I need to access it from home. https://en.wikipedia.org/wiki/Rdesktop If it uses some secret or unusual proprietary protocol, forget it. If remote access requires a specific Flash or Java app in the browser, it may or may not work, but probably won't. Flash support on Linux is better than it was but still mediocre. Since Flash these days is mostly used for two things (crappy games and obnoxious adverts) most Linux folks I know simply don't bother with it unless they use Chrome, in which case they get it whether they want it or not. Java is probably a bit better supported, but it can be annoying to set up. It took me about a day to get my bank's Java app working in Firefox, and it wouldn't work at all in other browsers or with the standard version of Java provided by my Linux distro. I had to replace my system Java with Oracle's Java, symlink it to an alternate location, and have my browser lie about what it is in the user-agent. -- Steven From sohcahtoa82 at gmail.com Fri Nov 7 20:10:43 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Fri, 7 Nov 2014 17:10:43 -0800 (PST) Subject: generating 2D bit array variants with specific algorythm In-Reply-To: References: <0e6787f9-88d6-423a-8410-7578fa83d61c@googlegroups.com> Message-ID: <2c5d5a1c-874b-4741-82e5-f1b76072adc8@googlegroups.com> On Friday, November 7, 2014 1:13:27 PM UTC-8, Gregory Ewing wrote: > Robert Voigtl?nder wrote: > > > I need to generate all variants of a 2D array with variable dimension sizes > > which fit a specific rule. (up to 200*1000) > > Um... you realise there are 200**1000 solutions for the > 200x1000 case? Are you sure that's really what you want? > > -- > Greg It sounds like it is indeed what he wants, however, this is likely a homework assignment and the idea is that your program COULD produce the answer for that if he wanted, not that he will actually be using the result. I'd handle it with recursion, myself. It sounds like a cool idea for a game of Code Golf on Stack Exchange. From steve+comp.lang.python at pearwood.info Fri Nov 7 20:50:53 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 08 Nov 2014 12:50:53 +1100 Subject: Different behaviour in list comps and generator expressions Message-ID: <545d76fe$0$12980$c3e8da3$5496439d@news.astraweb.com> The following list comprehension and generator expression are almost, but not quite, the same: [expr for x in iterable] list(expr for x in iterable) The difference is in the handling of StopIteration raised inside the expr. Generator expressions consume them and halt, while comprehensions allow them to leak out. A simple example: iterable = [iter([])] list(next(x) for x in iterable) => returns [] But: [next(x) for x in iterable] => raises StopIteration Has anyone come across this difference in the wild? Was it a problem? Do you rely on that difference, or is it a nuisance? Has it caused difficulty in debugging code? If you had to keep one behaviour, which would you keep? -- Steven From roy at panix.com Fri Nov 7 23:39:35 2014 From: roy at panix.com (Roy Smith) Date: Fri, 07 Nov 2014 23:39:35 -0500 Subject: Different behaviour in list comps and generator expressions References: <545d76fe$0$12980$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <545d76fe$0$12980$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > The following list comprehension and generator expression are almost, but > not quite, the same: > > [expr for x in iterable] > > list(expr for x in iterable) > > > The difference is in the handling of StopIteration raised inside the expr. > Generator expressions consume them and halt, while comprehensions allow > them to leak out. A simple example: > > iterable = [iter([])] > list(next(x) for x in iterable) > => returns [] > > But: > > [next(x) for x in iterable] > => raises StopIteration > > > Has anyone come across this difference in the wild? Was it a problem? Do you > rely on that difference, or is it a nuisance? Has it caused difficulty in > debugging code? > > If you had to keep one behaviour, which would you keep? Wow, that's really esoteric. I can't imagine this happening in real-life code (but I'm sure somebody will come up with an example :-)) My inclination is that a list comprehension should stop if StopIteration is raised by the comprehension body. I can't come up with a good argument to support that, other than it seems like the right thing to do. From vek.m1234 at gmail.com Fri Nov 7 09:52:22 2014 From: vek.m1234 at gmail.com (Veek M) Date: Fri, 07 Nov 2014 21:22:22 +0630 Subject: How do i reduce this to a single function - the code is largely similar, just a direction of search toggle. References: Message-ID: Veek M wrote: > new_col = self.b[row].index('def') > self.w.cursor = row, new_col > new_col = self.b[row].rindex('def') > self.w.cursor = row, new_col There's also the different methods index vs rindex. Does this sort of thing justify two functions and associated infrastructure (it's for vim so 2 x 3 mode lines in my .vimrc) From denismfmcmahon at gmail.com Fri Nov 7 10:18:35 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Fri, 7 Nov 2014 15:18:35 +0000 (UTC) Subject: How do i reduce this to a single function - the code is largely similar, just a direction of search toggle. References: Message-ID: On Fri, 07 Nov 2014 16:46:19 +0630, Veek M wrote: (1) Pass a true or false parameter to the function as the direction of search toggle. (2) replace the relevant assignments with something like: variable = something if condition else something else (3) Figuring out the while loop control is a bit trickier, the best I came up with was: while direction and condition_a or (not direction) and condition_b But I'm sure someone has something better -- Denis McMahon, denismfmcmahon at gmail.com From rosuav at gmail.com Sat Nov 8 01:46:56 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 8 Nov 2014 17:46:56 +1100 Subject: bdist_rpm with --requires and version In-Reply-To: <92de50e7-e430-42a3-b10b-9e0b851ceb71@googlegroups.com> References: <92de50e7-e430-42a3-b10b-9e0b851ceb71@googlegroups.com> Message-ID: On Sat, Nov 8, 2014 at 2:18 AM, wrote: > But how to? ... > python setup.py bdist_rpm --requires=another-package>=2.1 > > Of course this will generate a "=2.1" file which is > of course not wanted. What shell are you on? On POSIX shells, just quote or escape the relevant part. On Windows... I'm not sure. Depends whether you have cmd.exe, powershell, or something else, and I don't know any of them well enough to advise. But try putting the whole argument in quotes. ChrisA From dieter at handshake.de Sat Nov 8 01:50:41 2014 From: dieter at handshake.de (dieter) Date: Sat, 08 Nov 2014 07:50:41 +0100 Subject: [Python-Dev] Dinamically set __call__ method References: <545919B6.7040007@stoneleaf.us> <87a943qyvn.fsf@handshake.de> <545CC204.2010301@stoneleaf.us> Message-ID: <8761eq424e.fsf@handshake.de> Ethan Furman writes: > On 11/06/2014 10:59 PM, dieter wrote: >> John Ladasky writes: >>> On Tuesday, November 4, 2014 11:12:31 AM UTC-8, Ethan Furman wrote: >>> >>>> If you really absolutely positively have to have the signature be correct for each instance, you may to either look at a >>>> function creating factory, a class creating factory, or a meta-class. >>> >>> +1. Overriding __call__() within the class definition, over and over again, with different function, looks awkward to me. >> >> A possibility to get the original approach implemented looks like: >> >> make "__call__" a descriptor on the class which looks up the real >> method on the instance. > > This still wouldn't get the signatrue correct, though. Why not? Once the descriptor is resolved, you get the final instance method - with the correct signature. From notMyMail at mail.not Sat Nov 8 07:25:05 2014 From: notMyMail at mail.not (gm) Date: Sat, 08 Nov 2014 13:25:05 +0100 Subject: Raspberry model b --> program Message-ID: Hi ! I have one small program that should be completed till tomorrow so if someone can help am ready to pay this ( btw. budget for this is $40 ). Project: - usb scanner is connected to the PI. - when the user gets his e.g. coffe bill with barcode, he put this bill in from of scanner and scanner reads value. If the value is the same as the value in database - GPIO is triggered and signal is send to relay board - relay board opens the parking ramp. The cash register PC and RPI are connected over lan cable and they are on the same network. When the compare is over we are deleting the file that is on the PC side but when the new bill will be created, the new csv file will be created too. So nothing special. One csv file with barcode is on the PC side and db is on the RPI side. What we have done so far: - part for reading the data from scanner - mysql db with defined tables - connection to DB - successful test for GPIO What i need: - to hook up all this together and to test it. RPI is connected to my PC over SSH so there is no problem to make some "remote programming" and testing. If there is someone who can help, i am willing to pay for this. G. From edreamleo at gmail.com Sat Nov 8 07:26:05 2014 From: edreamleo at gmail.com (edreamleo at gmail.com) Date: Sat, 8 Nov 2014 04:26:05 -0800 (PST) Subject: Leo 5.0 alpha 2 released Message-ID: <58c6bab9-4c58-4618-b67e-c35f305859e6@googlegroups.com> Leo 5.0a2 is now available at: http://sourceforge.net/projects/leo/files/Leo/ Leo is a PIM, an IDE and an outliner. Video tutorials: http://leoeditor.com/screencasts.html Text tutorials: http://leoeditor.com/tutorial.html The highlights of Leo 5.0 -------------------------- * Better compatibility with vim, Emacs, pylint and PyQt: - Optional native emulation of vim commands. - Full support for Emacs org-mode outlines. - Better support for pylint. - Support for both PyQt4 and PyQt5. * Better handling of nodes containing large text: - Idle time syntax coloring eliminates delay. - Optional delayed loading of large text. * Power features: - Leo available via github repository. - File name completion. - Cloned nodes expand and contract independently. - @data nodes can be composed from descendant nodes. - No need to change Leo's main style sheet: it can be customized with @color and @font settings. - @persistence nodes save data in @auto trees. - A pluggable architecture for @auto nodes. - The style-reload command changes Leo's appearance instantly. * Important new plugins for tagging, display and node evaluation. * For beginners: - Leo's default workbook files contains Leo's quickstart guide. * Hundreds of new/improved features and bug fixes. Links: ------ Leo: http://leoeditor.com Docs: http://leoeditor.com/leo_toc.html Tutorials: http://leoeditor.com/tutorial.html Videos: http://leoeditor.com/screencasts.html Forum: http://groups.google.com/group/leo-editor Download: http://sourceforge.net/projects/leo/files/ Github: https://github.com/leo-editor/leo-editor Quotes: http://leoeditor.com/testimonials.html From ned at nedbatchelder.com Sat Nov 8 07:56:46 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sat, 08 Nov 2014 07:56:46 -0500 Subject: How do i reduce this to a single function - the code is largely similar, just a direction of search toggle. In-Reply-To: References: Message-ID: On 11/7/14 9:52 AM, Veek M wrote: > Veek M wrote: > > >> new_col = self.b[row].index('def') >> self.w.cursor = row, new_col > >> new_col = self.b[row].rindex('def') >> self.w.cursor = row, new_col > > There's also the different methods index vs rindex. Does this sort of thing > justify two functions and associated infrastructure (it's for vim so 2 x 3 > mode lines in my .vimrc) > Stepping back a bit from the lines of code, why do you need to use .index in one case and .rindex in the other? You are trying to find the "def" line in the editor buffer, either above the current point, or below it. But the "def" will always be the first non-whitespace text on the line. In fact, when searching upward, you could find this line: def get_default(self): and you want to end up on the "def" token, not the "def" in "get_default". .rindex isn't what you want in any case. Use .index in both cases. -- Ned Batchelder, http://nedbatchelder.com From 4kir4.1i at gmail.com Sat Nov 8 11:35:34 2014 From: 4kir4.1i at gmail.com (Akira Li) Date: Sat, 08 Nov 2014 19:35:34 +0300 Subject: Moving a window on the screen References: <545b321a$0$2396$426a34cc@news.free.fr> <545b3cd8$0$2306$426a34cc@news.free.fr> Message-ID: <87oash8xbd.fsf@gmail.com> "ast" writes: > Ok, thx, it works now with: > > import tkinter > fen = tkinter.Tk() > > x=0 > > def moveW(): > global x > fen.geometry("200x200+%d+10" % x) > x = x + 10 > if (x < 1200): > fen.after(50, moveW) > > moveW() In general, to avoid the start time "drift" [1], you could lock the execution with a timer e.g., to move the window from left to right *delta_x* pixels at a time every *period* ms [2]: #!/usr/bin/env python3 from time import monotonic from tkinter import Tk def timer(): return int(monotonic() * 1000) # milliseconds def call_repeatedly(period, function, *args): root.after(period - timer() % period, call_repeatedly, period, function, *args) # schedule the next call function(*args) def move(delta_x, max_x, width=200, x=[0]): root.geometry("%dx50+%d+100" % (width, x[0])) x[0] += delta_x # poor man's object if x[0] > (max_x - width): root.destroy() # exit root = Tk() period = 20 # call every *period* milliseconds delta_x = 2 # how many pixels to move at a time root.after(period - period % timer(), call_repeatedly, period, move, delta_x, root.winfo_screenwidth()) root.mainloop() [1]: http://stackoverflow.com/questions/8600161/executing-periodic-actions-in-python#comment26637231_8600301 [2]: http://stackoverflow.com/questions/24174924/how-to-run-a-function-periodically-in-python Akira From tjreedy at udel.edu Sat Nov 8 13:40:53 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 08 Nov 2014 13:40:53 -0500 Subject: Moving a window on the screen In-Reply-To: <87oash8xbd.fsf@gmail.com> References: <545b321a$0$2396$426a34cc@news.free.fr> <545b3cd8$0$2306$426a34cc@news.free.fr> <87oash8xbd.fsf@gmail.com> Message-ID: On 11/8/2014 11:35 AM, Akira Li wrote: > "ast" writes: > >> Ok, thx, it works now with: >> >> import tkinter >> fen = tkinter.Tk() >> >> x=0 >> >> def moveW(): >> global x >> fen.geometry("200x200+%d+10" % x) >> x = x + 10 >> if (x < 1200): >> fen.after(50, moveW) >> >> moveW() > > In general, to avoid the start time "drift" [1], which is hardly noticeable > you could lock the > execution with a timer e.g., to move the window from left to right > *delta_x* pixels at a time every *period* ms [2]: On my Win7 machine, your complicated code is much worse as it causes the window to jump about every half second > #!/usr/bin/env python3 > from time import monotonic > from tkinter import Tk > > def timer(): > return int(monotonic() * 1000) # milliseconds > > def call_repeatedly(period, function, *args): > root.after(period - timer() % period, call_repeatedly, period, The '- timer() % period' 'correction' is wrong when not 0 as it causes jumps. > function, *args) # schedule the next call > function(*args) > > def move(delta_x, max_x, width=200, x=[0]): > root.geometry("%dx50+%d+100" % (width, x[0])) > x[0] += delta_x # poor man's object > if x[0] > (max_x - width): > root.destroy() # exit > > root = Tk() > period = 20 # call every *period* milliseconds > delta_x = 2 # how many pixels to move at a time > root.after(period - period % timer(), call_repeatedly, period, 'period % timer()' is nonsensical as timer() is arbitrary. It will typically be 0 anyway. 'after(0, ...)' works fine. > move, delta_x, root.winfo_screenwidth()) > root.mainloop() > > > [1]: http://stackoverflow.com/questions/8600161/executing-periodic-actions-in-python#comment26637231_8600301 > [2]: http://stackoverflow.com/questions/24174924/how-to-run-a-function-periodically-in-python > > > Akira > -- Terry Jan Reedy From funthyme at gmail.com Sat Nov 8 14:41:30 2014 From: funthyme at gmail.com (John Pinner) Date: Sat, 8 Nov 2014 11:41:30 -0800 (PST) Subject: FYI: Micro Python running on kickstarter pyBoard project, now shipping In-Reply-To: References: <25b4884f-a3f9-436d-8d7d-f49f83c3e544@googlegroups.com> Message-ID: On Thursday, 23 October 2014 22:12:10 UTC+1, sohca... at gmail.com wrote: > On Thursday, October 23, 2014 10:07:26 AM UTC-7, jkn wrote: > > Hi all > > I haven't heard in mentioned here, but since I saw one of the boards today thought I'd pass on the news: > > > > The Kickstarter 'MicroPython' project, which has a tiny 'pyboard' (only a couple of sq.inches in size) with a processor running 'a complete re-write of the Python (version 3.4) programming language so that it fits and runs on a microcontroller' is now shipping. > > > > https://micropython.org/ > > > > Looks nice; I have no connection but will be getting one myself to play with... > > > > Cheers > > J^n > > > Is there any particular reason to get one of these when I can get a Raspberry Pi which is faster, has more memory, and a bundle of other features? > > I mean, the idea seems cool and all, but I'm trying to understand why I would want to spend the ~$45 on something like that when a ~$35 Raspberry Pi will do everything and more, and do it faster. They are quite different devices: * The Raspberry Pi is a low-power general purpose computer designed specifically for education purposes. It just so happens that it's ideal for geek experimentation as well... * MicroPython is an optimised version of Python 3 running on a micro-controller board, designed specifically for controlling 'things' (eg robots). Doing what it is designed for, it will run far faster and use far less power than a Pi, but cannot do any of the general computing things a Pi can do, for example it has no means of editing programs for MicroPython, you have to do this on, say, your PC and download them to the MicroPython board. It won't do *any* of the other things you can do with a Pi - watch videos, browse the net, etc etc, but what it can do it will do faster and better. If you want a low-power, cheap, computer to play with and learn from, get a Pi. If you want a nifty micro-controller you can program in Python, buy a MicroPython board. John -- From ethan at stoneleaf.us Sat Nov 8 14:49:17 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Sat, 08 Nov 2014 11:49:17 -0800 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: <8761eq424e.fsf@handshake.de> References: <545919B6.7040007@stoneleaf.us> <87a943qyvn.fsf@handshake.de> <545CC204.2010301@stoneleaf.us> <8761eq424e.fsf@handshake.de> Message-ID: <545E73BD.8060906@stoneleaf.us> On 11/07/2014 10:50 PM, dieter wrote: > Ethan Furman writes: > >> On 11/06/2014 10:59 PM, dieter wrote: >>> John Ladasky writes: >>>> On Tuesday, November 4, 2014 11:12:31 AM UTC-8, Ethan Furman wrote: >>>> >>>>> If you really absolutely positively have to have the signature be correct for each instance, you may to either look at a >>>>> function creating factory, a class creating factory, or a meta-class. >>>> >>>> +1. Overriding __call__() within the class definition, over and over again, with different function, looks awkward to me. >>> >>> A possibility to get the original approach implemented looks like: >>> >>> make "__call__" a descriptor on the class which looks up the real >>> method on the instance. >> >> This still wouldn't get the signatrue correct, though. > > Why not? Once the descriptor is resolved, you get the final > instance method - with the correct signature. Hmmm... well, it wouldn't be correct on a class lookup, but, yeah, it would be correct for an instance lookup -- and maybe that's good enough for the OP. -- ~Ethan~ From 4kir4.1i at gmail.com Sat Nov 8 15:31:20 2014 From: 4kir4.1i at gmail.com (Akira Li) Date: Sat, 08 Nov 2014 23:31:20 +0300 Subject: Moving a window on the screen References: <545b321a$0$2396$426a34cc@news.free.fr> <545b3cd8$0$2306$426a34cc@news.free.fr> <87oash8xbd.fsf@gmail.com> Message-ID: <87a9418mef.fsf@gmail.com> Terry Reedy writes: > On 11/8/2014 11:35 AM, Akira Li wrote: >> "ast" writes: >> >>> Ok, thx, it works now with: >>> >>> import tkinter >>> fen = tkinter.Tk() >>> >>> x=0 >>> >>> def moveW(): >>> global x >>> fen.geometry("200x200+%d+10" % x) >>> x = x + 10 >>> if (x < 1200): >>> fen.after(50, moveW) >>> >>> moveW() >> >> In general, to avoid the start time "drift" [1], > > which is hardly noticeable Do you mean hardly noticeable for these particular *period*, delta_x and (small) fixed number of repeatitions? That is why I said, "in general". The link [1] that I've provided contains an example where it *is* noticable. >> you could lock the >> execution with a timer e.g., to move the window from left to right >> *delta_x* pixels at a time every *period* ms [2]: > > On my Win7 machine, your complicated code is much worse as it causes > the window to jump about every half second Could you add print(timer()) inside move(), to see the values? What happens if you increase the period to 100 ms? >> #!/usr/bin/env python3 >> from time import monotonic >> from tkinter import Tk >> >> def timer(): >> return int(monotonic() * 1000) # milliseconds >> >> def call_repeatedly(period, function, *args): >> root.after(period - timer() % period, call_repeatedly, period, > > The '- timer() % period' 'correction' is wrong when not 0 as it causes > jumps. The formula is correct. It is obvious if you make the period one second (1000ms) and print the timer() values (in milliseconds): 52002 53000 54000 55000 56001 57000 58000 59001 60001 61000 62000 ... As you can see the start time is locked with the timer: the function is called at whole seconds. Individual calls may happens slightly sooner or later but the timing doesn't drift, the difference between the expected start time and the actual start time is 1ms: >>> M[0], M[-1], M[0] + 1000*(len(M)-1) (52002, 224001, 224002) Here's the same thing if I remove the locking `-timer() % period` and use just `root.after(period, call..)`: 34235 35236 36236 37236 38236 39237 40237 41237 42237 43238 44238 45238 46238 47239 48239 ... The start time drifts: >>> L[0], L[-1], L[0] + 1000*(len(L)-1) (34235, 206279, 206235) the difference between the expected start time and the actual start time is 44ms (4400% worse than the previous method). I agree, for the purpose of moving a window on the screen, the difference doesn't matter though if it is a GUI clock then you should not ignore it otherwise it will be wrong by a minute in a couple of days. >> function, *args) # schedule the next call >> function(*args) >> >> def move(delta_x, max_x, width=200, x=[0]): >> root.geometry("%dx50+%d+100" % (width, x[0])) >> x[0] += delta_x # poor man's object >> if x[0] > (max_x - width): >> root.destroy() # exit >> >> root = Tk() >> period = 20 # call every *period* milliseconds >> delta_x = 2 # how many pixels to move at a time >> root.after(period - period % timer(), call_repeatedly, period, > > 'period % timer()' is nonsensical as timer() is arbitrary. It will > typically be 0 anyway. 'after(0, ...)' works fine. > It is a bug (the terms are swapped by mistake). Thank you for noticing. It should be `timer() % period` instead. The same expression as used in the call_repeatedly() and in the link [2] that I've provided. `period - timer() % period` is used here to make the first start time at the exact boundary so there is the same interval between function(*args) calls. [1]: http://stackoverflow.com/questions/8600161/executing-periodic-actions-in-python#comment26637231_8600301 [2]: http://stackoverflow.com/questions/24174924/how-to-run-a-function-periodically-in-python Akira From flebber.crue at gmail.com Sat Nov 8 16:12:12 2014 From: flebber.crue at gmail.com (flebber) Date: Sat, 8 Nov 2014 13:12:12 -0800 (PST) Subject: Engaging, powerful - video inspriration/learning - Your best selections Message-ID: <1e4fc1b2-61e9-4cba-9d2d-0ff69f73f3ee@googlegroups.com> Morning Have you seen any python videos that were part of a series or that were from a conference that you found engaging and made a point click or solidify a concept or drive you to action to create something you wanted. That took an advanced topic or concept and made it clear as day to you. I have watched some Scipy conf videos which I really appreciated though some of the subject matter was over my technical level. Jessica McKellar did a great talk on the future of python. http://pyvideo.org/video/2375/the-future-of-python-a-choose-your-own-adventur Looking forward to see what videos engaged and drove your passion and increased your skills. Live engaged sayth From flebber.crue at gmail.com Sat Nov 8 16:14:44 2014 From: flebber.crue at gmail.com (flebber) Date: Sat, 8 Nov 2014 13:14:44 -0800 (PST) Subject: Leo 5.0 alpha 2 released In-Reply-To: <58c6bab9-4c58-4618-b67e-c35f305859e6@googlegroups.com> References: <58c6bab9-4c58-4618-b67e-c35f305859e6@googlegroups.com> Message-ID: <9e88475f-95ae-4d49-9a16-f96f89d9916a@googlegroups.com> On Saturday, 8 November 2014 23:26:20 UTC+11, edre... at gmail.com wrote: > Leo 5.0a2 is now available at: > http://sourceforge.net/projects/leo/files/Leo/ > > Leo is a PIM, an IDE and an outliner. > Video tutorials: http://leoeditor.com/screencasts.html > Text tutorials: http://leoeditor.com/tutorial.html > > The highlights of Leo 5.0 > -------------------------- > > * Better compatibility with vim, Emacs, pylint and PyQt: > - Optional native emulation of vim commands. > - Full support for Emacs org-mode outlines. > - Better support for pylint. > - Support for both PyQt4 and PyQt5. > * Better handling of nodes containing large text: > - Idle time syntax coloring eliminates delay. > - Optional delayed loading of large text. > * Power features: > - Leo available via github repository. > - File name completion. > - Cloned nodes expand and contract independently. > - @data nodes can be composed from descendant nodes. > - No need to change Leo's main style sheet: > it can be customized with @color and @font settings. > - @persistence nodes save data in @auto trees. > - A pluggable architecture for @auto nodes. > - The style-reload command changes Leo's appearance instantly. > * Important new plugins for tagging, display and node evaluation. > * For beginners: > - Leo's default workbook files contains Leo's quickstart guide. > * Hundreds of new/improved features and bug fixes. > > Links: > ------ > Leo: http://leoeditor.com > Docs: http://leoeditor.com/leo_toc.html > Tutorials: http://leoeditor.com/tutorial.html > Videos: http://leoeditor.com/screencasts.html > Forum: http://groups.google.com/group/leo-editor > Download: http://sourceforge.net/projects/leo/files/ > Github: https://github.com/leo-editor/leo-editor > Quotes: http://leoeditor.com/testimonials.html I tried to learn that is understand how Leo benefited me. There must be a click and aha moment with this editor, I never made it there. Having said that i got proficient with vim but not quite with that either. I use brackets currently. Have a great day Sayth From wolfgang.maier at biologie.uni-freiburg.de Sat Nov 8 16:31:23 2014 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Sat, 08 Nov 2014 22:31:23 +0100 Subject: Different behaviour in list comps and generator expressions In-Reply-To: <545d76fe$0$12980$c3e8da3$5496439d@news.astraweb.com> References: <545d76fe$0$12980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 08.11.2014 02:50, Steven D'Aprano wrote: > The following list comprehension and generator expression are almost, but > not quite, the same: > > [expr for x in iterable] > > list(expr for x in iterable) > > > The difference is in the handling of StopIteration raised inside the expr. > Generator expressions consume them and halt, while comprehensions allow > them to leak out. This is not the right description of what's happening. It is not the generator expression that consumes it, but the list constructor and, of course, list can't tell at which level in the inside code StopIteration got raised. So, yes this had me confused some times, too, but it is really not surprising. > A simple example: > > iterable = [iter([])] > list(next(x) for x in iterable) > => returns [] > > But: > > [next(x) for x in iterable] > => raises StopIteration > Yes, but the equivalent to list(next(x) for x in iterable) is: l = [] for item in (next(x) for x in iterable): l.append(item) => returns [] because the for consumes the StopIteration this, on the other hand raises StopIteration l = [] for item in [next(x) for x in iterable]: l.append(item) because the error gets raised already when for causes iter() to be called on the list comprehension. > > Has anyone come across this difference in the wild? Was it a problem? Do you > rely on that difference, or is it a nuisance? Has it caused difficulty in > debugging code? > > If you had to keep one behaviour, which would you keep? > The point is: there is no difference in the behavior of comprehensions and generator expressions, it is just how you access them: for anything that follows the iterator protocol, a comprehension (since it is evaluated immediately) raises during the iter() phase, while a generator expression (which gets evaluated lazily) raises during the next() phase where it gets swallowed. So in your example you would have to use the silly list([next(x) for x in iterable]) if you want the error to get raised. I agree this is all rather non-intuitive, but how would you change it ? From greg.ewing at canterbury.ac.nz Sat Nov 8 17:31:13 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 09 Nov 2014 11:31:13 +1300 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> <87a943qyvn.fsf@handshake.de> <545CC204.2010301@stoneleaf.us> <8761eq424e.fsf@handshake.de> Message-ID: Ethan Furman wrote: >> >>> On 11/06/2014 10:59 PM, dieter wrote: >>> >>>> A possibility to get the original approach implemented looks like: >>>> >>>> make "__call__" a descriptor on the class which looks up the real >>>> method on the instance. >>> >>> This still wouldn't get the signatrue correct, though. >> >> Why not? Once the descriptor is resolved, you get the final >> instance method - with the correct signature. > > Hmmm... well, it wouldn't be correct on a class lookup, but, yeah, it > would be correct for an instance lookup -- and maybe that's good enough > for the OP. Seems to depend on how you get hold of the object you're inspecting the signature of. I did an experiment: class C(object): @property def __call__(self): return self.call def f(x, y): print("Called f with %s, %s" % (x, y)) c = C() c.call = f c(17, 42) prints: Called f with 17, 42 This works too: import inspect print(inspect.getargspec(c.__call__)) prints: ArgSpec(args=['x', 'y'], varargs=None, keywords=None, defaults=None) But print(inspect.getargspec(c)) doesn't work: TypeError: <__main__.C object at 0x479250> is not a Python function (BTW, I'm actually surprised that this technique makes c callable. There must be more going on that just "look up __call__ in the class object", because evaluating C.__call__ just returns the descriptor and doesn't invoking the descriptor mechanism.) -- Greg From wolfgang.maier at biologie.uni-freiburg.de Sat Nov 8 17:42:29 2014 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Sat, 08 Nov 2014 23:42:29 +0100 Subject: Different behaviour in list comps and generator expressions In-Reply-To: References: <545d76fe$0$12980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 08.11.2014 22:31, Wolfgang Maier wrote: > On 08.11.2014 02:50, Steven D'Aprano wrote: >> The following list comprehension and generator expression are almost, but >> not quite, the same: >> >> [expr for x in iterable] >> >> list(expr for x in iterable) >> >> >> The difference is in the handling of StopIteration raised inside the >> expr. >> Generator expressions consume them and halt, while comprehensions allow >> them to leak out. > > This is not the right description of what's happening. It is not the > generator expression that consumes it, but the list constructor and, of > course, list can't tell at which level in the inside code StopIteration > got raised. > So, yes this had me confused some times, too, but it is really not > surprising. > >> A simple example: >> >> iterable = [iter([])] >> list(next(x) for x in iterable) >> => returns [] >> >> But: >> >> [next(x) for x in iterable] >> => raises StopIteration >> > > Yes, but the equivalent to list(next(x) for x in iterable) is: > > l = [] > for item in (next(x) for x in iterable): > l.append(item) > > => returns [] because the for consumes the StopIteration > > this, on the other hand raises StopIteration > > l = [] > for item in [next(x) for x in iterable]: > l.append(item) > > because the error gets raised already when for causes iter() to be > called on the list comprehension. > >> >> Has anyone come across this difference in the wild? Was it a problem? >> Do you >> rely on that difference, or is it a nuisance? Has it caused difficulty in >> debugging code? >> >> If you had to keep one behaviour, which would you keep? >> > > The point is: there is no difference in the behavior of comprehensions > and generator expressions, it is just how you access them: > for anything that follows the iterator protocol, a comprehension (since > it is evaluated immediately) raises during the iter() phase, while a > generator expression (which gets evaluated lazily) raises during the > next() phase where it gets swallowed. > > So in your example you would have to use the silly > > list([next(x) for x in iterable]) > > if you want the error to get raised. > > I agree this is all rather non-intuitive, but how would you change it ? > > Ah, I came across the related thread on python-ideas only now and from this I can see that, as I expected, you know everything I've written above already. In light of the discussion on the other list: I did find it annoying occasionally that raising StopIteration inside a generator expression conveys a different behavior than elsewhere. It did take me quite a while to understand why that is so, but after that it did not cause me much of a headache anymore. I would say that Guido's suggestion of transforming StopIteration raised inside a generator into some other error to eliminate ambiguity would really help in some situations, but then I'm not sure whether that's worth breaking existing code. Best, Wolfgang From toby at tobiah.org Sat Nov 8 19:34:43 2014 From: toby at tobiah.org (Tobiah) Date: Sat, 08 Nov 2014 16:34:43 -0800 Subject: Syncing audio and video for casual recording Message-ID: I decided I'd like to publish some youtube videos of me playing an instrument. The audio being the important bit, I'd like to use my existing mics, which I've been sending through a USB audio interface to my computer. I don't have any camera yet, other than a prosumer digital camera that does take decent video. The problem that I'm anticipating is the syncing of audio and video. Now, I do have a Tascam recorder with timecode, so maybe that's one way to approach this. I'm just guessing that any camera that has this would be expensive, but I didn't find out much in a very quick search. Aside from that, could I feed a decent audio signal into the camera and get the audio in that way? I've never done any video, so I'm quite in the dark about the camera part. Thanks, Tobiah --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From ethan at stoneleaf.us Sat Nov 8 22:27:41 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Sat, 08 Nov 2014 19:27:41 -0800 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> <87a943qyvn.fsf@handshake.de> <545CC204.2010301@stoneleaf.us> <8761eq424e.fsf@handshake.de> Message-ID: <545EDF2D.9070608@stoneleaf.us> On 11/08/2014 02:31 PM, Gregory Ewing wrote: > > Seems to depend on how you get hold of the object you're > inspecting the signature of. I did an experiment: > > class C(object): > > @property > def __call__(self): > return self.call > > def f(x, y): > print("Called f with %s, %s" % (x, y)) > > c = C() > c.call = f > c(17, 42) > > prints: > Called f with 17, 42 > > This works too: > > import inspect > print(inspect.getargspec(c.__call__)) > > prints: > ArgSpec(args=['x', 'y'], varargs=None, keywords=None, defaults=None) > > But > > print(inspect.getargspec(c)) > > doesn't work: > > TypeError: <__main__.C object at 0x479250> is not a Python function > > (BTW, I'm actually surprised that this technique makes c callable. > There must be more going on that just "look up __call__ in the class > object", because evaluating C.__call__ just returns the descriptor > and doesn't invoking the descriptor mechanism.) Looks like you found a bug in inspect.getargspec. And the thing going on is the normal python behavior (in __getattribute__, I believe) of examining the returned attribute to see if it is a descriptor, and if so invoking it. -- ~Ethan~ From tjreedy at udel.edu Sat Nov 8 23:38:29 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 08 Nov 2014 23:38:29 -0500 Subject: FYI: Micro Python running on kickstarter pyBoard project, now shipping In-Reply-To: References: <25b4884f-a3f9-436d-8d7d-f49f83c3e544@googlegroups.com> Message-ID: On 11/8/2014 2:41 PM, John Pinner wrote: > They are quite different devices: > > * The Raspberry Pi is a low-power general purpose computer designed > specifically for education purposes. It just so happens that it's > ideal for geek experimentation as well... > > * MicroPython is an optimised version of Python 3 running on a > micro-controller board, designed specifically for controlling > 'things' (eg robots). Doing what it is designed for, it will run far > faster and use far less power than a Pi, but cannot do any of the > general computing things a Pi can do, for example it has no means of > editing programs for MicroPython, you have to do this on, say, your > PC and download them to the MicroPython board. It won't do *any* of > the other things you can do with a Pi - watch videos, browse the net, > etc etc, but what it can do it will do faster and better. > > If you want a low-power, cheap, computer to play with and learn from, > get a Pi. > > If you want a nifty micro-controller you can program in Python, buy a > MicroPython board. Nicely explained. Thank you. -- Terry Jan Reedy From vek.m1234 at gmail.com Sun Nov 9 03:45:08 2014 From: vek.m1234 at gmail.com (Veek M) Date: Sun, 09 Nov 2014 15:15:08 +0630 Subject: How do i reduce this to a single function - the code is largely similar, just a direction of search toggle. References: Message-ID: Ned Batchelder wrote: > On 11/7/14 9:52 AM, Veek M wrote: > and you want to end up on the "def" token, not the "def" in yep, bumped into this :) thanks! From vek.m1234 at gmail.com Sun Nov 9 04:06:50 2014 From: vek.m1234 at gmail.com (Veek M) Date: Sun, 09 Nov 2014 15:36:50 +0630 Subject: functools documentation - help with funny words Message-ID: https://docs.python.org/3.4/library/functools.html 1. "A key function is a callable that accepts one argument and returns another value indicating the position in the desired collation sequence." x = ['x','z','q']; sort(key=str.upper) My understanding is that, x, y, .. are passed to the key function which converts it to upper case and returns the value, which is then sorted. So what does he mean by 'position in the desired..."? Position is 0, 1, 2.. upper is 'normalizing' the input and then sort gathers the values and sorts them.. so where is the 'key' function returning a position in the sorted- list.. or whatever.. what does a key function do? 2. lru_cache "Since a dictionary is used to cache results, the positional and keyword arguments to the function must be hashable." basically says that the args must be immutable and not subject to change because he's using the args as part of a key to the result? "To help measure the effectiveness of the cache and tune the maxsize parameter, the wrapped function is instrumented with a cache_info() function that returns a named tuple showing hits, misses, maxsize and currsize" What does he mean by 'instrument'? Just a 'helper' function or is it nested in lru_cache or structured in some special way. "An LRU (least recently used) cache works best when the most recent calls are the best predictors of upcoming calls (for example, the most popular articles on a news server tend to change each day)." What? So if article1 changes.. how does that predict anything..? If article1 is most popular, you want it in the cache, but it'll become most popular only after some time.. or is he saying that popular articles must be kicked out off the cache at the end of 24hrs? From yusufcanbayrak at gmail.com Fri Nov 7 17:04:19 2014 From: yusufcanbayrak at gmail.com (Yusuf Can Bayrak) Date: Sat, 8 Nov 2014 00:04:19 +0200 Subject: dictionary issue for formatted print Message-ID: when dictionary has one value for each key it's okey. I'm just type '% greek_letters' and it's working. But how can i assign dict's values to formatted print, if it has more values than one. > > 1. # -*- coding: utf-8 -*- > 2. greek_letters = { > 3. 'omega': ['?','?'], 'psi': ['?', '?'] , 'kapa': > '?', 'to': ['?', '?'], 'lambda': ['?', '?'], > 4. 'ksi': ['?', '?'], 'delta': ['?', '?'], 'mu': > ['?'], 'sigma': ['?', '?'], 'epsilon': ['?', '?'], > 5. 'gamma': ['?', '?'], 'phi': ['?', '?'], > 'theta': ['?', '?'] > 6. } > 7. print 'x(%(to)s) = A * cos(%(omega)s * %(to)s + %(theta)s)' % > greek_letters.values()[1] > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From satishmlmlml at gmail.com Sun Nov 9 05:42:01 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Sun, 9 Nov 2014 02:42:01 -0800 (PST) Subject: What is description attribute in python? Message-ID: What does description attribute in the following code mean? curs.execute('select * from people') colnames = [desc[0] for desc in curs.description] From satishmlmlml at gmail.com Sun Nov 9 05:44:39 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Sun, 9 Nov 2014 02:44:39 -0800 (PST) Subject: What does zip mean? Message-ID: What does zip return in the following piece of code? curs.execute('select * from people') colnames = [desc[0] for desc in curs.description] rowdicts = [] for row in curs.fetchall(): rowdicts.append(dict(zip(colnames, row))) From steve+comp.lang.python at pearwood.info Sun Nov 9 05:58:00 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 09 Nov 2014 21:58:00 +1100 Subject: What does zip mean? References: Message-ID: <545f48b9$0$13005$c3e8da3$5496439d@news.astraweb.com> satishmlmlml at gmail.com wrote: > What does zip return in the following piece of code? Have you read the Fine Manual? In Python 2, zip returns a list: zip(['a', 'b', 'c'], [1, 2, 3]) => [('a', 1), ('b', 2), ('c', 3)] https://docs.python.org/2/library/functions.html#zip In Python 3, zip does the same, except instead of a list, it returns a special iterator which produces the items on demand rather than in advance. https://docs.python.org/3/library/functions.html#zip > curs.execute('select * from people') > colnames = [desc[0] for desc in curs.description] > rowdicts = [] > for row in curs.fetchall(): > rowdicts.append(dict(zip(colnames, row))) zip(colnames, row) will return: (first column name, first item of row), (second column name, second item of row), (third column name, third item of row), etc. -- Steven From steve+comp.lang.python at pearwood.info Sun Nov 9 05:59:08 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 09 Nov 2014 21:59:08 +1100 Subject: What is description attribute in python? References: Message-ID: <545f48fc$0$13005$c3e8da3$5496439d@news.astraweb.com> satishmlmlml at gmail.com wrote: > What does description attribute in the following code mean? > > curs.execute('select * from people') > colnames = [desc[0] for desc in curs.description] It's an attribute called "description". You would need to read the documentation for curs to know what it does. What is curs? Where does it come from? -- Steven From miloshzorica at gmail.com Sun Nov 9 06:06:25 2014 From: miloshzorica at gmail.com (milos zorica) Date: Sun, 9 Nov 2014 08:06:25 -0300 Subject: What does zip mean? In-Reply-To: <545f48b9$0$13005$c3e8da3$5496439d@news.astraweb.com> References: <545f48b9$0$13005$c3e8da3$5496439d@news.astraweb.com> Message-ID: sorry my bad On Sun, Nov 9, 2014 at 7:58 AM, Steven D'Aprano < steve+comp.lang.python at pearwood.info> wrote: > satishmlmlml at gmail.com wrote: > > > What does zip return in the following piece of code? > > Have you read the Fine Manual? > > In Python 2, zip returns a list: > > zip(['a', 'b', 'c'], [1, 2, 3]) > > => [('a', 1), ('b', 2), ('c', 3)] > > https://docs.python.org/2/library/functions.html#zip > > > In Python 3, zip does the same, except instead of a list, it returns a > special iterator which produces the items on demand rather than in advance. > > https://docs.python.org/3/library/functions.html#zip > > > > > curs.execute('select * from people') > > colnames = [desc[0] for desc in curs.description] > > rowdicts = [] > > for row in curs.fetchall(): > > rowdicts.append(dict(zip(colnames, row))) > > zip(colnames, row) will return: > > (first column name, first item of row), > (second column name, second item of row), > (third column name, third item of row), > etc. > > > > -- > Steven > > -- > https://mail.python.org/mailman/listinfo/python-list > -- Milos Zorica +1 845 277 0549 | +1 786 471 4846 -------------- next part -------------- An HTML attachment was scrubbed... URL: From satishmlmlml at gmail.com Sun Nov 9 06:05:40 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Sun, 9 Nov 2014 03:05:40 -0800 (PST) Subject: What is description attribute in python? In-Reply-To: <545f48fc$0$13005$c3e8da3$5496439d@news.astraweb.com> References: <545f48fc$0$13005$c3e8da3$5496439d@news.astraweb.com> Message-ID: curs is coming from the following piece of code import sqlite3 conn = sqlite3.connect('dbase1') curs = conn.cursor() From Deepfriedice at openmailbox.org Sun Nov 9 06:08:15 2014 From: Deepfriedice at openmailbox.org (Deepfriedice) Date: Sun, 09 Nov 2014 21:08:15 +1000 Subject: What is description attribute in python? References: <545f48fc$0$13005$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 09/11/14 20:59, Steven D'Aprano wrote: > It's an attribute called "description". You would need to read the > documentation for curs to know what it does. > > What is curs? Where does it come from? It looks like a cursor from an SQL DB library. For example, sqlite3 in the standard library provides a Cursor.description attribute: https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.description > This read-only attribute provides the column names of the last query. > To remain compatible with the Python DB API, it returns a 7-tuple for > each column where the last six items of each tuple are None. > > It is set for SELECT statements without any matching rows as well. You'll have to read the documentation from the library you're using to determine what it actually does. From satishmlmlml at gmail.com Sun Nov 9 06:11:44 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Sun, 9 Nov 2014 03:11:44 -0800 (PST) Subject: What is rstrip() in python? Message-ID: What is rstrip() in python? What does it do in the following piece of code? import sqlite3 conn = sqlite3.connect('dbase1') curs = conn.cursor() file = open('data.txt') rows = [line.rstrip().split(',') for line in file] From rosuav at gmail.com Sun Nov 9 06:28:29 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Nov 2014 22:28:29 +1100 Subject: What is rstrip() in python? In-Reply-To: References: Message-ID: On Sun, Nov 9, 2014 at 10:11 PM, wrote: > What is rstrip() in python? > > What does it do in the following piece of code? > > import sqlite3 > conn = sqlite3.connect('dbase1') > curs = conn.cursor() > > file = open('data.txt') > rows = [line.rstrip().split(',') for line in file] Do you know what type of object 'line' is here? Do you know what you get when you iterate over a file? Get an object of that type in the interactive interpreter, maybe like this: file = open('data.txt') line = next(file) Then you can find out about its methods: help(line.rstrip) That should tell you what you want to know. ChrisA From greg.ewing at canterbury.ac.nz Sun Nov 9 06:38:07 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 10 Nov 2014 00:38:07 +1300 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> <87a943qyvn.fsf@handshake.de> <545CC204.2010301@stoneleaf.us> <8761eq424e.fsf@handshake.de> Message-ID: Ethan Furman wrote: > And the thing going on is the normal python behavior (in > __getattribute__, I believe) of examining the returned attribute to see > if it is a descriptor, and if so invoking it. Only if you look it up through the instance, though. Normally, if you look up an attribute on a class, the descriptor protocol doesn't get triggered. -- Greg From flebber.crue at gmail.com Sun Nov 9 07:07:40 2014 From: flebber.crue at gmail.com (flebber) Date: Sun, 9 Nov 2014 04:07:40 -0800 (PST) Subject: Engaging, powerful - video inspriration/learning - Your best selections In-Reply-To: <1e4fc1b2-61e9-4cba-9d2d-0ff69f73f3ee@googlegroups.com> References: <1e4fc1b2-61e9-4cba-9d2d-0ff69f73f3ee@googlegroups.com> Message-ID: <604cfd39-0a33-4902-89bd-4e232b8f2eca@googlegroups.com> Not fans of videos hey(well python videos anyway) bugger. Sayth. From python.list at tim.thechases.com Sun Nov 9 05:59:10 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 9 Nov 2014 04:59:10 -0600 Subject: What is description attribute in python? In-Reply-To: References: Message-ID: <20141109045910.1e325bdf@bigbox.christie.dr> On 2014-11-09 02:42, satishmlmlml at gmail.com wrote: > What does description attribute in the following code mean? > > curs.execute('select * from people') > colnames = [desc[0] for desc in curs.description] http://legacy.python.org/dev/peps/pep-0249/#cursor-attributes -tkc From steve+comp.lang.python at pearwood.info Sun Nov 9 07:55:10 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 09 Nov 2014 23:55:10 +1100 Subject: Syncing audio and video for casual recording References: Message-ID: <545f642f$0$12986$c3e8da3$5496439d@news.astraweb.com> Tobiah wrote: > I decided I'd like to publish some youtube videos of me playing > an instrument. The audio being the important bit, I'd like to use > my existing mics, which I've been sending through a USB audio interface > to my computer. > > I don't have any camera yet, other than a prosumer digital > camera that does take decent video. The problem that I'm > anticipating is the syncing of audio and video. [...] I think you may have sent this to the wrong mailing list (or newsgroup). This is about the Python programming language. -- Steven From steve+comp.lang.python at pearwood.info Sun Nov 9 07:57:22 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 09 Nov 2014 23:57:22 +1100 Subject: What is rstrip() in python? References: Message-ID: <545f64b3$0$12986$c3e8da3$5496439d@news.astraweb.com> satishmlmlml at gmail.com wrote: > What is rstrip() in python? Have you read the Fine Manual? Did you try googling first? https://duckduckgo.com/html/?q=python+rstrip > What does it do in the following piece of code? It removes trailing whitespace. > import sqlite3 > conn = sqlite3.connect('dbase1') > curs = conn.cursor() > > file = open('data.txt') > rows = [line.rstrip().split(',') for line in file] -- Steven From steve+comp.lang.python at pearwood.info Sun Nov 9 08:14:07 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 10 Nov 2014 00:14:07 +1100 Subject: [Python-Dev] Dinamically set __call__ method References: <545919B6.7040007@stoneleaf.us> <87a943qyvn.fsf@handshake.de> <545CC204.2010301@stoneleaf.us> <8761eq424e.fsf@handshake.de> Message-ID: <545f68a0$0$12993$c3e8da3$5496439d@news.astraweb.com> Gregory Ewing wrote: > Ethan Furman wrote: >> And the thing going on is the normal python behavior (in >> __getattribute__, I believe) of examining the returned attribute to see >> if it is a descriptor, and if so invoking it. > > Only if you look it up through the instance, though. > Normally, if you look up an attribute on a class, > the descriptor protocol doesn't get triggered. Since this whole thread is about giving instances their own individual __call__ methods, I don't think that doing the look-up on the class is part of the requirements :-) This seems to work for me: class call_instance(object): def __get__(self, obj, cls=None): if cls is None: cls = type(obj) if obj is None: obj = cls return obj.my_call class SomeClass(object): __call__ = call_instance() a = SomeClass() b = SomeClass() c = SomeClass() c.eggs = 23 from types import MethodType a.my_call = lambda x, y=1: x/y b.my_call = lambda spam: str(spam).upper() c.my_call = MethodType(lambda self: self.eggs + 1, c) -- Steven From davea at davea.name Sun Nov 9 08:41:41 2014 From: davea at davea.name (Dave Angel) Date: Sun, 9 Nov 2014 08:41:41 -0500 (EST) Subject: dictionary issue for formatted print References: Message-ID: Yusuf Can Bayrak Wrote in message: > when dictionary has one value for each key it's okey. I'm just type '% greek_letters' and it's working. > > But how can i assign dict's values to formatted print, if it has more values than one. # -*- coding: utf-8 -*-greek_letters = { 'omega': ['?','?'], 'psi': ['?', '?'] , 'kapa': '?', 'to': ['?', '?'], 'lambda': ['?', '?'], 'ksi': ['?', '?'], 'delta': ['?', '?'], 'mu': ['?'], 'sigma': ['?', '?'], 'epsilon': ['?', '?'], 'gamma': ['?', '?'], 'phi': ['?', '?'], 'theta': ['?', '?'] }print 'x(%(to)s) = A * cos(%(omega)s * %(to)s + %(theta)s)' % greek_letters.values()[1] > How do you intend for the logic to choose? You need to decide the logic (usually by doing it by hand) before you can figure out how to code it. My assumption is that you want the expression to decide (the thing starting "A *" ). So you'll need to have two separate keys, like omega and Omega. The dictionary gets a little larger, and it just works. -- DaveA From breamoreboy at yahoo.co.uk Sun Nov 9 09:13:14 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 09 Nov 2014 14:13:14 +0000 Subject: What is description attribute in python? In-Reply-To: References: <545f48fc$0$13005$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 09/11/2014 11:05, satishmlmlml at gmail.com wrote: > curs is coming from the following piece of code > > import sqlite3 > conn = sqlite3.connect('dbase1') > curs = conn.cursor() > Today's exercise is to find the documentation and read it before posting another question. Better still is to use the interactive prompt to run the above and the help facility at the same time. IMHO this is the best possible way to learn Python. -- 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 Sun Nov 9 09:17:16 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 09 Nov 2014 14:17:16 +0000 Subject: What is rstrip() in python? In-Reply-To: References: Message-ID: On 09/11/2014 11:11, satishmlmlml at gmail.com wrote: > What is rstrip() in python? It's a function or method call. > > What does it do in the following piece of code? I'm not actually sure. Would you be kind enough to look it up in the documentation for me and let me know, thanks? > > import sqlite3 > conn = sqlite3.connect('dbase1') > curs = conn.cursor() > > file = open('data.txt') > rows = [line.rstrip().split(',') for line in file] > -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From __peter__ at web.de Sun Nov 9 10:04:20 2014 From: __peter__ at web.de (Peter Otten) Date: Sun, 09 Nov 2014 16:04:20 +0100 Subject: dictionary issue for formatted print References: Message-ID: Yusuf Can Bayrak wrote: > when dictionary has one value for each key it's okey. I'm just type '% > greek_letters' and it's working. > > But how can i assign dict's values to formatted print, if it has more > values than one. > >> >> 1. # -*- coding: utf-8 -*- >> 2. greek_letters = { >> 3. 'omega': ['?','?'], 'psi': ['?', '?'] , 'kapa': >> '?', 'to': ['?', '?'], 'lambda': ['?', '?'], >> 4. 'ksi': ['?', '?'], 'delta': ['?', '?'], 'mu': >> ['?'], 'sigma': ['?', '?'], 'epsilon': ['?', '?'], >> 5. 'gamma': ['?', '?'], 'phi': ['?', '?'], >> 'theta': ['?', '?'] >> 6. } >> 7. print 'x(%(to)s) = A * cos(%(omega)s * %(to)s + %(theta)s)' % >> greek_letters.values()[1] You can build a temporary dict: >>> greek_letters = { ... 'omega': ['?','?'], 'to': ['?', '?'], 'theta': ['?', '?']} >>> print 'x(%(to)s) = A * cos(%(omega)s * %(to)s + %(theta)s)' % { ... k: v[1] for k, v in greek_letters.items()} x(?) = A * cos(? * ? + ?) Python also offers an alternative style of formatting that allows subscripts: >>> print 'x({to[0]}) = A * cos({omega[1]} * {to[0]} + {theta[1]})'.format( ... **greek_letters) x(?) = A * cos(? * ? + ?) From ian.g.kelly at gmail.com Sun Nov 9 12:05:03 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 9 Nov 2014 10:05:03 -0700 Subject: functools documentation - help with funny words In-Reply-To: References: Message-ID: On Sun, Nov 9, 2014 at 2:06 AM, Veek M wrote: > https://docs.python.org/3.4/library/functools.html > > 1. "A key function is a callable that accepts one argument and returns > another value indicating the position in the desired collation sequence." > > x = ['x','z','q']; sort(key=str.upper) This call isn't correct. sort is a list method, not a builtin. So the above should be: >>> x = ['x', 'z', 'q'] >>> x.sort(key=str.upper) > My understanding is that, x, y, .. are passed to the key function which > converts it to upper case and returns the value, which is then sorted. > So what does he mean by 'position in the desired..."? Position is 0, 1, 2.. > > upper is 'normalizing' the input and then sort gathers the values and sorts > them.. so where is the 'key' function returning a position in the sorted- > list.. or whatever.. what does a key function do? When you pass a key function to the list.sort method, the key function is called on each element of the list, and the return values are compared to sort the list in place of the elements. For example: >>> sorted(['23', '4', '162']) ['162', '23', '4'] Because '162' < '23' < '4'. But: >>> sorted(['23', '4', '162'], key=int) ['4', '23', '162'] Because 4 < 23 < 162. https://docs.python.org/3/glossary.html?highlight=%22key+function%22 > 2. lru_cache > > "Since a dictionary is used to cache results, the positional and keyword > arguments to the function must be hashable." > > basically says that the args must be immutable and not subject to change > because he's using the args as part of a key to the result? https://docs.python.org/3/glossary.html?highlight=hashable > "To help measure the effectiveness of the cache and tune the maxsize > parameter, the wrapped function is instrumented with a cache_info() function > that returns a named tuple showing hits, misses, maxsize and currsize" > > What does he mean by 'instrument'? Just a 'helper' function or is it nested > in lru_cache or structured in some special way. It means code added in some way to enable debugging or performance analysis. http://en.wikipedia.org/wiki/Instrumentation_(computer_programming) In this case it takes the form of a method added to the function object: >>> @functools.lru_cache() ... def codepoint(s): return ord(s) ... >>> list(map(codepoint, 'abracadabra')) [97, 98, 114, 97, 99, 97, 100, 97, 98, 114, 97] >>> codepoint.cache_info() CacheInfo(hits=6, misses=5, maxsize=128, currsize=5) > "An LRU (least recently used) cache works best when the most recent calls > are the best predictors of upcoming calls (for example, the most popular > articles on a news server tend to change each day)." > > What? So if article1 changes.. how does that predict anything..? If article1 > is most popular, you want it in the cache, but it'll become most popular > only after some time.. or is he saying that popular articles must be kicked > out off the cache at the end of 24hrs? By "predicts" it means whether the fact that an item was recently requested is positively correlated with the probability that it will soon be requested again. Popular articles are an example of this; when an article is requested, there is a good chance that it was requested because it is featured or trending and will likely be requested again soon. On the other hand if the incoming requests tend to be random and not correlated in time, then an LRU cache won't work as well. If each request is negatively correlated with its probability of being requested again soon (e.g. a graph traversal where some property is being computed once for each node; once it's been computed for a particular node, it won't be called with the same node again during the same traversal), then an LRU cache may not perform well at all. From tjreedy at udel.edu Sun Nov 9 12:46:14 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 09 Nov 2014 12:46:14 -0500 Subject: What is rstrip() in python? In-Reply-To: References: Message-ID: On 11/9/2014 6:11 AM, satishmlmlml at gmail.com wrote: > What is rstrip() in python? The manuals have a rather complete index. If 'rstrip' is missing from the index, let us know so we can fix it. -- Terry Jan Reedy From joel.goldstick at gmail.com Sun Nov 9 14:16:23 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 9 Nov 2014 14:16:23 -0500 Subject: What is rstrip() in python? In-Reply-To: References: Message-ID: On Sun, Nov 9, 2014 at 12:46 PM, Terry Reedy wrote: > On 11/9/2014 6:11 AM, satishmlmlml at gmail.com wrote: >> >> What is rstrip() in python? google on 'rstrip python' gets this at first link: https://docs.python.org/2/library/stdtypes.html#str.rstrip google is your friend. > > > The manuals have a rather complete index. If 'rstrip' is missing from the > index, let us know so we can fix it. > > -- > Terry Jan Reedy > > -- > https://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick http://joelgoldstick.com From khalidness at gmail.com Sun Nov 9 14:58:49 2014 From: khalidness at gmail.com (Syed Khalid) Date: Sun, 9 Nov 2014 11:58:49 -0800 (PST) Subject: Python script that does batch find and replace in txt files Message-ID: Python script that does batch find and replace in txt files Need a python script that opens all .txt files in a folder find replace/delete text and save files. I have text files and I need to perform below steps for each file. Step 1: Put cursor at start of file and Search for "Contact's Name:". Delete all the rows before it. Step 2: Put cursor at end of file, Search for "Contact's Name:" select option UP. Step 3: Search for "Photo of the" Replace with blanks Step 4: Search for "Contact is" Replace with blanks Step 5: Search for "Contact's Name:" Replace with blanks Step 6: Search for "Age:" Replace with blanks Step 7: Search for "Sex:" Replace with blanks Step 8: Search for "House No:" Replace with blanks Step 9: Search for "available" Replace with blanks Step 10: Remove Empty Lines Containing Blank Characters from file Step 11: Trim Leading Space for each line Step 12: Trim Trailing Space after each line Step 13: Search for - (hyphen) Replace with _ (underscore) Step 14: Save file. Currently I have recorded a macro in Notepad++. I open each file, run macro and save file. As there are many files I was looking for a program to automate the process. I posted the same query in Notepad++ forum. I got a reply that it can be done by using Python script. Kindly do the needful. Thank you. khalidness From ethan at stoneleaf.us Sun Nov 9 15:16:17 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Sun, 09 Nov 2014 12:16:17 -0800 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> <87a943qyvn.fsf@handshake.de> <545CC204.2010301@stoneleaf.us> <8761eq424e.fsf@handshake.de> Message-ID: <545FCB91.4010703@stoneleaf.us> On 11/09/2014 03:38 AM, Gregory Ewing wrote: > Ethan Furman wrote: >> >> And the thing going on is the normal python behavior (in __getattribute__, I believe) of examining the returned >> attribute to see if it is a descriptor, and if so invoking it. > > Only if you look it up through the instance, though. > Normally, if you look up an attribute on a class, > the descriptor protocol doesn't get triggered. Hrmm, maybe we're not talking about the same thing. I was responding to your comment: > (BTW, I'm actually surprised that this technique makes c callable. > There must be more going on that just "look up __call__ in the class > object", because evaluating C.__call__ just returns the descriptor > and doesn't invoking the descriptor mechanism.) which seems to clash with what you just said. -- ~Ethan~ From breamoreboy at yahoo.co.uk Sun Nov 9 15:17:54 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 09 Nov 2014 20:17:54 +0000 Subject: Python script that does batch find and replace in txt files In-Reply-To: References: Message-ID: On 09/11/2014 19:58, Syed Khalid wrote: > Python script that does batch find and replace in txt files Need a python script that opens all .txt files in a folder find replace/delete text and save files. > > I have text files and I need to perform below steps for each file. > > Step 1: Put cursor at start of file and Search for "Contact's Name:". Delete all the rows before it. > Step 2: Put cursor at end of file, Search for "Contact's Name:" select option UP. > Step 3: Search for "Photo of the" Replace with blanks > Step 4: Search for "Contact is" Replace with blanks > Step 5: Search for "Contact's Name:" Replace with blanks > Step 6: Search for "Age:" Replace with blanks > Step 7: Search for "Sex:" Replace with blanks > Step 8: Search for "House No:" Replace with blanks > Step 9: Search for "available" Replace with blanks > Step 10: Remove Empty Lines Containing Blank Characters from file > Step 11: Trim Leading Space for each line > Step 12: Trim Trailing Space after each line > Step 13: Search for - (hyphen) Replace with _ (underscore) > Step 14: Save file. > > Currently I have recorded a macro in Notepad++. > I open each file, run macro and save file. > As there are many files I was looking for a program to automate the process. > > I posted the same query in Notepad++ forum. I got a reply that it can be done by using Python script. > > Kindly do the needful. > > Thank you. > khalidness > No problem once your cheque made payable to the Python Software Foundation has been cashed. I'll pluck a figure of ?200 out of the air, YMMV. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From fomcl at yahoo.com Sun Nov 9 15:23:20 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 9 Nov 2014 20:23:20 +0000 (UTC) Subject: Python script that does batch find and replace in txt files In-Reply-To: References: Message-ID: <46769509.90793.1415564600851.JavaMail.yahoo@jws10740.mail.gq1.yahoo.com> ----- Original Message ----- > From: Syed Khalid > To: python-list at python.org > Cc: > Sent: Sunday, November 9, 2014 8:58 PM > Subject: Python script that does batch find and replace in txt files > > Python script that does batch find and replace in txt files Need a python script > that opens all .txt files in a folder find replace/delete text and save files. > > I have text files and I need to perform below steps for each file. > > Step 1: Put cursor at start of file and Search for "Contact's > Name:". Delete all the rows before it. > Step 2: Put cursor at end of file, Search for "Contact's Name:" > select option UP. > Step 3: Search for "Photo of the" Replace with blanks > Step 4: Search for "Contact is" Replace with blanks > Step 5: Search for "Contact's Name:" Replace with blanks > Step 6: Search for "Age:" Replace with blanks > Step 7: Search for "Sex:" Replace with blanks > Step 8: Search for "House No:" Replace with blanks > Step 9: Search for "available" Replace with blanks > Step 10: Remove Empty Lines Containing Blank Characters from file > Step 11: Trim Leading Space for each line > Step 12: Trim Trailing Space after each line > Step 13: Search for - (hyphen) Replace with _ (underscore) > Step 14: Save file. something like (untested) import glob, codecs, re, os regex = re.compile(r"Age: |Sex: |House No: ") # etc etc for txt in glob.glob("/some/path/*.txt"): with codecs.open(txt, encoding="utf-8") as f: oldlines = f.readlines() for i, line in enumerate(oldlines): if "Contact's Name: " in line: break newlines = [regex.sub("", line).strip().replace("-", "_") for line in oldlines[i:] with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: w.write(os.linesep.join(newlines)) > > Currently I have recorded a macro in Notepad++. > I open each file, run macro and save file. > As there are many files I was looking for a program to automate the process. > > I posted the same query in Notepad++ forum. I got a reply that it can be done by > using Python script. > > Kindly do the needful. > > Thank you. > khalidness > > -- > https://mail.python.org/mailman/listinfo/python-list > From khalidness at gmail.com Sun Nov 9 15:52:35 2014 From: khalidness at gmail.com (Syed Khalid) Date: Mon, 10 Nov 2014 02:22:35 +0530 Subject: Python script that does batch find and replace in txt files In-Reply-To: <46769509.90793.1415564600851.JavaMail.yahoo@jws10740.mail.gq1.yahoo.com> References: <46769509.90793.1415564600851.JavaMail.yahoo@jws10740.mail.gq1.yahoo.com> Message-ID: Hi Albert, Thank you for script. I am getting the below error : File "EamClean.log", line 12 with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: ^ SyntaxError: invalid syntax Kindly do the needful. On Mon, Nov 10, 2014 at 1:53 AM, Albert-Jan Roskam wrote: > > > > > ----- Original Message ----- > > From: Syed Khalid > > To: python-list at python.org > > Cc: > > Sent: Sunday, November 9, 2014 8:58 PM > > Subject: Python script that does batch find and replace in txt files > > > > Python script that does batch find and replace in txt files Need a > python script > > that opens all .txt files in a folder find replace/delete text and save > files. > > > > I have text files and I need to perform below steps for each file. > > > > Step 1: Put cursor at start of file and Search for "Contact's > > Name:". Delete all the rows before it. > > Step 2: Put cursor at end of file, Search for "Contact's Name:" > > select option UP. > > Step 3: Search for "Photo of the" Replace with blanks > > Step 4: Search for "Contact is" Replace with blanks > > Step 5: Search for "Contact's Name:" Replace with blanks > > Step 6: Search for "Age:" Replace with blanks > > Step 7: Search for "Sex:" Replace with blanks > > Step 8: Search for "House No:" Replace with blanks > > Step 9: Search for "available" Replace with blanks > > Step 10: Remove Empty Lines Containing Blank Characters from file > > Step 11: Trim Leading Space for each line > > Step 12: Trim Trailing Space after each line > > Step 13: Search for - (hyphen) Replace with _ (underscore) > > > Step 14: Save file. > > something like (untested) > > > import glob, codecs, re, os > > regex = re.compile(r"Age: |Sex: |House No: ") # etc etc > > for txt in glob.glob("/some/path/*.txt"): > with codecs.open(txt, encoding="utf-8") as f: > oldlines = f.readlines() > for i, line in enumerate(oldlines): > if "Contact's Name: " in line: > break > newlines = [regex.sub("", line).strip().replace("-", "_") for line in > oldlines[i:] > with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: > w.write(os.linesep.join(newlines)) > > > > > > > > Currently I have recorded a macro in Notepad++. > > I open each file, run macro and save file. > > As there are many files I was looking for a program to automate the > process. > > > > I posted the same query in Notepad++ forum. I got a reply that it can be > done by > > using Python script. > > > > Kindly do the needful. > > > > Thank you. > > khalidness > > > > -- > > https://mail.python.org/mailman/listinfo/python-list > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From khalidness at gmail.com Sun Nov 9 16:08:13 2014 From: khalidness at gmail.com (Syed Khalid) Date: Sun, 9 Nov 2014 13:08:13 -0800 (PST) Subject: Python script that does batch find and replace in txt files In-Reply-To: References: <46769509.90793.1415564600851.JavaMail.yahoo@jws10740.mail.gq1.yahoo.com> Message-ID: <76a85d07-fbf2-49a7-866a-c990aa0f85b1@googlegroups.com> My Script, I have added import glob, codecs, re, os regex = re.compile(r"Age: |Sex: |House No: ") # etc etc Script I executed in EditRocket : for txt in glob.glob("/D:/Python/source/*.txt"): with codecs.open(txt, encoding="utf-8") as f: oldlines = f.readlines() for i, line in enumerate(oldlines): if "Contact's Name:" in line: break newlines = [regex.sub("", line).strip().replace("-", "_") for line in oldlines[i:] with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: w.write(os.linesep.join(newlines)) Error Message : File "EamClean.log", line 12 with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: ^ SyntaxError: invalid syntax Kindly do the needful From khalidness at gmail.com Sun Nov 9 16:20:09 2014 From: khalidness at gmail.com (Syed Khalid) Date: Mon, 10 Nov 2014 02:50:09 +0530 Subject: Python script that does batch find and replace in txt files In-Reply-To: References: <46769509.90793.1415564600851.JavaMail.yahoo@jws10740.mail.gq1.yahoo.com> Message-ID: Code after adding path of .txt files : import glob, codecs, re, os regex = re.compile(r"Age: |Sex: |House No: ") # etc etc for txt in glob.glob("D:/Python/source/*.txt"): with codecs.open(txt, encoding="utf-8") as f: oldlines = f.readlines() for i, line in enumerate(oldlines): if "Elector's Name:" in line: break newlines = [regex.sub("", line).strip().replace("-", "_") for line in oldlines[i:] with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: w.write(os.linesep.join(newlines)) I executed code in edit rocket. Error message : File "EamClean.log", line 12 with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: ^ SyntaxError: invalid syntax On Mon, Nov 10, 2014 at 2:22 AM, Syed Khalid wrote: > Hi Albert, > > Thank you for script. > > I am getting the below error : > > File "EamClean.log", line 12 > with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: > ^ > SyntaxError: invalid syntax > > Kindly do the needful. > > On Mon, Nov 10, 2014 at 1:53 AM, Albert-Jan Roskam > wrote: > >> >> >> >> >> ----- Original Message ----- >> > From: Syed Khalid >> > To: python-list at python.org >> > Cc: >> > Sent: Sunday, November 9, 2014 8:58 PM >> > Subject: Python script that does batch find and replace in txt files >> > >> > Python script that does batch find and replace in txt files Need a >> python script >> > that opens all .txt files in a folder find replace/delete text and save >> files. >> > >> > I have text files and I need to perform below steps for each file. >> > >> > Step 1: Put cursor at start of file and Search for "Contact's >> > Name:". Delete all the rows before it. >> > Step 2: Put cursor at end of file, Search for "Contact's Name:" >> > select option UP. >> > Step 3: Search for "Photo of the" Replace with blanks >> > Step 4: Search for "Contact is" Replace with blanks >> > Step 5: Search for "Contact's Name:" Replace with blanks >> > Step 6: Search for "Age:" Replace with blanks >> > Step 7: Search for "Sex:" Replace with blanks >> > Step 8: Search for "House No:" Replace with blanks >> > Step 9: Search for "available" Replace with blanks >> > Step 10: Remove Empty Lines Containing Blank Characters from file >> > Step 11: Trim Leading Space for each line >> > Step 12: Trim Trailing Space after each line >> > Step 13: Search for - (hyphen) Replace with _ (underscore) >> >> > Step 14: Save file. >> >> something like (untested) >> >> >> import glob, codecs, re, os >> >> regex = re.compile(r"Age: |Sex: |House No: ") # etc etc >> >> for txt in glob.glob("/some/path/*.txt"): >> with codecs.open(txt, encoding="utf-8") as f: >> oldlines = f.readlines() >> for i, line in enumerate(oldlines): >> if "Contact's Name: " in line: >> break >> newlines = [regex.sub("", line).strip().replace("-", "_") for line in >> oldlines[i:] >> with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: >> w.write(os.linesep.join(newlines)) >> >> >> >> >> > >> > Currently I have recorded a macro in Notepad++. >> > I open each file, run macro and save file. >> > As there are many files I was looking for a program to automate the >> process. >> > >> > I posted the same query in Notepad++ forum. I got a reply that it can >> be done by >> > using Python script. >> > >> > Kindly do the needful. >> > >> > Thank you. >> > khalidness >> > >> > -- >> > https://mail.python.org/mailman/listinfo/python-list >> > >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sun Nov 9 16:44:53 2014 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 09 Nov 2014 21:44:53 +0000 Subject: Python script that does batch find and replace in txt files In-Reply-To: References: <46769509.90793.1415564600851.JavaMail.yahoo@jws10740.mail.gq1.yahoo.com> Message-ID: <545FE055.5080805@mrabarnett.plus.com> On 2014-11-09 21:20, Syed Khalid wrote: > > Code after adding path of .txt files : > > import glob, codecs, re, os > > regex = re.compile(r"Age: |Sex: |House No: ") # etc etc > > for txt in glob.glob("D:/Python/source/*.txt"): > with codecs.open(txt, encoding="utf-8") as f: > oldlines = f.readlines() > for i, line in enumerate(oldlines): > if "Elector's Name:" in line: > break > newlines = [regex.sub("", line).strip().replace("-", "_") for line > in oldlines[i:] > with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: > w.write(os.linesep.join(newlines)) > > > I executed code in edit rocket. > > Error message : > > > File "EamClean.log", line 12 > with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: > ^ > SyntaxError: invalid syntax > [snip] The previous line is missing a ']' on the end. It should be: newlines = [regex.sub("", line).strip().replace("-", "_") for line in oldlines[i:]] From khalidness at gmail.com Sun Nov 9 16:51:37 2014 From: khalidness at gmail.com (Syed Khalid) Date: Mon, 10 Nov 2014 03:21:37 +0530 Subject: Python script that does batch find and replace in txt files In-Reply-To: References: <46769509.90793.1415564600851.JavaMail.yahoo@jws10740.mail.gq1.yahoo.com> Message-ID: Albert, Thanks a million for script, It worked fine after I closed the bracket. import glob, codecs, re, os regex = re.compile(r"Age: |Sex: |House No: ") # etc etc for txt in glob.glob("D:/Python/source/*.txt"): with codecs.open(txt, encoding="utf-8") as f: oldlines = f.readlines() for i, line in enumerate(oldlines): if "Elector's Name:" in line: break newlines = [regex.sub("", line).strip().replace("-", "_") for line in oldlines[i:]] with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: w.write(os.linesep.join(newlines)) This program is not deleting the empty lines containing blank characters. Kindly do the needful. On Mon, Nov 10, 2014 at 2:50 AM, Syed Khalid wrote: > > Code after adding path of .txt files : > > import glob, codecs, re, os > > regex = re.compile(r"Age: |Sex: |House No: ") # etc etc > > for txt in glob.glob("D:/Python/source/*.txt"): > with codecs.open(txt, encoding="utf-8") as f: > oldlines = f.readlines() > for i, line in enumerate(oldlines): > if "Elector's Name:" in line: > break > newlines = [regex.sub("", line).strip().replace("-", "_") for line in > oldlines[i:] > with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: > w.write(os.linesep.join(newlines)) > > > I executed code in edit rocket. > > Error message : > > > File "EamClean.log", line 12 > with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: > ^ > SyntaxError: invalid syntax > > > > > > On Mon, Nov 10, 2014 at 2:22 AM, Syed Khalid wrote: > >> Hi Albert, >> >> Thank you for script. >> >> I am getting the below error : >> >> File "EamClean.log", line 12 >> with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: >> ^ >> SyntaxError: invalid syntax >> >> Kindly do the needful. >> >> On Mon, Nov 10, 2014 at 1:53 AM, Albert-Jan Roskam >> wrote: >> >>> >>> >>> >>> >>> ----- Original Message ----- >>> > From: Syed Khalid >>> > To: python-list at python.org >>> > Cc: >>> > Sent: Sunday, November 9, 2014 8:58 PM >>> > Subject: Python script that does batch find and replace in txt files >>> > >>> > Python script that does batch find and replace in txt files Need a >>> python script >>> > that opens all .txt files in a folder find replace/delete text and >>> save files. >>> > >>> > I have text files and I need to perform below steps for each file. >>> > >>> > Step 1: Put cursor at start of file and Search for "Contact's >>> > Name:". Delete all the rows before it. >>> > Step 2: Put cursor at end of file, Search for "Contact's Name:" >>> > select option UP. >>> > Step 3: Search for "Photo of the" Replace with blanks >>> > Step 4: Search for "Contact is" Replace with blanks >>> > Step 5: Search for "Contact's Name:" Replace with blanks >>> > Step 6: Search for "Age:" Replace with blanks >>> > Step 7: Search for "Sex:" Replace with blanks >>> > Step 8: Search for "House No:" Replace with blanks >>> > Step 9: Search for "available" Replace with blanks >>> > Step 10: Remove Empty Lines Containing Blank Characters from file >>> > Step 11: Trim Leading Space for each line >>> > Step 12: Trim Trailing Space after each line >>> > Step 13: Search for - (hyphen) Replace with _ (underscore) >>> >>> > Step 14: Save file. >>> >>> something like (untested) >>> >>> >>> import glob, codecs, re, os >>> >>> regex = re.compile(r"Age: |Sex: |House No: ") # etc etc >>> >>> for txt in glob.glob("/some/path/*.txt"): >>> with codecs.open(txt, encoding="utf-8") as f: >>> oldlines = f.readlines() >>> for i, line in enumerate(oldlines): >>> if "Contact's Name: " in line: >>> break >>> newlines = [regex.sub("", line).strip().replace("-", "_") for line >>> in oldlines[i:] >>> with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: >>> w.write(os.linesep.join(newlines)) >>> >>> >>> >>> >>> > >>> > Currently I have recorded a macro in Notepad++. >>> > I open each file, run macro and save file. >>> > As there are many files I was looking for a program to automate the >>> process. >>> > >>> > I posted the same query in Notepad++ forum. I got a reply that it can >>> be done by >>> > using Python script. >>> > >>> > Kindly do the needful. >>> > >>> > Thank you. >>> > khalidness >>> > >>> > -- >>> > https://mail.python.org/mailman/listinfo/python-list >>> > >>> >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Sun Nov 9 17:58:23 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 9 Nov 2014 14:58:23 -0800 Subject: Python script that does batch find and replace in txt files Message-ID: <1415573903.73187.BPMail_high_carrier@web163801.mail.gq1.yahoo.com> ---------------------------- On Sun, Nov 9, 2014 10:51 PM CET Syed Khalid wrote: >Albert, > >Thanks a million for script, > >It worked fine after I closed the bracket. > > >import glob, codecs, re, os > >regex = re.compile(r"Age: |Sex: |House No: ") # etc etc > >for txt in glob.glob("D:/Python/source/*.txt"): > with codecs.open(txt, encoding="utf-8") as f: > oldlines = f.readlines() > for i, line in enumerate(oldlines): > if "Elector's Name:" in line: > break > newlines = [regex.sub(", line).strip().replace("-", "_") for line in >oldlines[i:]] You're welcome newlines = [regex.sub("", line).strip().replace("-", "_") for line in oldlines[i:] if line.strip()] From rosuav at gmail.com Sun Nov 9 18:31:21 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 10 Nov 2014 10:31:21 +1100 Subject: __missing__ for the top-level Python script Message-ID: Let's have some fun nutting out possible implementations for a bad idea :) If you want a dictionary that prepopulates itself on demand, you implement __missing__. Is there a way to implement the same thing for the __main__ module? Since it isn't imported (as such), I don't think "switch out what's in sys.modules" will work, though I'm open to correction on that. Desired result: Implicit imports. ## test.py print("Path separator is",os.sep) try: print("Version", psycopg2.__version__, "of psycopg2 is installed.") except NameError: print("You don't have psycopg2 installed.") sys.exit(1) So the semantics should be: If NameError would be raised (not including UnboundLocalError, which still represents an error), attempt to import the absent name. If successful, continue as if it had already been done. If ImportError is raised, suppress it and let the original NameError happen. Yes, this is extremely unPythonic. But just as an intellectual exercise, can this be done? I'm assuming Python 3 here, so if there's something neat that can be done with import hooks, go for it. ChrisA From khalidness at gmail.com Sun Nov 9 20:49:29 2014 From: khalidness at gmail.com (Syed Khalid) Date: Sun, 9 Nov 2014 17:49:29 -0800 (PST) Subject: Python script that does batch find and replace in txt files In-Reply-To: References: Message-ID: Albert, Code is not removing empty lines containing blank characters and not removing leading and trailing spaces present in each line. import glob, codecs, re, os regex = re.compile(r"Age: |Sex: |House No: ") # etc etc for txt in glob.glob("D:/Python/source/*.txt"): with codecs.open(txt, encoding="utf-8") as f: oldlines = f.readlines() for i, line in enumerate(oldlines): if "Elector's Name:" in line: break newlines = [regex.sub("", line).strip().replace("-", "_") for line in oldlines[i:]] with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: w.write(os.linesep.join(newlines)) Kindly do the needful From hayesstw at telkomsa.net Sun Nov 9 23:55:05 2014 From: hayesstw at telkomsa.net (Steve Hayes) Date: Mon, 10 Nov 2014 06:55:05 +0200 Subject: Python modules Message-ID: I have a book on Python that advocates dividing programs into modules, and importing them when needed. I have a question about this. I can understand doing that in a compiled language, where different modules can be imported from all sorts of places when the program is compiled. But I understand that Python is an interpreted language, and If I wrote a program in Python like that, and wanted to run it on another computer, how would it find all the modules to import at run-time, unless I copied the whole directory structure over to the other computer? -- Steve Hayes from Tshwane, South Africa Web: http://www.khanya.org.za/stevesig.htm Blog: http://khanya.wordpress.com E-mail - see web page, or parse: shayes at dunelm full stop org full stop uk From Deepfriedice at openmailbox.org Sun Nov 9 23:55:27 2014 From: Deepfriedice at openmailbox.org (Deepfriedice) Date: Mon, 10 Nov 2014 14:55:27 +1000 Subject: Python modules References: Message-ID: On 10/11/14 14:55, Steve Hayes wrote: > I have a book on Python that advocates dividing programs into modules, and > importing them when needed. > > I have a question about this. > > I can understand doing that in a compiled language, where different modules > can be imported from all sorts of places when the program is compiled. > > But I understand that Python is an interpreted language, and If I wrote a > program in Python like that, and wanted to run it on another computer, how > would it find all the modules to import at run-time, unless I copied the whole > directory structure over to the other computer? You copy over the directory structure, or wrap it in a compressed archive. From ben+python at benfinney.id.au Mon Nov 10 00:12:07 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 10 Nov 2014 16:12:07 +1100 Subject: Python modules References: Message-ID: <85egtbbpw8.fsf@benfinney.id.au> Steve Hayes writes: > I have a book on Python that advocates dividing programs into modules, > and importing them when needed. Which book is this? (This is not essential to your question, but it might help to gauge your broader learning environment.) > I can understand doing that in a compiled language, where different > modules can be imported from all sorts of places when the program is > compiled. Python is a compiled language; when you run a Python program a necessary step is to compile the Python source to a bytecode for actual execution. Usually, the compilation step is done dynamically; but (barring contrived examples) it is always done prior to running the program. > But I understand that Python is an interpreted language The two are not mutually exclusive. The Python interpreter works with compiled Python code, it does not execute the source directly. > If I wrote a program in Python like that, and wanted to run it on > another computer, how would it find all the modules to import at > run-time, unless I copied the whole directory structure over to the > other computer? That's the idea, yes. You need to distinguish between: * The standard library: installed along with the Python interpreter when you install that, and available on the default module search path. * Third-party modules: installed using your package manager (ideally by the operating system package manager), again to a location already part of the default module search path on your system. * Modules specific to the application you're writing: Keep these in a known hierarchy, and use the distribution tools to package them to keep them together when distributing to oher machines. Use abolute import for standard library and third-party modules. Use relative import for application-private modules. This ensures your aplication's private modules don't conflict with current or future names of modules from the standard library or third parties. You are working through the Python tutorial step by step, right? This topic is covered when you learn about modules . -- \ ?I am amazed, O Wall, that you have not collapsed and fallen, | `\ since you must bear the tedious stupidities of so many | _o__) scrawlers.? ?anonymous graffiti, Pompeii, 79 CE | Ben Finney From hayesstw at telkomsa.net Mon Nov 10 01:58:16 2014 From: hayesstw at telkomsa.net (Steve Hayes) Date: Mon, 10 Nov 2014 08:58:16 +0200 Subject: Python modules References: Message-ID: On Mon, 10 Nov 2014 16:12:07 +1100, Ben Finney wrote: >Steve Hayes writes: > >> I have a book on Python that advocates dividing programs into modules, >> and importing them when needed. > >Which book is this? (This is not essential to your question, but it >might help to gauge your broader learning environment.) Cunningham, Katie. 2014. Teach yourself Python in 24 hours. Indianapolis: Sams. ISBN: 978-0-672-33687-4 For Python 2.7.5 >> I can understand doing that in a compiled language, where different >> modules can be imported from all sorts of places when the program is >> compiled. > >Python is a compiled language; when you run a Python program a necessary >step is to compile the Python source to a bytecode for actual execution. > >Usually, the compilation step is done dynamically; but (barring >contrived examples) it is always done prior to running the program. > >> But I understand that Python is an interpreted language > >The two are not mutually exclusive. The Python interpreter works with >compiled Python code, it does not execute the source directly. > >> If I wrote a program in Python like that, and wanted to run it on >> another computer, how would it find all the modules to import at >> run-time, unless I copied the whole directory structure over to the >> other computer? > >That's the idea, yes. You need to distinguish between: > >* The standard library: installed along with the Python interpreter when > you install that, and available on the default module search path. > >* Third-party modules: installed using your package manager (ideally by > the operating system package manager), again to a location already > part of the default module search path on your system. > >* Modules specific to the application you're writing: Keep these in a > known hierarchy, and use the distribution tools to package them to > keep them together when distributing to oher machines. > >Use abolute import for standard library and third-party modules. Use >relative import for application-private modules. > >This ensures your aplication's private modules don't conflict with >current or future names of modules from the standard library or third >parties. So if I want to run it on another computer, where do I look for the compiled executable program to copy? -- Steve Hayes from Tshwane, South Africa Web: http://www.khanya.org.za/stevesig.htm Blog: http://khanya.wordpress.com E-mail - see web page, or parse: shayes at dunelm full stop org full stop uk From ben+python at benfinney.id.au Mon Nov 10 02:48:04 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 10 Nov 2014 18:48:04 +1100 Subject: Python modules References: Message-ID: <85a93zbiob.fsf@benfinney.id.au> Steve Hayes writes: > So if I want to run it on another computer, where do I look for the > compiled executable program to copy? You generally don't do that (the compiled files tend to be specific to various aspects of the target platform). This is a way that i's important to remember that most Python interpreters require compiled Python code. Instead, to have a Python program run on a different computer, the files to copy are the *source* files ? preferably, in the hierarchy those files expect. You can do this with ?rsync? for simple cases. For more complex cases, look into Python's distribution and packaging tools . For even more complex cases (e.g. where the Python code is only part of a more diverse code base), look into deployment systems and operating system packages. -- \ ?When we pray to God we must be seeking nothing ? nothing.? | `\ ?Francis of Assisi | _o__) | Ben Finney From fomcl at yahoo.com Mon Nov 10 04:22:03 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 10 Nov 2014 09:22:03 +0000 (UTC) Subject: locale.getlocale() in cmd.exe vs. Idle Message-ID: <37011265.138748.1415611323250.JavaMail.yahoo@jws10709.mail.gq1.yahoo.com> Hi, Why do I get different output for locale.getlocale() in Idle vs. cmd.exe? # IDLE Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import locale >>> locale.getdefaultlocale() ('nl_NL', 'cp1252') >>> locale.getlocale() ('Dutch_Netherlands', '1252') # I need this specific notation >>> # cmd.exe or Ipython C:\Users\albertjan>python Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import locale >>> locale.getdefaultlocale() ('nl_NL', 'cp1252') >>> locale.getlocale() (None, None) # using setlocale does work (one of these instances when I answer my own question while writing to the Python list) C:\Users\albertjan>python Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import locale >>> locale.setlocale(locale.LC_ALL, "") 'Dutch_Netherlands.1252' >>> locale.getlocale() ('Dutch_Netherlands', '1252') Thank you! Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From poalman at gmail.com Mon Nov 10 06:05:10 2014 From: poalman at gmail.com (Paul Wiseman) Date: Mon, 10 Nov 2014 11:05:10 +0000 Subject: ssl error with the python mac binary Message-ID: Hey, I've been using the latest mac ppc/i386 binaries from python.org (https://www.python.org/ftp/python/2.7.8/python-2.7.8-macosx10.5.dmg). >From what I can tell this version is linked against a pretty old version of OpenSSL (OpenSSL 0.9.7l 28 Sep 2006) which doesn't seem to be able to handle new sha-256 certificates. For example I'm unable to use pip (I guess the certificate was updated recently) Searching for gnureadline Reading https://pypi.python.org/simple/gnureadline/ Download error on https://pypi.python.org/simple/gnureadline/: [Errno 1] _ssl.c:510: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm -- Some packages may not be found! Am I right in thinking this is an issue with the build of python itself? Is there a way I can upgrade the version of OpenSSL linked with python- or force the python build to look elsewhere for the library? Or will I have to build my own from source? Thanks! Paul From annieford8 at gmail.com Mon Nov 10 05:55:30 2014 From: annieford8 at gmail.com (michel88) Date: Mon, 10 Nov 2014 02:55:30 -0800 (PST) Subject: Booksigning Party at PyCon This Year! In-Reply-To: <43E5D0F3.5060305@taupro.com> References: <43E5D0F3.5060305@taupro.com> Message-ID: <1415616930540-5077004.post@n6.nabble.com> My kids want to celebrate Halloween party at one of the best party venue. Can you please help us and recommend me best Halloween party nyc with good food supplies arrangements? -- View this message in context: http://python.6.x6.nabble.com/Booksigning-Party-at-PyCon-This-Year-tp935988p5077004.html Sent from the Python - python-list mailing list archive at Nabble.com. From mok-kong.shen at t-online.de Mon Nov 10 06:07:58 2014 From: mok-kong.shen at t-online.de (Mok-Kong Shen) Date: Mon, 10 Nov 2014 12:07:58 +0100 Subject: A syntax question Message-ID: I don't understand the following phenomenon. Could someone kindly explain it? Thanks in advance. M. K. Shen ------------------------------------------------- count=5 def test(): print(count) if count==5: count+=0 ### Error message if this line is active, otherwise ok. print(count) return test() From alister.nospam.ware at ntlworld.com Mon Nov 10 06:23:51 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Mon, 10 Nov 2014 11:23:51 GMT Subject: A syntax question References: Message-ID: On Mon, 10 Nov 2014 12:07:58 +0100, Mok-Kong Shen wrote: > I don't understand the following phenomenon. Could someone kindly > explain it? Thanks in advance. > > M. K. Shen > > ------------------------------------------------- > > count=5 > > def test(): > print(count) > if count==5: > count+=0 ### Error message if this line is active, otherwise ok. > print(count) > return > > test() My crystal ball is currently in for repair and is not expected back in the foreseeable future. What result are you getting that you don't understand & what do you expect? What is the error message you get? Post the full traceback -- The POP server is out of Coke From alister.nospam.ware at ntlworld.com Mon Nov 10 06:28:24 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Mon, 10 Nov 2014 11:28:24 GMT Subject: Python script that does batch find and replace in txt files References: Message-ID: On Sun, 09 Nov 2014 17:49:29 -0800, Syed Khalid wrote: > Albert, > > Code is not removing empty lines containing blank characters and not > removing leading and trailing spaces present in each line. > > > > > import glob, codecs, re, os > > regex = re.compile(r"Age: |Sex: |House No: ") # etc etc > > for txt in glob.glob("D:/Python/source/*.txt"): > with codecs.open(txt, encoding="utf-8") as f: > oldlines = f.readlines() > for i, line in enumerate(oldlines): > if "Elector's Name:" in line: > break > newlines = [regex.sub("", line).strip().replace("-", "_") for line > in oldlines[i:]] > with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: > w.write(os.linesep.join(newlines)) > > Kindly do the needful kindly read the code to understand how it is operating & then make the necessary changes/additions yourself comp.lang.python is no a free coding shop -- Nobody ever ruined their eyesight by looking at the bright side of something. From dpalao.python at gmail.com Mon Nov 10 06:31:05 2014 From: dpalao.python at gmail.com (David Palao) Date: Mon, 10 Nov 2014 12:31:05 +0100 Subject: A syntax question In-Reply-To: References: Message-ID: > My crystal ball is currently in for repair and is not expected back in > the foreseeable future. Without a crystal ball, this prediction might be not well founded. From wolfgang.maier at biologie.uni-freiburg.de Mon Nov 10 06:39:17 2014 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Mon, 10 Nov 2014 12:39:17 +0100 Subject: A syntax question In-Reply-To: References: Message-ID: You may want to read: https://docs.python.org/3/faq/programming.html?highlight=global#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value from the Python docs Programming FAQ section. It explains your problem pretty well. As others have hinted at, always provide concrete Python error messages and tracebacks instead of vague descriptions. Best, Wolfgang On 11/10/2014 12:07 PM, Mok-Kong Shen wrote: > > I don't understand the following phenomenon. Could someone kindly > explain it? Thanks in advance. > > M. K. Shen > > ------------------------------------------------- > > count=5 > > def test(): > print(count) > if count==5: > count+=0 ### Error message if this line is active, otherwise ok. > print(count) > return > > test() From roy at panix.com Mon Nov 10 08:36:54 2014 From: roy at panix.com (Roy Smith) Date: Mon, 10 Nov 2014 08:36:54 -0500 Subject: Python modules References: Message-ID: In article , Steve Hayes wrote: > I have a book on Python that advocates dividing programs into modules, and > importing them when needed. Yes, this is a good idea. Breaking your program down into modules, each of which does a small set of closely related things, makes it easier to manage. You can test each module in isolation. When you look at your version control log, you can see just the changes which apply to just that module. When somebody new joins the team, they can learn about each module one at a time. None of this is specific to Python. Good software engineering practice is to break large applications into manageable pieces. The vocabulary may change from language to language (module, package, class, library, dll, etc), but the basic concept is the same. > But I understand that Python is an interpreted language, and If I wrote a > program in Python like that, and wanted to run it on another computer, how > would it find all the modules to import at run-time, unless I copied the whole > directory structure over to the other computer? Yes, exactly. When you deploy your application someplace, you need to include all the things it depends on. In the simple case of a few python files (say, a main program and a few modules that you're written), the easiest thing to do might be to just clone your source repository on the other machine and run it directly from that. Another possibility would be to package up all the files in some sort of archive (tar, zip, whatever) and unpack that wherever you need it. You will also have to set up a correct environment. This usually means having an appropriate version of Python already installed, plus whatever third-party modules you use. From rosuav at gmail.com Mon Nov 10 08:49:11 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Nov 2014 00:49:11 +1100 Subject: Python modules In-Reply-To: References: Message-ID: On Tue, Nov 11, 2014 at 12:36 AM, Roy Smith wrote: > Yes, exactly. When you deploy your application someplace, you need to > include all the things it depends on. In the simple case of a few > python files (say, a main program and a few modules that you're > written), the easiest thing to do might be to just clone your source > repository on the other machine and run it directly from that. Even in less simple cases, that's often a good way to run things. As long as your source repo has no large binary files in it, it'll be reasonably small; for 400KB of source code and ~1600 commits spanning ~3 years of history, around about 2MB. When your deployment is a source clone, it's really easy to pull changes and see what's new; and if you ever find a bug on a deployment machine (maybe a different OS from your usual dev system), you can make a patch right there and send it along. There's no huge "okay, let's make a new release now" overhead - you just keep committing (maybe pushing) changes, same as you do any other time, and perhaps tag some commit with a version number. Very very easy. I recommend it. ChrisA From joel.goldstick at gmail.com Mon Nov 10 09:35:47 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 10 Nov 2014 09:35:47 -0500 Subject: A syntax question In-Reply-To: References: Message-ID: On Mon, Nov 10, 2014 at 6:39 AM, Wolfgang Maier wrote: > You may want to read: > > https://docs.python.org/3/faq/programming.html?highlight=global#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value > > from the Python docs Programming FAQ section. > It explains your problem pretty well. > > As others have hinted at, always provide concrete Python error messages and > tracebacks instead of vague descriptions. > > Best, > Wolfgang > > > > On 11/10/2014 12:07 PM, Mok-Kong Shen wrote: >> >> >> I don't understand the following phenomenon. Could someone kindly >> explain it? Thanks in advance. >> >> M. K. Shen >> >> ------------------------------------------------- >> >> count=5 >> >> def test(): >> print(count) >> if count==5: >> count+=0 ### Error message if this line is active, otherwise ok. >> print(count) >> return >> >> test() > > > -- > https://mail.python.org/mailman/listinfo/python-list Your problem is that count is not local. You are reading count from an outer scope. When you try to increment count in your function, it can't because it doesn't exist. Don't use globals. -- Joel Goldstick http://joelgoldstick.com From invalid at invalid.invalid Mon Nov 10 09:44:53 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 10 Nov 2014 14:44:53 +0000 (UTC) Subject: A syntax question References: Message-ID: On 2014-11-10, David Palao wrote: >> My crystal ball is currently in for repair and is not expected back >> in the foreseeable future. > > Without a crystal ball, this prediction might be not well founded. That isn't a prediction. It's an explicit statement of no prediction. He said that it is "not expected back" rather than "expected not to be back". They're two different things. The former asserts a _lack_ of expection/prediction. The latter asserts an expectation/prediction. -- Grant Edwards grant.b.edwards Yow! Am I in Milwaukee? at gmail.com From rosuav at gmail.com Mon Nov 10 09:54:02 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Nov 2014 01:54:02 +1100 Subject: A syntax question In-Reply-To: References: Message-ID: On Tue, Nov 11, 2014 at 1:35 AM, Joel Goldstick wrote: > Your problem is that count is not local. You are reading count from > an outer scope. When you try to increment count in your function, it > can't because it doesn't exist. > Don't use globals. False analysis, I'm afraid. The problem is that the assignment will, in the absence of a "global" declaration, cause the name "count" to indicate a local variable - so it won't ever be read from outer scope. However, the OP's issue is better solved by sharing tracebacks than by us peering into crystal balls; mine's showing a very clear image at the moment, but it might well be incorrect. ChrisA From alister.nospam.ware at ntlworld.com Mon Nov 10 09:54:55 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Mon, 10 Nov 2014 14:54:55 GMT Subject: A syntax question References: Message-ID: <3l48w.682048$9R5.402039@fx29.am4> On Mon, 10 Nov 2014 14:44:53 +0000, Grant Edwards wrote: > On 2014-11-10, David Palao wrote: > >>> My crystal ball is currently in for repair and is not expected back in >>> the foreseeable future. >> >> Without a crystal ball, this prediction might be not well founded. > > That isn't a prediction. It's an explicit statement of no prediction. > He said that it is "not expected back" rather than "expected not to be > back". They're two different things. The former asserts a _lack_ of > expection/prediction. The latter asserts an expectation/prediction. It was only a a joke maybe it was a bit to subtle -- A light wife doth make a heavy husband. -- Wm. Shakespeare, "The Merchant of Venice" From alister.nospam.ware at ntlworld.com Mon Nov 10 09:56:11 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Mon, 10 Nov 2014 14:56:11 GMT Subject: A syntax question References: <3l48w.682048$9R5.402039@fx29.am4> Message-ID: On Mon, 10 Nov 2014 14:54:55 +0000, alister wrote: > On Mon, 10 Nov 2014 14:44:53 +0000, Grant Edwards wrote: > >> On 2014-11-10, David Palao wrote: >> >>>> My crystal ball is currently in for repair and is not expected back >>>> in the foreseeable future. >>> >>> Without a crystal ball, this prediction might be not well founded. >> >> That isn't a prediction. It's an explicit statement of no prediction. >> He said that it is "not expected back" rather than "expected not to be >> back". They're two different things. The former asserts a _lack_ of >> expection/prediction. The latter asserts an expectation/prediction. > > It was only a a joke maybe it was a bit to subtle I didn't expect the Spanish inquisition (Damn wish Id though of that before sending the last post) -- One picture is worth more than ten thousand words. -- Chinese proverb From __peter__ at web.de Mon Nov 10 10:10:17 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 Nov 2014 16:10:17 +0100 Subject: A syntax question References: Message-ID: Joel Goldstick wrote: > On Mon, Nov 10, 2014 at 6:39 AM, Wolfgang Maier > wrote: >> You may want to read: >> >> https://docs.python.org/3/faq/programming.html?highlight=global#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value >> >> from the Python docs Programming FAQ section. >> It explains your problem pretty well. >> >> As others have hinted at, always provide concrete Python error messages >> and tracebacks instead of vague descriptions. >> >> Best, >> Wolfgang >> >> >> >> On 11/10/2014 12:07 PM, Mok-Kong Shen wrote: >>> >>> >>> I don't understand the following phenomenon. Could someone kindly >>> explain it? Thanks in advance. >>> >>> M. K. Shen >>> >>> ------------------------------------------------- >>> >>> count=5 >>> >>> def test(): >>> print(count) >>> if count==5: >>> count+=0 ### Error message if this line is active, otherwise ok. >>> print(count) >>> return >>> >>> test() >> >> >> -- >> https://mail.python.org/mailman/listinfo/python-list > > Your problem is that count is not local. You are reading count from > an outer scope. When you try to increment count in your function, it > can't because it doesn't exist. > Don't use globals. That's what most would expect, but the error is already triggered by the first print(count) Python decides at compile-time that count is a local variable if there is an assignment ("name binding") to count anywhere in the function's scope -- even if the corresponding code will never be executed: >>> x = 42 >>> def test(): ... print(x) ... if 0: x = 42 ... >>> test() Traceback (most recent call last): File "", line 1, in File "", line 2, in test UnboundLocalError: local variable 'x' referenced before assignment This is different from the class body where the global namespace is tried when a lookup in the local namespace fails: >>> x = 42 >>> class A: ... print(x) ... x += 1 ... 42 >>> x 42 >>> A.x 43 Historical ;) note: In Python 2 you could trigger a similar behaviour with exec: >>> def f(a): ... if a: exec "x = 42" ... print x ... >>> x = "global" >>> f(True) 42 >>> f(False) global From joel.goldstick at gmail.com Mon Nov 10 10:27:29 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 10 Nov 2014 10:27:29 -0500 Subject: A syntax question In-Reply-To: References: Message-ID: On Mon, Nov 10, 2014 at 9:54 AM, Chris Angelico wrote: > On Tue, Nov 11, 2014 at 1:35 AM, Joel Goldstick > wrote: >> Your problem is that count is not local. You are reading count from >> an outer scope. When you try to increment count in your function, it >> can't because it doesn't exist. >> Don't use globals. > > False analysis, I'm afraid. The problem is that the assignment will, > in the absence of a "global" declaration, cause the name "count" to > indicate a local variable - so it won't ever be read from outer scope. > However, the OP's issue is better solved by sharing tracebacks than by > us peering into crystal balls; mine's showing a very clear image at > the moment, but it might well be incorrect. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list Interesting. Thanks for pointing that out -- Joel Goldstick http://joelgoldstick.com From invalid at invalid.invalid Mon Nov 10 11:11:22 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 10 Nov 2014 16:11:22 +0000 (UTC) Subject: A syntax question References: <3l48w.682048$9R5.402039@fx29.am4> Message-ID: On 2014-11-10, alister wrote: > On Mon, 10 Nov 2014 14:44:53 +0000, Grant Edwards wrote: > >> On 2014-11-10, David Palao wrote: >> >>>> My crystal ball is currently in for repair and is not expected back in >>>> the foreseeable future. >>> >>> Without a crystal ball, this prediction might be not well founded. >> >> That isn't a prediction. It's an explicit statement of no prediction. >> He said that it is "not expected back" rather than "expected not to be >> back". They're two different things. The former asserts a _lack_ of >> expection/prediction. The latter asserts an expectation/prediction. > > It was only a a joke maybe it was a bit to subtle I know, but in c.l.p, even jokes get nicely pednatic answers. ;) -- Grant Edwards grant.b.edwards Yow! The FALAFEL SANDWICH at lands on my HEAD and I gmail.com become a VEGETARIAN ... From rosuav at gmail.com Mon Nov 10 11:18:15 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Nov 2014 03:18:15 +1100 Subject: A syntax question In-Reply-To: References: <3l48w.682048$9R5.402039@fx29.am4> Message-ID: On Tue, Nov 11, 2014 at 3:11 AM, Grant Edwards wrote: > I know, but in c.l.p, even jokes get nicely pednatic answers. And in c.l.p, odd jokes get even more pedantic spelling corrections. ChrisA From Steve.Dower at microsoft.com Mon Nov 10 11:35:01 2014 From: Steve.Dower at microsoft.com (Steve Dower) Date: Mon, 10 Nov 2014 16:35:01 +0000 Subject: [Distutils] Call for information - What assumptions can I make about Unix users' access to Windows? In-Reply-To: <85sihu52lg.fsf@benfinney.id.au> References: <851tpf54y5.fsf@benfinney.id.au> <5d041f9c5799466da8037b3d33be7959@DM2PR0301MB0734.namprd03.prod.outlook.com> <85sihu52lg.fsf@benfinney.id.au> Message-ID: <638dcdc4d36b44ef8d1f68d23c83a875@DM2PR0301MB0734.namprd03.prod.outlook.com> Ben Finney wrote: > Steve Dower writes: >> Ben Finney wrote: >> > The restrictions of the license terms make MS Windows an >> > unacceptable risk on any machine I'm responsible for. >> >> Just out of interest, which restrictions would those be? > > It has been a long time since I bothered to read any of the numerous license > texts from Microsoft, so I can't cite specific clauses. From memory, > unacceptable restrictions include: > > * Restricting the instance to specific hardware, instead of leaving it > up to the recipient to run the work they paid for on any hardware they > choose. If by "specific hardware" you mean the one-license-per-user-per-machine rule, you probably want to consider Windows Server, which has a more flexible license in this respect (or maybe not - it might just allow multiple users on one license/machine. I haven't checked this). > * Forbidding reverse-engineering of the OS to see how it behaves. Yeah, I doubt that restriction is moving anywhere. It's standard for closed-source software, and as I understand it's intended to legally protect trade secrets and patents (i.e. "we tried our hardest to keep this a trade secret"). I've never heard of anyone being pursued for doing it though, except to be offered a job working on Windows :) > * Forbidding collaboration with other recipients to discover how the OS > behaves. "Other recipients" are explicitly excluded - "for use by one person at a time"[1] - so the rest of this point doesn't really make any sense to me. That said, it does trigger some memories of when I was contributing to ReactOS years ago... is this one of their suggestions about how to avoid taint? (Or maybe from Wine?) Those guys have obtained their own legal advice which is going to be aimed at preventing a court case (not just preventing a loss - preventing it from happening in the first place) and so it's going to be based on an interpretation of the license and be more defensive than most people need to worry about. > * Refusal to disclose the source code for the running OS to the > recipient. Again, it's part of the business and legal model. If you really want access to the source code, you can pay for it, but most people and businesses can't afford it or don't want it that badly. (There are also technical reasons why the source code can't easily be disclosed - how many hundreds of gigabytes of code are you willing to download and wade through? Yes, it's that big.) > * Forbidding the recipient from getting their choice of vendor to make > improvements to the OS and collaborate with other recipients on the > improvements. I know this used to exist, as there were a number of RT/embedded OSs available that were based on Windows. I think at this point they've all been absorbed into Microsoft though. > * Arrogating control of the running OS to a party other than the license > recipient, including the ability to (at Microsoft's sole discretion) > deny applications to run, and to disable features of the OS. > > * Arrogating data collection to Microsoft and undisclosed third parties, > tracking broad classes of activity on the OS and sending the logs to a > server not of the recipient's choosing. It seems you fundamentally disagree with the 'licensing' model and would prefer an 'ownership' model. That's fine, but it's not the business model Windows operates under and that is unlikely to ever change. Even if I were CEO, I'd have a hard time changing that one :) >> Does this prevent you from creating a VM on a cloud provider on your >> own account? > > If I need to accept restrictions such as the above, I don't see that the > location of the instance (nor the fees charged) has any affect on these > concerns. The risks discussed above are not mitigated. > >> If the licensing is a real issue, I'm in a position where I can have a >> positive impact on fixing it, so any info you can provide me (on- or >> off-list) about your concerns is valuable. > > Thank you for this offer, I am glad to see willingness expressed to solve these > restrictions. I hope you can achieve software freedom for all recipients of > Microsoft operating systems. > > Until then, the risk is too great to anyone to whom I have professional > responsibilities, and my advice must continue to be that they avoid accepting > such restrictions. That's a fair enough position, and without people taking that stance, Linux (and practically every OS that's based on it) wouldn't be anywhere near as usable as it is today. I'm also fully aware of people with the exact opposite stance who give the exact opposite advice, so there's room in this world for all of us. I'm sorry I can't do any better than the few responses above - these are big issues that run to the core of how Microsoft does business, and not only am I incapable of changing them, I'm nowhere near capable of fully understanding how it all fits together. Thanks for being willing to engage, though. It's always valuable to hear alternative points of view and get a better feeling for how the things we do here are perceived. Rest assured, I will continue to push for as many of our products to be free OSS as I can (we've already put out many developer products under Apache 2.0 or MIT), but it's slow progress and Windows will likely be the last one to make the switch. Cheers, Steve 1: http://download.microsoft.com/Documents/UseTerms/Windows_8_English_ca383862-45cf-467e-97d3-386e0e0260a6.pdf From giacomo_boffi at inwind.it Mon Nov 10 11:48:25 2014 From: giacomo_boffi at inwind.it (giacomo boffi) Date: Mon, 10 Nov 2014 17:48:25 +0100 Subject: What does zip mean? References: Message-ID: On 11/09/2014 11:44 AM, satishmlmlml at gmail.com wrote: > What does zip return in the following piece of code? To help you understanding what is the `zip` builtin, please forget about PKZip etc and think about the _zip fastener_ or _zipper_ in your bag or in your trousers In the bag you have two sequences of teeth that the zipper binds together in interlocking pairs In your program you have two lists, whose elements `zip` returns bound together in pairs From invalid at invalid.invalid Mon Nov 10 12:19:31 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 10 Nov 2014 17:19:31 +0000 (UTC) Subject: What does zip mean? References: Message-ID: On 2014-11-10, giacomo boffi wrote: > On 11/09/2014 11:44 AM, satishmlmlml at gmail.com wrote: >> What does zip return in the following piece of code? > > To help you understanding what is the `zip` builtin, please forget > about PKZip etc and think about the _zip fastener_ or _zipper_ in > your bag or in your trousers > > In the bag you have two sequences of teeth that the zipper > binds together in interlocking pairs No, you don't. That's not how a zipper works. Each tooth from side A, isn't bound with one from side B. It's bound with _two_ of them from side B. And each of those is in turn bound with an additional tooth from side A, and so on... > In your program you have two lists, whose elements `zip` returns > bound together in pairs What the zipper on a coat does is convert two separate sequences into a single sequence where the members alternate between the two input sequences. IOW if we want to do something analogous to a zipper fastener it should do this: zip([a,b,c,d,e,f],[1,2,3,4,5,6]) => [a,1,b,2,c,3,d,4,e,5,f,6] Item '1' is bound equally to item 'a' and 'b'. Item 'b' is bound equally to item '1' and '2'. -- Grant Edwards grant.b.edwards Yow! I joined scientology at at a garage sale!! gmail.com From paddy3118 at gmail.com Mon Nov 10 13:45:00 2014 From: paddy3118 at gmail.com (Paddy) Date: Mon, 10 Nov 2014 10:45:00 -0800 (PST) Subject: "Natural" use of cmp= in sort Message-ID: Hi, I do agree with Raymond H. about the relative merits of cmp= and key= in sort/sorted, but I decided to also not let natural uses of cmp= pass silently. In answering this question, http://stackoverflow.com/a/26850434/10562 about ordering subject to inequalities it seemed natural to use the cmp= argument of sort rather than key=. The question is about merging given inequalities to make 1 inequality such that the inequalities also stays true. Here is a copy of my code: Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ineq = """f4 > f2 > f3 f4 > f1 > f3 f4 > f2 > f1 f2 > f1 > f3""" >>> print(ineq) f4 > f2 > f3 f4 > f1 > f3 f4 > f2 > f1 f2 > f1 > f3 >>> greater_thans, all_f = set(), set() >>> for line in ineq.split('\n'): ....tokens = line.strip().split()[::2] ....for n, t1 in enumerate(tokens[:-1]): ........for t2 in tokens[n+1:]: ............greater_thans.add((t1, t2)) ............all_f.add(t1) ........all_f.add(t2) >>> sorted(all_f, cmp=lambda t1, t2: 0 if t1==t2 else ...........(1 if (t1, t2) not in greater_thans else -1)) ['f4', 'f2', 'f1', 'f3'] >>> From sohcahtoa82 at gmail.com Mon Nov 10 13:56:18 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Mon, 10 Nov 2014 10:56:18 -0800 (PST) Subject: I don't read docs and don't know how to use Google. What does the print function do? Message-ID: Please help me this assignment is due in an hour. Don't give me hints, just give me the answer because I only want a grade. I'm not actually interested in learning how to program, but I know software engineers make lots of money so I want to be one. From __peter__ at web.de Mon Nov 10 14:19:46 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 Nov 2014 20:19:46 +0100 Subject: "Natural" use of cmp= in sort References: Message-ID: Paddy wrote: > Hi, I do agree with > Raymond H. about the relative merits of cmp= and key= in > sort/sorted, but I decided to also not let natural uses of cmp= pass > silently. > > In answering this question, http://stackoverflow.com/a/26850434/10562 > about ordering subject to inequalities it seemed natural to use the cmp= > argument of sort rather than key=. > > The question is about merging given inequalities to make 1 inequality such > that the inequalities also stays true. > > > Here is a copy of my code: > > Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] > on win32 Type "copyright", "credits" or "license()" for more information. >>>> ineq = """f4 > f2 > f3 > f4 > f1 > f3 > f4 > f2 > f1 > f2 > f1 > f3""" >>>> print(ineq) > f4 > f2 > f3 > f4 > f1 > f3 > f4 > f2 > f1 > f2 > f1 > f3 >>>> greater_thans, all_f = set(), set() >>>> for line in ineq.split('\n'): > ....tokens = line.strip().split()[::2] > ....for n, t1 in enumerate(tokens[:-1]): > ........for t2 in tokens[n+1:]: > ............greater_thans.add((t1, t2)) > ............all_f.add(t1) > ........all_f.add(t2) > > >>>> sorted(all_f, cmp=lambda t1, t2: 0 if t1==t2 else > ...........(1 if (t1, t2) not in greater_thans else -1)) > ['f4', 'f2', 'f1', 'f3'] >>>> I'm not sure this works. I tried: $ cat paddy.py ineq = """f4 > f2 > f3 f4 > f1 > f3 f4 > f2 > f1 f2 > f1 > f3 f3 > f5 """ greater_thans = set() all_f = set() for line in ineq.split('\n'): tokens = line.strip().split()[::2] for n, t1 in enumerate(tokens[:-1]): for t2 in tokens[n+1:]: greater_thans.add((t1, t2)) all_f.add(t1) all_f.add(t2) print all_f print greater_thans print sorted(all_f, cmp=lambda t1, t2: 0 if t1==t2 else (1 if (t1, t2) not in greater_thans else -1)) $ PYTHONHASHSEED=0 python paddy.py set(['f1', 'f2', 'f3', 'f4', 'f5']) set([('f1', 'f3'), ('f2', 'f1'), ('f2', 'f3'), ('f4', 'f3'), ('f4', 'f2'), ('f4', 'f1'), ('f3', 'f5')]) ['f4', 'f2', 'f1', 'f3', 'f5'] $ PYTHONHASHSEED=1 python paddy.py set(['f5', 'f4', 'f3', 'f2', 'f1']) set([('f1', 'f3'), ('f2', 'f3'), ('f2', 'f1'), ('f4', 'f1'), ('f3', 'f5'), ('f4', 'f3'), ('f4', 'f2')]) ['f5', 'f4', 'f2', 'f1', 'f3'] From __peter__ at web.de Mon Nov 10 14:24:18 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 Nov 2014 20:24:18 +0100 Subject: I don't read docs and don't know how to use Google. What does the print function do? References: Message-ID: sohcahtoa82 at gmail.com wrote: > Please help me this assignment is due in an hour. Don't give me hints, > just give me the answer because I only want a grade. I'm not actually > interested in learning how to program, but I know software engineers make > lots of money so I want to be one. I'm sorry I have to decline your kind offer unless you also let me do your dishes and walk your dog. From ian.g.kelly at gmail.com Mon Nov 10 14:43:39 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 10 Nov 2014 12:43:39 -0700 Subject: "Natural" use of cmp= in sort In-Reply-To: References: Message-ID: On Mon, Nov 10, 2014 at 12:19 PM, Peter Otten <__peter__ at web.de> wrote: > I'm not sure this works. I tried: Here's a simpler failure case. >>> ineq = """f2 > f3 ... f3 > f1""" [Previously posted code elided] >>> greater_thans set([('f3', 'f1'), ('f2', 'f3')]) >>> sorted(all_f, cmp=lambda t1, t2: 0 if t1==t2 else ... (1 if (t1, t2) not in greater_thans else -1)) ['f1', 'f2', 'f3'] Note that the greater_thans set is missing the implication by transitivity that f2 > f1, so the given cmp function would inconsistently return -1 for both comparisons cmp('f1', 'f2') and cmp('f2', 'f1'). From roy at panix.com Mon Nov 10 14:48:12 2014 From: roy at panix.com (Roy Smith) Date: Mon, 10 Nov 2014 14:48:12 -0500 Subject: A syntax question References: <3l48w.682048$9R5.402039@fx29.am4> Message-ID: In article , Chris Angelico wrote: > On Tue, Nov 11, 2014 at 3:11 AM, Grant Edwards > wrote: > > I know, but in c.l.p, even jokes get nicely pednatic answers. > > And in c.l.p, odd jokes get even more pedantic spelling corrections. > > ChrisA a n d i m a g i n a r y j o k e s g e t r o t a t e d From roy at panix.com Mon Nov 10 14:49:37 2014 From: roy at panix.com (Roy Smith) Date: Mon, 10 Nov 2014 14:49:37 -0500 Subject: I don't read docs and don't know how to use Google. What does the print function do? References: Message-ID: In article , sohcahtoa82 at gmail.com wrote: > Please help me this assignment is due in an hour. Don't give me hints, just > give me the answer because I only want a grade. I'm not actually interested > in learning how to program, but I know software engineers make lots of money > so I want to be one. This post is a sine of the times. From Charles at CharlesWeitzer.com Mon Nov 10 14:55:45 2014 From: Charles at CharlesWeitzer.com (Charles Weitzer) Date: Mon, 10 Nov 2014 11:55:45 -0800 Subject: Design and Build Software Engineer Opportunity Message-ID: <002d01cffd20$51a43310$f4ec9930$@CharlesWeitzer.com> My name is Charles Weitzer. I do recruiting for machine learning teams worldwide. One of my clients is a startup quantitative hedge fund located in Northern, California. The founders previous worked together at one of the most successful quantitative hedge funds in the world in New York City. Now they are ready to do it again. The team would like to hire an extremely talented design and build software engineer as soon as possible.. They are rebuilding their current trading strategy and system and also designing a new strategy. You could work on either or both. The title and level of seniority are very flexible. Their team has made unpublished discoveries in the field of machine learning and in other areas as well. This is an opportunity to leverage these discoveries in a real world environment. Here is their description of the position: ********************************************************** Design and Build Software Engineer Fast-growing quantitative trading firm seeks an exceptional software engineer. You will design and build new production trading systems, machine learning infrastructure, data integration pipelines, and large-scale storage systems. We seek a candidate with a proven track record of building correct, well-designed software, solving hard problems, and delivering complex projects on time. You should preferably have experience designing and implementing fault-tolerant distributed systems. Experience with building large-scale data infrastructure, stream processing systems, or latency-sensitive programs is a bonus. We are getting big fast. Willingness to take initiative, and a gritty determination to productize, are essential. Join a team that includes faculty at premier universities and PhD's from top-tier schools, led by the founder and CEO of a successful Internet infrastructure startup. You will have a high impact, and you can expect frequent interaction with the researchers, officers, and founders. Compensation and benefits are highly competitive. Qualifications: * Experience developing with C/C++/Python/Go in a Linux environment with a focus on performance, concurrency, and correctness. * Experience working in TCP/IP networking, multithreading and server development. * Experience working with common Internet protocols (IP, TCP/UDP, SSL/TLS, HTTP, SNMP, etc.) * Experience architecting and designing highly-available critical systems. * Experience architecting and designing large-scale data management infrastructure. * Experience working in large codebases and building modular, manageable code. Useful Skills: * Experience with debugging and performance profiling, including the use of tools such as strace, valgrind, gdb, tcpdump, etc. * Experience with build and test automation tools. * Experience working with well-defined change management processes. * Has experience hunting down RDBMS performance problems, understands indexing options, can read an execution/explain plan, has some experience with ORM and optimization at the code layer, etc. * Experience with messaging queues (such as RabbitMQ and Redis), as well as distributed caching systems. ********************************************************** This group is currently managing a very healthy amount of capital. And their job description above is really just a starting point in terms of possible responsibilities and seniority. They can be very flexible for the right person. If you are interested, let me know the best way to get in touch and we can discuss details. Talk soon, Charles Weitzer CEO\Senior Recruiter Charles Weitzer and Associates, Inc. Global Financial Recruiting Services Charles at CharlesWeitzer.com Voice: USA (510) 558-9182 From larry.martell at gmail.com Mon Nov 10 14:59:19 2014 From: larry.martell at gmail.com (Larry Martell) Date: Mon, 10 Nov 2014 14:59:19 -0500 Subject: I don't read docs and don't know how to use Google. What does the print function do? In-Reply-To: References: Message-ID: On Mon, Nov 10, 2014 at 2:49 PM, Roy Smith wrote: > In article , > sohcahtoa82 at gmail.com wrote: > >> Please help me this assignment is due in an hour. Don't give me hints, just >> give me the answer because I only want a grade. I'm not actually interested >> in learning how to program, but I know software engineers make lots of money >> so I want to be one. > > This post is a sine of the times. Don't go off on a tangent. From breamoreboy at yahoo.co.uk Mon Nov 10 15:04:31 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 10 Nov 2014 20:04:31 +0000 Subject: I don't read docs and don't know how to use Google. What does the print function do? In-Reply-To: References: Message-ID: On 10/11/2014 19:24, Peter Otten wrote: > sohcahtoa82 at gmail.com wrote: > >> Please help me this assignment is due in an hour. Don't give me hints, >> just give me the answer because I only want a grade. I'm not actually >> interested in learning how to program, but I know software engineers make >> lots of money so I want to be one. > > I'm sorry I have to decline your kind offer unless you also let me do your > dishes and walk your dog. > Quote Of The Day/Week/Month/Year/Decade/Millenium* * please delete whichever you feel is appropriate -- 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 Mon Nov 10 15:08:28 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 10 Nov 2014 20:08:28 +0000 Subject: A syntax question In-Reply-To: References: Message-ID: On 10/11/2014 11:31, David Palao wrote: >> My crystal ball is currently in for repair and is not expected back in >> the foreseeable future. > > Without a crystal ball, this prediction might be not well founded. > Especially in the future when sombody asks "Who the hell was he replying to?". -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From ethan at stoneleaf.us Mon Nov 10 15:16:45 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 10 Nov 2014 12:16:45 -0800 Subject: I don't read docs and don't know how to use Google. What does the print function do? In-Reply-To: References: Message-ID: <54611D2D.8030007@stoneleaf.us> On 11/10/2014 11:59 AM, Larry Martell wrote: > On Mon, Nov 10, 2014 at 2:49 PM, Roy Smith wrote: >> In article , >> sohcahtoa82 at gmail.com wrote: >> >>> Please help me this assignment is due in an hour. Don't give me hints, just >>> give me the answer because I only want a grade. I'm not actually interested >>> in learning how to program, but I know software engineers make lots of money >>> so I want to be one. >> >> This post is a sine of the times. > > Don't go off on a tangent. Please! We don't need all this hyperbole! -- ~Ethan~ From python.list at tim.thechases.com Mon Nov 10 15:29:40 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 10 Nov 2014 14:29:40 -0600 Subject: A syntax question In-Reply-To: References: Message-ID: <20141110142940.4a130b9f@bigbox.christie.dr> On 2014-11-10 20:08, Mark Lawrence wrote: > On 10/11/2014 11:31, David Palao wrote: > >> My crystal ball is currently in for repair and is not expected > >> back in the foreseeable future. > > > > Without a crystal ball, this prediction might be not well founded. > > > > Especially in the future when sombody asks "Who the hell was he > replying to?". That might be a concern if the mail.python.org archive failed, and all usenet archives fell offline. Since the threading wasn't broken, it's a simple matter of looking at the previous message in the thread, as referenced in the appropriate headers: In-Reply-To: References: where that particular message can be found. Any competent mailer or news client should handle threading without the user even thinking about it. It might also be more of a concern if there was actual question/answer content rather than just a little throw-away humor. -tkc From tjreedy at udel.edu Mon Nov 10 15:31:34 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 Nov 2014 15:31:34 -0500 Subject: locale.getlocale() in cmd.exe vs. Idle In-Reply-To: <37011265.138748.1415611323250.JavaMail.yahoo@jws10709.mail.gq1.yahoo.com> References: <37011265.138748.1415611323250.JavaMail.yahoo@jws10709.mail.gq1.yahoo.com> Message-ID: On 11/10/2014 4:22 AM, Albert-Jan Roskam wrote: > Hi, > > Why do I get different output for locale.getlocale() in Idle vs. cmd.exe? > > # IDLE > Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license()" for more information. >>>> import locale >>>> locale.getdefaultlocale() > ('nl_NL', 'cp1252') >>>> locale.getlocale() > ('Dutch_Netherlands', '1252') # I need this specific notation >>>> > > # cmd.exe or Ipython > C:\Users\albertjan>python > Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import locale >>>> locale.getdefaultlocale() > ('nl_NL', 'cp1252') >>>> locale.getlocale() > (None, None) > > # using setlocale does work (one of these instances when I answer my own question while writing to the Python list) > C:\Users\albertjan>python > Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import locale >>>> locale.setlocale(locale.LC_ALL, "") > 'Dutch_Netherlands.1252' >>>> locale.getlocale() > ('Dutch_Netherlands', '1252') Idle runs code in an environment that is slightly altered from the standard python startup environment'. idlelib.IOBinding has this ''' # Try setting the locale, so that we can find out # what encoding to use try: import locale locale.setlocale(locale.LC_CTYPE, "") ''' idlelib.run, which runs in the user-code subprocess, imports IOBinding. Setting LC_CTYPE is sufficient for getlocale() to not return null values. C:\Users\Terry>python -c "import locale; print(locale.getlocale())" (None, None) C:\Users\Terry>python -c "import locale; locale.setlocale(locale.LC_CTYPE, ''); print(locale.getlocale())" ('English_United States', '1252') -- Terry Jan Reedy From invalid at invalid.invalid Mon Nov 10 16:00:50 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 10 Nov 2014 21:00:50 +0000 (UTC) Subject: I don't read docs and don't know how to use Google. What does the print function do? References: Message-ID: On 2014-11-10, sohcahtoa82 at gmail.com wrote: > Please help me this assignment is due in an hour. Don't give me > hints, just give me the answer because I only want a grade. I'm not > actually interested in learning how to program, but I know software > engineers make lots of money so I want to be one. That's the saddest troll I've seen in ages. -- Grant Edwards grant.b.edwards Yow! I just forgot my whole at philosophy of life!!! gmail.com From greg.ewing at canterbury.ac.nz Mon Nov 10 16:04:30 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 11 Nov 2014 10:04:30 +1300 Subject: What does zip mean? In-Reply-To: References: Message-ID: Grant Edwards wrote: > What the zipper on a coat does is convert two separate sequences into > a single sequence where the members alternate between the two input > sequences. True, the zipper analogy isn't quite accurate. It's hard to think of an equally concise and suggestive name, however. -- Greg From cs at zip.com.au Mon Nov 10 15:36:01 2014 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 11 Nov 2014 07:36:01 +1100 Subject: What does zip mean? In-Reply-To: References: Message-ID: <20141110203601.GA69721@cskk.homeip.net> On 10Nov2014 17:19, Grant Edwards wrote: >On 2014-11-10, giacomo boffi wrote: >> To help you understanding what is the `zip` builtin, please forget >> about PKZip etc and think about the _zip fastener_ or _zipper_ in >> your bag or in your trousers >> >> In the bag you have two sequences of teeth that the zipper >> binds together in interlocking pairs > >No, you don't. That's not how a zipper works. Each tooth from side A, >isn't bound with one from side B. It's bound with _two_ of them from >side B. And each of those is in turn bound with an additional tooth >from side A, and so on... This is true, but the analogy is still the correct one:-) Your nitpicking will not help the OP. Cheers, Cameron Simpson WFO: the normal throttle position for Denizens, squids, and unfortunates on 50cc Honda step-throughs. From denismfmcmahon at gmail.com Mon Nov 10 16:36:54 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Mon, 10 Nov 2014 21:36:54 +0000 (UTC) Subject: I don't read docs and don't know how to use Google. What does the print function do? References: Message-ID: On Mon, 10 Nov 2014 10:56:18 -0800, sohcahtoa82 wrote: > ... I know software engineers > make lots of money so I want to be one. I hear that pretty boy male escorts can make even more money than software engineers. They also don't need to learn how to program, which is something software engineers do need to do, so it sounds as if you'd be better off signing up with an escort agency. -- Denis McMahon, denismfmcmahon at gmail.com From sohcahtoa82 at gmail.com Mon Nov 10 16:45:32 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Mon, 10 Nov 2014 13:45:32 -0800 (PST) Subject: I don't read docs and don't know how to use Google. What does the print function do? In-Reply-To: References: Message-ID: <5e6d9132-ae99-4ef6-8e58-45000b2f4adb@googlegroups.com> On Monday, November 10, 2014 1:01:05 PM UTC-8, Grant Edwards wrote: > On 2014-11-10, sohcahtoa82 wrote: > > > Please help me this assignment is due in an hour. Don't give me > > hints, just give me the answer because I only want a grade. I'm not > > actually interested in learning how to program, but I know software > > engineers make lots of money so I want to be one. > > That's the saddest troll I've seen in ages. > Either you and I have a different definition of what a troll is, or your ability to detect parody and recognize a joke is a bit off. From ian.g.kelly at gmail.com Mon Nov 10 17:31:46 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 10 Nov 2014 15:31:46 -0700 Subject: I don't read docs and don't know how to use Google. What does the print function do? In-Reply-To: <5e6d9132-ae99-4ef6-8e58-45000b2f4adb@googlegroups.com> References: <5e6d9132-ae99-4ef6-8e58-45000b2f4adb@googlegroups.com> Message-ID: On Mon, Nov 10, 2014 at 2:45 PM, wrote: > On Monday, November 10, 2014 1:01:05 PM UTC-8, Grant Edwards wrote: >> On 2014-11-10, sohcahtoa82 wrote: >> >> > Please help me this assignment is due in an hour. Don't give me >> > hints, just give me the answer because I only want a grade. I'm not >> > actually interested in learning how to program, but I know software >> > engineers make lots of money so I want to be one. >> >> That's the saddest troll I've seen in ages. >> > > Either you and I have a different definition of what a troll is, or your ability to detect parody and recognize a joke is a bit off. The former, probably. It may have been amusing, but it was nonetheless an off-topic post seeking to get a reaction, i.e. a troll. From nad at acm.org Mon Nov 10 17:51:02 2014 From: nad at acm.org (Ned Deily) Date: Mon, 10 Nov 2014 14:51:02 -0800 Subject: ssl error with the python mac binary References: Message-ID: In article , Paul Wiseman wrote: > I've been using the latest mac ppc/i386 binaries from python.org > (https://www.python.org/ftp/python/2.7.8/python-2.7.8-macosx10.5.dmg). > From what I can tell this version is linked against a pretty old > version of OpenSSL (OpenSSL 0.9.7l 28 Sep 2006) which doesn't seem to > be able to handle new sha-256 certificates. > > For example I'm unable to use pip (I guess the certificate was updated > recently) Yes, the current python.org certificate does seem to cause problems for that version of OpenSSL, unfortunately. > Am I right in thinking this is an issue with the build of python > itself? Is there a way I can upgrade the version of OpenSSL linked > with python- or force the python build to look elsewhere for the > library? Or will I have to build my own from source? In the Pythons from the python.org OS X installers, the Python _ssl and _hashlib extension modules are dynamically linked with the system-supplied OpenSSL libraries. If actually running on OS X 10.5, one would have to rebuild _ssl.so and _hashlib.so, linking them with a locally-supplied version of a newer OpenSSL, since different versions of OpenSSL are not ABI-compatible, e.g. 0.9.7 vs 0.9.8 vs 1.0.1. If running on OS X 10.6 or later, another option might be to install from the 64-bit/32-bit installer which is a good idea to do anyway. For pip usage, a workaround would be to manually download distributions from PyPI (or elsewhere) using a web browser and then use pip to install from the downloaded file. The next version of pip is expected to have a --no-check-certificate option that bypasses the certificate check at the cost of reduced security. For the upcoming Python 2.7.9 release (planned for early December), I intend to have the Pythons in the python.org OS X installers use their own versions of OpenSSL and thus no longer depend on the now-deprecated system OpenSSL. -- Ned Deily, nad at acm.org From python at mrabarnett.plus.com Mon Nov 10 18:10:14 2014 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 10 Nov 2014 23:10:14 +0000 Subject: I don't read docs and don't know how to use Google. What does the print function do? In-Reply-To: <54611D2D.8030007@stoneleaf.us> References: <54611D2D.8030007@stoneleaf.us> Message-ID: <546145D6.7050603@mrabarnett.plus.com> On 2014-11-10 20:16, Ethan Furman wrote: > On 11/10/2014 11:59 AM, Larry Martell wrote: >> On Mon, Nov 10, 2014 at 2:49 PM, Roy Smith wrote: >>> In article , >>> sohcahtoa82 at gmail.com wrote: >>> >>>> Please help me this assignment is due in an hour. Don't give me hints, just >>>> give me the answer because I only want a grade. I'm not actually interested >>>> in learning how to program, but I know software engineers make lots of money >>>> so I want to be one. >>> >>> This post is a sine of the times. >> >> Don't go off on a tangent. > > Please! We don't need all this hyperbole! > ... cos it's off-topic. From satishmlmlml at gmail.com Mon Nov 10 18:13:31 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Mon, 10 Nov 2014 15:13:31 -0800 (PST) Subject: What does (?P) pattern syntax do? Message-ID: What does ?P and match in the following piece of code? re.search('(?P\w*)/(?P\w*)', '...aaa/bbb/ccc]').groups() From ben+python at benfinney.id.au Mon Nov 10 18:19:56 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 11 Nov 2014 10:19:56 +1100 Subject: What does (?P) pattern syntax do? References: Message-ID: <85k3327ieb.fsf@benfinney.id.au> satishmlmlml at gmail.com writes: > What does ?P and match in the following piece of code? Learn about Python's regular expression features from the documentation . Experiment with regular expressions using online tools such as . -- \ ?From the moment I picked your book up until I laid it down I | `\ was convulsed with laughter. Someday I intend reading it.? | _o__) ?Groucho Marx | Ben Finney From tjreedy at udel.edu Mon Nov 10 19:39:22 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 Nov 2014 19:39:22 -0500 Subject: What does zip mean? In-Reply-To: <20141110203601.GA69721@cskk.homeip.net> References: <20141110203601.GA69721@cskk.homeip.net> Message-ID: On 11/10/2014 3:36 PM, Cameron Simpson wrote: > On 10Nov2014 17:19, Grant Edwards wrote: >> On 2014-11-10, giacomo boffi wrote: >>> To help you understanding what is the `zip` builtin, please forget >>> about PKZip etc and think about the _zip fastener_ or _zipper_ in >>> your bag or in your trousers >>> >>> In the bag you have two sequences of teeth that the zipper >>> binds together in interlocking pairs >> >> No, you don't. That's not how a zipper works. Each tooth from side A, >> isn't bound with one from side B. It's bound with _two_ of them from >> side B. And each of those is in turn bound with an additional tooth >> from side A, and so on... > > This is true, but the analogy is still the correct one:-) Perhaps ironically in this context, zippers replaced hook-and-eye fastening, where the two sequences *are* matched in parallel. "Hookless fastener" was one of the original names (Wikipedia). -- Terry Jan Reedy From paddy3118 at gmail.com Mon Nov 10 21:03:07 2014 From: paddy3118 at gmail.com (Paddy) Date: Mon, 10 Nov 2014 18:03:07 -0800 (PST) Subject: "Natural" use of cmp= in sort In-Reply-To: References: Message-ID: <65bf2f6b-f83e-4900-ab6d-2dcdcbcb84b3@googlegroups.com> On Monday, 10 November 2014 19:44:39 UTC, Ian wrote: > On Mon, Nov 10, 2014 at 12:19 PM, Peter Otten wrote: > > I'm not sure this works. I tried: > > Here's a simpler failure case. > > >>> ineq = """f2 > f3 > ... f3 > f1""" > > [Previously posted code elided] > > >>> greater_thans > set([('f3', 'f1'), ('f2', 'f3')]) > >>> sorted(all_f, cmp=lambda t1, t2: 0 if t1==t2 else > ... (1 if (t1, t2) not in greater_thans else -1)) > ['f1', 'f2', 'f3'] > > Note that the greater_thans set is missing the implication by > transitivity that f2 > f1, so the given cmp function would > inconsistently return -1 for both comparisons cmp('f1', 'f2') and > cmp('f2', 'f1'). Thanks. I will look into this... From paddy3118 at gmail.com Mon Nov 10 22:09:49 2014 From: paddy3118 at gmail.com (Paddy) Date: Mon, 10 Nov 2014 19:09:49 -0800 (PST) Subject: "Natural" use of cmp= in sort In-Reply-To: References: Message-ID: On Monday, 10 November 2014 18:45:15 UTC, Paddy wrote: > Hi, I do agree with Raymond H. about the relative merits of cmp= and key= in sort/sorted, but I decided to also not let natural uses of cmp= pass silently. > > In answering this question, http://stackoverflow.com/a/26850434/10562 about ordering subject to inequalities it seemed natural to use the cmp= argument of sort rather than key=. > > The question is about merging given inequalities to make 1 inequality such that the inequalities also stays true. > > Thanks Peter, Ian. I have modified my code to expand transitive relations and ask you to view it on stackoverflow via the original link (as posting code on newsgroups is an ugly hack). My main reason for the post to c.l.p remains though; it seems like a *natural* use of the cmp= comparator function to sorted rather than using key= . From ian.g.kelly at gmail.com Tue Nov 11 01:36:10 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 10 Nov 2014 23:36:10 -0700 Subject: "Natural" use of cmp= in sort In-Reply-To: References: Message-ID: On Mon, Nov 10, 2014 at 8:09 PM, Paddy wrote: > On Monday, 10 November 2014 18:45:15 UTC, Paddy wrote: >> Hi, I do agree with Raymond H. about the relative merits of cmp= and key= in sort/sorted, but I decided to also not let natural uses of cmp= pass silently. >> >> In answering this question, http://stackoverflow.com/a/26850434/10562 about ordering subject to inequalities it seemed natural to use the cmp= argument of sort rather than key=. >> >> The question is about merging given inequalities to make 1 inequality such that the inequalities also stays true. >> >> > > Thanks Peter, Ian. I have modified my code to expand transitive relations and ask you to view it on stackoverflow via the original link (as posting code on newsgroups is an ugly hack). You still run into trouble though if the given inequalities don't provide enough information for a total ordering. E.g.: >>> ' > '.join(extract_relations("""f4 > f1 ... f2 > f3""")) 'f1 > f2 > f3 > f4' By adding some debugging prints, we can see what cmp calls were made by the sort routine and what the results were: cmp('f2', 'f1') -> 1 cmp('f3', 'f2') -> 1 cmp('f4', 'f3') -> 1 There is no information about the relative order of f2 and f1, so the cmp function just returns 1 there. f2 is known to be greater than f3, so that call correctly returns 1. There is again no information about the relative order of f4 and f3, so it again just returns 1. However, this is inconsistent with the first comparison that placed f1 > f2, because it implies that f1 > f4. As you can see, giving an inconsistent cmp function to sort produces bogus results. If you only have a partial ordering of the inputs, you need to make sure that the cmp function you provide is consistent with *some* total ordering. Another issue is that your expand_transitive_relations function is I think O(n**3 log n), which looks unattractive compared to the O(n**2) topological sort given in the other answers. Another advantage of the topological sort is that it will detect if the graph is cyclic (i.e. the input data itself is inconsistent), rather than just return a bogus output. > My main reason for the post to c.l.p remains though; it seems like a *natural* use of the cmp= comparator function to sorted rather than using key= . There are cases where a cmp function is more natural than a key function, but for these we have the functools.cmp_to_key adapter. From ian.g.kelly at gmail.com Tue Nov 11 02:43:40 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 11 Nov 2014 00:43:40 -0700 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> <87a943qyvn.fsf@handshake.de> <545CC204.2010301@stoneleaf.us> <8761eq424e.fsf@handshake.de> Message-ID: On Sat, Nov 8, 2014 at 3:31 PM, Gregory Ewing wrote: > (BTW, I'm actually surprised that this technique makes c callable. > There must be more going on that just "look up __call__ in the class > object", because evaluating C.__call__ just returns the descriptor > and doesn't invoking the descriptor mechanism.) But of course it doesn't just lookup C.__call__, because it has to bind the method to the instance before calling it, which means invoking the descriptor protocol. The actual lookup is more like: type(a).__dict__['__call__'].__get__(a, type(a)) From paddy3118 at gmail.com Tue Nov 11 02:44:56 2014 From: paddy3118 at gmail.com (Paddy) Date: Mon, 10 Nov 2014 23:44:56 -0800 (PST) Subject: "Natural" use of cmp= in sort In-Reply-To: References: Message-ID: On Tuesday, 11 November 2014 06:37:18 UTC, Ian wrote: > On Mon, Nov 10, 2014 at 8:09 PM, Paddy wrote: > > On Monday, 10 November 2014 18:45:15 UTC, Paddy wrote: > >> Hi, I do agree with Raymond H. about the relative merits of cmp= and key= in sort/sorted, but I decided to also not let natural uses of cmp= pass silently. > >> > >> In answering this question, http://stackoverflow.com/a/26850434/10562 about ordering subject to inequalities it seemed natural to use the cmp= argument of sort rather than key=. > >> > >> The question is about merging given inequalities to make 1 inequality such that the inequalities also stays true. > >> > >> > > > > Thanks Peter, Ian. I have modified my code to expand transitive relations and ask you to view it on stackoverflow via the original link (as posting code on newsgroups is an ugly hack). > > You still run into trouble though if the given inequalities don't > provide enough information for a total ordering. E.g.: > > >>> ' > '.join(extract_relations("""f4 > f1 > ... f2 > f3""")) > 'f1 > f2 > f3 > f4' > > By adding some debugging prints, we can see what cmp calls were made > by the sort routine and what the results were: > > cmp('f2', 'f1') -> 1 > cmp('f3', 'f2') -> 1 > cmp('f4', 'f3') -> 1 > > There is no information about the relative order of f2 and f1, so the > cmp function just returns 1 there. > f2 is known to be greater than f3, so that call correctly returns 1. > There is again no information about the relative order of f4 and f3, > so it again just returns 1. However, this is inconsistent with the > first comparison that placed f1 > f2, because it implies that f1 > f4. > > As you can see, giving an inconsistent cmp function to sort produces > bogus results. If you only have a partial ordering of the inputs, you > need to make sure that the cmp function you provide is consistent with > *some* total ordering. > > Another issue is that your expand_transitive_relations function is I > think O(n**3 log n), which looks unattractive compared to the O(n**2) > topological sort given in the other answers. Another advantage of the > topological sort is that it will detect if the graph is cyclic (i.e. > the input data itself is inconsistent), rather than just return a > bogus output. > > > My main reason for the post to c.l.p remains though; it seems like a *natural* use of the cmp= comparator function to sorted rather than using key= . > > There are cases where a cmp function is more natural than a key > function, but for these we have the functools.cmp_to_key adapter. Thanks Ian. The original author states "...and it is sure that the given inputs will give an output, i.e., the inputs will always be valid.", which could be taken as meaning that all inputs are sufficient, well formed, and contain all relations as their first example does. In that case, expand_transitive_relations is not even needed. Lets say it isn't for the sake of argument, then we are left with the direct use of cmp= versus a conversion to a key= function. It seems to me that *in this case* the cmp= function naturally flows from the solution algorithm and that cmp_to_key is less so. Yes, I knew that there are cases where a cmp function is more natural than key; the idea is to squirrel out a few. We have already made the, (well reasoned in my opinion), decision to go down the key= route in Python 3. I also like to track where my algorithms might originally map to cmp=. (It is not often). My only other case of this type is here: http://stackoverflow.com/questions/15797120/can-this-cmp-function-be-better-written-as-a-key-for-sorted. From crk at godblessthe.us Sun Nov 9 18:03:58 2014 From: crk at godblessthe.us (Clayton Kirkwood) Date: Sun, 9 Nov 2014 15:03:58 -0800 Subject: Python script that does batch find and replace in txt files In-Reply-To: <76a85d07-fbf2-49a7-866a-c990aa0f85b1@googlegroups.com> References: <46769509.90793.1415564600851.JavaMail.yahoo@jws10740.mail.gq1.yahoo.com> <76a85d07-fbf2-49a7-866a-c990aa0f85b1@googlegroups.com> Message-ID: <00a501cffc71$728ed120$57ac7360$@us> >-----Original Message----- >From: Python-list [mailto:python-list- >bounces+crk=godblessthe.us at python.org] On Behalf Of Syed Khalid >Sent: Sunday, November 09, 2014 1:08 PM >To: python-list at python.org >Subject: Re: Python script that does batch find and replace in txt files > >My Script, > >I have added > >import glob, codecs, re, os > >regex = re.compile(r"Age: |Sex: |House No: ") # etc etc Script I >executed in EditRocket : > >for txt in glob.glob("/D:/Python/source/*.txt"): > with codecs.open(txt, encoding="utf-8") as f: > oldlines = f.readlines() > for i, line in enumerate(oldlines): > if "Contact's Name:" in line: > break > newlines = [regex.sub("", line).strip().replace("-", "_") for line >in oldlines[i:] > with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: > w.write(os.linesep.join(newlines)) > To my young eyes, it looks like you are missing a ] at the end of the line before the with. > >Error Message : > > File "EamClean.log", line 12 > with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w: > ^ >SyntaxError: invalid syntax > >Kindly do the needful > > > >-- >https://mail.python.org/mailman/listinfo/python-list From crk at godblessthe.us Mon Nov 10 18:21:42 2014 From: crk at godblessthe.us (Clayton Kirkwood) Date: Mon, 10 Nov 2014 15:21:42 -0800 Subject: I don't read docs and don't know how to use Google. What does the print function do? In-Reply-To: References: Message-ID: <019e01cffd3d$18b60c50$4a2224f0$@us> >-----Original Message----- >From: Python-list [mailto:python-list- >bounces+crk=godblessthe.us at python.org] On Behalf Of Grant Edwards >Sent: Monday, November 10, 2014 1:01 PM >To: python-list at python.org >Subject: Re: I don't read docs and don't know how to use Google. What >does the print function do? > >On 2014-11-10, sohcahtoa82 at gmail.com wrote: > >> Please help me this assignment is due in an hour. Don't give me >> hints, just give me the answer because I only want a grade. I'm not >> actually interested in learning how to program, but I know software >> engineers make lots of money so I want to be one. > >That's the saddest troll I've seen in ages. Uh, how are you going to maintain a programming job if you don't know how to program? I don't want to act but I know Brad Pitt makes lots of money doing it, so I want to be Brad Pitt. Not! Not going to happen. Although I suspect for a price you could bring all of your professional programming jobs to somebody here, but I think you would pay out more than you would make. Clayton > >-- >Grant Edwards grant.b.edwards Yow! I just forgot my >whole > at philosophy of life!!! > gmail.com >-- >https://mail.python.org/mailman/listinfo/python-list From manolo at austrohungaro.com Mon Nov 10 16:36:00 2014 From: manolo at austrohungaro.com (Manolo =?iso-8859-1?Q?Mart=EDnez?=) Date: Mon, 10 Nov 2014 22:36:00 +0100 Subject: I don't read docs and don't know how to use Google. What does the print function do? In-Reply-To: References: Message-ID: <20141110213600.GB17612@beagle.localdomain> On 11/10/14 at 09:00pm, Grant Edwards wrote: > That's the saddest troll I've seen in ages. That, on the other hand, is a pretty decent bit of trolling. From rosuav at gmail.com Tue Nov 11 03:35:35 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Nov 2014 19:35:35 +1100 Subject: I don't read docs and don't know how to use Google. What does the print function do? In-Reply-To: <019e01cffd3d$18b60c50$4a2224f0$@us> References: <019e01cffd3d$18b60c50$4a2224f0$@us> Message-ID: On Tue, Nov 11, 2014 at 10:21 AM, Clayton Kirkwood wrote: > Uh, how are you going to maintain a programming job if you don't know how to > program? I don't want to act but I know Brad Pitt makes lots of money doing > it, so I want to be Brad Pitt. Not! Not going to happen. Although I suspect > for a price you could bring all of your professional programming jobs to > somebody here, but I think you would pay out more than you would make. > I'm not entirely sure how it works, but it does happen. I've been writing code for over two decades, and trying to earn a living at it for one and a bit, and in all that time, I have *never even once* found a job by applying in the classic way and sending in a resume. There are blog posts out there about how large proportions of applicants can't even write simple code on command... and I've taken the questions and shown them to my siblings (who protest that they're definitely not programmers), proving that a basic smattering of mathematical nous puts you above people who are trying to earn money from coding. It's like a carpenter, looking for a skilled assistant, and getting people who don't know which end of a saw to hold. It's like a prospective accountant not knowing the words "credit" and "debit". It's like someone trying to rule a country just on the basis of looking good on television... okay, so maybe there's one other "industry" where the incompetent have a shot at it. But fortunately, it's not everyone. There are the "bad eggs" who waste everyone's time, but there are plenty of truly competent people too. It's just a matter of figuring out which are the "will-be-competent" and which are the "totally lazy and not going anywhere", and there's not always a lot to distinguish them by. ChrisA From alister.nospam.ware at ntlworld.com Tue Nov 11 04:00:55 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Tue, 11 Nov 2014 09:00:55 GMT Subject: I don't read docs and don't know how to use Google. What does the print function do? References: Message-ID: On Mon, 10 Nov 2014 21:36:54 +0000, Denis McMahon wrote: > On Mon, 10 Nov 2014 10:56:18 -0800, sohcahtoa82 wrote: > >> ... I know software engineers make lots of money so I want to be one. > > I hear that pretty boy male escorts can make even more money than > software engineers. > > They also don't need to learn how to program, which is something > software engineers do need to do, so it sounds as if you'd be better off > signing up with an escort agency. in both cases you start at the bottom, as a rent boy you stay there -- He thinks by infection, catching an opinion like a cold. From alister.nospam.ware at ntlworld.com Tue Nov 11 04:04:52 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Tue, 11 Nov 2014 09:04:52 GMT Subject: A syntax question References: <3l48w.682048$9R5.402039@fx29.am4> Message-ID: On Mon, 10 Nov 2014 19:53:56 -0500, Dennis Lee Bieber wrote: > On Mon, 10 Nov 2014 14:56:11 GMT, alister > declaimed the following: > >>On Mon, 10 Nov 2014 14:54:55 +0000, alister wrote: >> >>> On Mon, 10 Nov 2014 14:44:53 +0000, Grant Edwards wrote: >>> >>>> On 2014-11-10, David Palao wrote: >>>> >>>>>> My crystal ball is currently in for repair and is not expected back >>>>>> in the foreseeable future. >>>>> >>>>> Without a crystal ball, this prediction might be not well founded. >>>> >>>> That isn't a prediction. It's an explicit statement of no >>>> prediction. >>>> He said that it is "not expected back" rather than "expected not to >>>> be back". They're two different things. The former asserts a _lack_ >>>> of expection/prediction. The latter asserts an >>>> expectation/prediction. >>> >>> It was only a a joke maybe it was a bit to subtle >> >>I didn't expect the Spanish inquisition (Damn wish Id though of that >>before sending the last post) > > They're now the Congregation of the Doctrine of the Faith -- formerly > led by the person who became Pope Benedict. but "I didnt expect the congregation of the Doctrine of the Faith" is not on topic. -- Never trust an automatic pistol or a D.A.'s deal. -- John Dillinger From info at egenix.com Tue Nov 11 04:06:05 2014 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Tue, 11 Nov 2014 10:06:05 +0100 Subject: ANN: eGenix pyOpenSSL Distribution 0.13.6 Message-ID: <5461D17D.2030507@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com pyOpenSSL Distribution Version 0.13.6 An easy-to-install and easy-to-use distribution of the pyOpenSSL Python interface for OpenSSL - available for Windows, Mac OS X and Unix platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.13.6.html ________________________________________________________________________ INTRODUCTION The eGenix.com pyOpenSSL Distribution includes everything you need to get started with SSL in Python. It comes with an easy-to-use installer that includes the most recent OpenSSL library versions in pre-compiled form, making your application independent of OS provided OpenSSL libraries: http://www.egenix.com/products/python/pyOpenSSL/ pyOpenSSL is an open-source Python add-on that allows writing SSL/TLS- aware network applications as well as certificate management tools: https://launchpad.net/pyopenssl/ OpenSSL is an open-source implementation of the SSL/TLS protocol: http://www.openssl.org/ ________________________________________________________________________ NEWS This new release of the eGenix.com pyOpenSSL Distribution updates the included OpenSSL version to the latest OpenSSL 1.0.1h version and adds a few more context options: New in OpenSSL -------------- * Reenabled the SSLv2 support in the bundled OpenSSL libraries which we had removed in 0.13.5, since removing the SSLv2 symbols resulted in too many compatibility problems with existing code such as e.g. >>> import OpenSSL >>> import ssl Traceback (most recent call last): File "", line 1, in File "ssl.py", line 60, in import _ssl ImportError: _ssl.so: undefined symbol: SSLv2_method The ImportError is the result of using the 0.13.5 version of the OpenSSL libs with an ssl module which was compiled against a system version with SSLv2 support, effectively making the ssl module unusable. To protect against SSLv2 and SSLv3 downgrade attacks, please make sure you setup the SSL context to disallow using SSLv2 and SSLv3, e.g. context = SSL.Context(SSL.SSLv23_METHOD) context.set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3) New in pyOpenSSL ---------------- * OpenSSL.__version__ is now updated to the distribution version rather than left at "0.13" as it was in previous releases. It now shows "0.13.6" for this release. * Emphasized on the need to "import OpenSSL" early to prevent Python from loading the system OpenSSL libraries instead of the embedded ones. Be sure to read the section Loading the embedded OpenSSL Libraries of the documentation for details on how to make sure that the embedded libraries are loaded: http://www.egenix.com/products/python/pyOpenSSL/doc/#LoadingOpenSSL Please see the product changelog for the full set of changes: http://www.egenix.com/products/python/pyOpenSSL/changelog.html pyOpenSSL / OpenSSL Binaries Included ------------------------------------- In addition to providing sources, we make binaries available that include both pyOpenSSL and the necessary OpenSSL libraries for all supported platforms: Windows x86 and x64, Linux x86 and x64, Mac OS X PPC, x86 and x64. We've also added egg-file distribution versions of our eGenix.com pyOpenSSL Distribution for Windows, Linux and Mac OS X to the available download options. These make setups using e.g. zc.buildout and other egg-file based installers a lot easier. ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/pyOpenSSL/ ________________________________________________________________________ UPGRADING Before installing this version of pyOpenSSL, please make sure that you uninstall any previously installed pyOpenSSL version. Otherwise, you could end up not using the included OpenSSL libs. _______________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. ________________________________________________________________________ MORE INFORMATION For more information about the eGenix pyOpenSSL Distribution, licensing and download instructions, please visit our web-site or write to sales at egenix.com. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Nov 11 2014) >>> Python Projects, Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope/Plone.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::::: Try our mxODBC.Connect Python Database Interface for free ! :::::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From ian.g.kelly at gmail.com Tue Nov 11 03:35:34 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 11 Nov 2014 01:35:34 -0700 Subject: "Natural" use of cmp= in sort In-Reply-To: References: Message-ID: On Tue, Nov 11, 2014 at 12:44 AM, Paddy wrote: > Thanks Ian. The original author states "...and it is sure that the given inputs will give an output, i.e., the inputs will always be valid.", which could be taken as meaning that all inputs are sufficient, well formed, and contain all relations as their first example does. Well, I brought it up because the start of that sentence is "There can be multiple inequalities as answer but I need any one which is correct...". The only way there would be more than one correct answer would be if the inputs were only partially ordered. I take the second part of the sentence as meaning only that the input can be safely assumed to be consistent. > Yes, I knew that there are cases where a cmp function is more natural than key; the idea is to squirrel out a few. We have already made the, (well reasoned in my opinion), decision to go down the key= route in Python 3. I also like to track where my algorithms might originally map to cmp=. (It is not often). Basically any time you have a comparison that isn't easily expressed by mapping the values to some bunch of ordered objects. As an example of what I mean, we can easily sort alphabetically using a key function: sorted(items, key=str) And we can easily sort reverse alphabetically: sorted(items, key=str, reverse=True) And we can easily sort alphabetically on multiple criteria: sorted(items, key=lambda x: (str(x.last_name), str(x.first_name))) But what if we want to combine those last two requirements? Suppose we have a table that we want to present sorted primarily in ascending order on one column, and secondarily in descending order on another. We can't just add the reverse argument argument to the previous expression, because that would reverse the sort order for both columns. But there is no simple key function for strings that will reverse the sort without using the reverse argument. There are basically two ways to approach this. One is to implement a cmp function and pass it to cmp_to_key. The other is to create a class with comparison methods that result in the desired order, and use the class as the key; this is really just a variation ot the cmp_to_key approach. From satishmlmlml at gmail.com Tue Nov 11 04:18:02 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Tue, 11 Nov 2014 01:18:02 -0800 (PST) Subject: What is \1 here? Message-ID: <6720bebb-8263-4fb1-bcef-10dcfdc44905@googlegroups.com> What does \1 do in the following piece of code(fourth line)? import re print(re.sub('[ABC]', '*', 'XAXAXBXBXCXC')) print(re.sub('[ABC]_', '*', 'XA-XA_XB-XB_XC-XC_')) print(re.sub('(.) spam', 'spam\\1', 'x spam, y spam')) def mapper(matchobj): return 'spam' + matchobj.group(1) print(re.sub('(.) spam', mapper, 'x spam, y spam')) From paddy3118 at gmail.com Tue Nov 11 04:21:19 2014 From: paddy3118 at gmail.com (Paddy) Date: Tue, 11 Nov 2014 01:21:19 -0800 (PST) Subject: "Natural" use of cmp= in sort In-Reply-To: References: Message-ID: <534c62e0-2b6c-47ed-9aed-3c4bdbeabdc6@googlegroups.com> On Tuesday, 11 November 2014 09:07:14 UTC, Ian wrote: > On Tue, Nov 11, 2014 at 12:44 AM, Paddy wrote: > > Thanks Ian. The original author states "...and it is sure that the given inputs will give an output, i.e., the inputs will always be valid.", which could be taken as meaning that all inputs are sufficient, well formed, and contain all relations as their first example does. > > Well, I brought it up because the start of that sentence is "There can > be multiple inequalities as answer but I need any one which is > correct...". The only way there would be more than one correct answer > would be if the inputs were only partially ordered. I take the second > part of the sentence as meaning only that the input can be safely > assumed to be consistent. > > > Yes, I knew that there are cases where a cmp function is more natural than key; the idea is to squirrel out a few. We have already made the, (well reasoned in my opinion), decision to go down the key= route in Python 3. I also like to track where my algorithms might originally map to cmp=. (It is not often). > > Basically any time you have a comparison that isn't easily expressed > by mapping the values to some bunch of ordered objects. Yep. I want to track when this comes up for me and others during their normal programming rather than in examples made to highlight the issue. From satishmlmlml at gmail.com Tue Nov 11 04:37:21 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Tue, 11 Nov 2014 01:37:21 -0800 (PST) Subject: What is ?s here? Message-ID: What does ?s do in the following piece of code? import re, pprint text = open('books.xml').read() pattern = '(?s)isbn="(.*?)".*?(.*?)' found = re.findall(pattern, text) mapping = {isbn: title for (isbn, title) in found} pprint.pprint(mapping) Here is books.xml Python & XML December 2001 Jones, Drake From breamoreboy at yahoo.co.uk Tue Nov 11 05:03:38 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 11 Nov 2014 10:03:38 +0000 Subject: What is \1 here? In-Reply-To: <6720bebb-8263-4fb1-bcef-10dcfdc44905@googlegroups.com> References: <6720bebb-8263-4fb1-bcef-10dcfdc44905@googlegroups.com> Message-ID: On 11/11/2014 09:18, satishmlmlml at gmail.com wrote: > What does \1 do in the following piece of code(fourth line)? > import re > print(re.sub('[ABC]', '*', 'XAXAXBXBXCXC')) > print(re.sub('[ABC]_', '*', 'XA-XA_XB-XB_XC-XC_')) > print(re.sub('(.) spam', 'spam\\1', 'x spam, y spam')) > def mapper(matchobj): > return 'spam' + matchobj.group(1) > print(re.sub('(.) spam', mapper, 'x spam, y spam')) > What did your last skivvy die of, overwork? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From ashleighdeal at hotmail.co.uk Tue Nov 11 06:17:42 2014 From: ashleighdeal at hotmail.co.uk (Ashleigh .) Date: Tue, 11 Nov 2014 11:17:42 +0000 Subject: FW: Trouble with Python In-Reply-To: References: Message-ID: To whom it may concern, I am currently trying to run some code in python(x,y). It was working perfectly a couple of weeks ago but recently it hasn't been. Every time it runs, the program crashes and becomes unresponsive resulting in me having to exit. It has happened on multiple computers, all using windows, and I was wondering if you could help me with my problem. I have attached a copy of my code. Thank you Ashleigh Deal -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: analyse_max.py Type: text/x-script.phyton Size: 4474 bytes Desc: not available URL: From A.E.Deal at student.reading.ac.uk Tue Nov 11 06:19:34 2014 From: A.E.Deal at student.reading.ac.uk (Ashleigh Deal) Date: Tue, 11 Nov 2014 11:19:34 +0000 Subject: Trouble with python Message-ID: <1415704786000.50391@student.reading.ac.uk> To whom it may concern, I am trying to use python as part of my part 3 project but my coding has suddenly stopped working. I am using python(x,y) and it was working perfectly a couple of weeks ago but recently it hasn't been. Every time it runs, the program crashes and becomes unresponsive resulting in me having to exit. It has happened on multiple computers in the met department, agriculture and also on my own laptop and I was wondering if you could help me with my problem. I have spoken to my supervisor already and he doesn't know what is wrong with it. I have attached a copy of my code, one version in word and one in python. Thank you Ashleigh Deal? -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: python code.docx Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document Size: 14207 bytes Desc: python code.docx URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: analyse_max.py URL: From ned at nedbatchelder.com Tue Nov 11 06:52:15 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Tue, 11 Nov 2014 06:52:15 -0500 Subject: What is \1 here? In-Reply-To: <6720bebb-8263-4fb1-bcef-10dcfdc44905@googlegroups.com> References: <6720bebb-8263-4fb1-bcef-10dcfdc44905@googlegroups.com> Message-ID: On 11/11/14 4:18 AM, satishmlmlml at gmail.com wrote: > What does \1 do in the following piece of code(fourth line)? > import re > print(re.sub('[ABC]', '*', 'XAXAXBXBXCXC')) > print(re.sub('[ABC]_', '*', 'XA-XA_XB-XB_XC-XC_')) > print(re.sub('(.) spam', 'spam\\1', 'x spam, y spam')) > def mapper(matchobj): > return 'spam' + matchobj.group(1) > print(re.sub('(.) spam', mapper, 'x spam, y spam')) > Maybe you can't tell from the reception you're getting here: People are growing tired of your questions about basic Python behavior. They want you to find a way to learn for yourself. You're asking about regular expressions. The Python docs have an extensive page detailing how they work: https://docs.python.org/3/library/re.html You need to learn how to find this stuff out for yourself. Ben Finney even gave you a pointer to a helpful site for experimenting with regexes: http://pythex.org/ -- Ned Batchelder, http://nedbatchelder.com From ben+python at benfinney.id.au Tue Nov 11 06:53:49 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 11 Nov 2014 22:53:49 +1100 Subject: Trouble with python References: <1415704786000.50391@student.reading.ac.uk> Message-ID: <85bnoec5rm.fsf@benfinney.id.au> Ashleigh Deal writes: > I am trying to use python as part of my part 3 project but my coding > has suddenly stopped working. I am using python(x,y) and it was > working perfectly a couple of weeks ago but recently it hasn't been. What has changed in the meantime, which could conceivably affect the program's behaviour? > Every time it runs, the program crashes and becomes unresponsive > resulting in me having to exit. When you say ?the program crashes?, that implies it stops with a fatal error. What is the complete error message text? -- \ ?If you ever teach a yodeling class, probably the hardest thing | `\ is to keep the students from just trying to yodel right off. | _o__) You see, we build to that.? ?Jack Handey | Ben Finney From davea at davea.name Tue Nov 11 07:22:44 2014 From: davea at davea.name (Dave Angel) Date: Tue, 11 Nov 2014 07:22:44 -0500 (EST) Subject: What is \1 here? References: <6720bebb-8263-4fb1-bcef-10dcfdc44905@googlegroups.com> Message-ID: satishmlmlml at gmail.com Wrote in message: > What does \1 do in the following piece of code(fourth line)? > import re > print(re.sub('[ABC]', '*', 'XAXAXBXBXCXC')) > print(re.sub('[ABC]_', '*', 'XA-XA_XB-XB_XC-XC_')) > print(re.sub('(.) spam', 'spam\\1', 'x spam, y spam')) > def mapper(matchobj): > return 'spam' + matchobj.group(1) > print(re.sub('(.) spam', mapper, 'x spam, y spam')) > > Recommend you use raw strings when defining regex patterns. Then you wouldn't have to double the backslash. To see what re.sub will see, try print ('spam\\1') As for what the function does with that, I'll have to guess, as I don't do regex. I'd guess it'll match any digit. -- DaveA From jaiminajmeri at gmail.com Mon Nov 10 23:30:46 2014 From: jaiminajmeri at gmail.com (Jaimin Ajmeri) Date: Tue, 11 Nov 2014 04:30:46 +0000 (UTC) Subject: Need some help with NetGroupAddUser References: <200212022206.gB2M6oCB006981@smtp-server1.tampabay.rr.com> Message-ID: cfl.rr.com> writes: > > New B question -- Need help with win32net.NetGroupAddUser. I used Mark Hammond > sample code to create a new user from his book Python Programming on Win32. I > then added one line to add the newuser to a group. > def CreateUserAndShare(userName, fullName): > homeDir = "%s\\%s" % (serverName, userName) > # Create user data in information level 3 (PyUSER_INFO_3) format. > userData = {} > userData['name'] = userName > userData['full_name'] = fullName > userData['password'] = userName > userData['flags'] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT > userData['priv'] = win32netcon.USER_PRIV_USER > userData['home_dir'] = homeDir > userData['home_dir_drive'] = "P:" > userData['primary_group_id'] = ntsecuritycon.DOMAIN_GROUP_RID_USERS > userData['password_expired'] = 1 # User must change password next logon. > > # Create the user > win32net.NetUserAdd(serverName, 3, userData) > win32net.NetGroupAddUser(serverName, "Administrator", userName) > > This is my error: > pywintypes.api_error: (2220, 'NetGroupAddUser', 'The group name could not be > found.') > What should I be using for the groupname parameter, I've tried them all, > Administrator, Guests, Users ext.... Any help will be greatly appreciated. > Thanks, > kc > > Hello kcollins15, Just try this..... import win32api import win32net ############################### Code to create user goes here ############################### ###################################################################### # Code to add created user to a group (on a local machine) serverName = "\\\\" + win32api.GetComputerName() domain = win32api.GetDomainName() data = [{"domainandname" : domain + "\\TestUser"}] print "Adding...." win32net.NetLocalGroupAddMembers(serverName,"Users",3,data) print "Added Successfully !!" ###################################################################### This is working piece of code. It worked for me, I needed to add newly created user to the group called "Users". Just replace "Users" with "Administrator". I'll get back soon on how and when NetGroupAddUser() should be used. Hope it helps...! Jaimin Ajmeri From joel.goldstick at gmail.com Tue Nov 11 09:14:12 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 11 Nov 2014 09:14:12 -0500 Subject: Trouble with python In-Reply-To: <85bnoec5rm.fsf@benfinney.id.au> References: <1415704786000.50391@student.reading.ac.uk> <85bnoec5rm.fsf@benfinney.id.au> Message-ID: On Tue, Nov 11, 2014 at 6:53 AM, Ben Finney wrote: > Ashleigh Deal writes: > >> I am trying to use python as part of my part 3 project but my coding >> has suddenly stopped working. I am using python(x,y) and it was >> working perfectly a couple of weeks ago but recently it hasn't been. > > What has changed in the meantime, which could conceivably affect the > program's behaviour? > >> Every time it runs, the program crashes and becomes unresponsive >> resulting in me having to exit. > > When you say ?the program crashes?, that implies it stops with a fatal > error. What is the complete error message text? > > -- > \ ?If you ever teach a yodeling class, probably the hardest thing | > `\ is to keep the students from just trying to yodel right off. | > _o__) You see, we build to that.? ?Jack Handey | > Ben Finney > A couple of points: Its best to cut and paste your code directly into your email text. And use plaintext, not rtf (emails with different fonts, etc.) This way your code will be exactly what you typed. You should say which version of python. I don't know what python(x,y) means, but python 3.4 or 2.7 is useful information. If you feel that the code used to work, but doesn't now, then how about the data file? Has the data you are studying changed? > -- > https://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick http://joelgoldstick.com From fomcl at yahoo.com Tue Nov 11 09:47:01 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 11 Nov 2014 14:47:01 +0000 (UTC) Subject: locale.getlocale() in cmd.exe vs. Idle In-Reply-To: References: Message-ID: <595961668.36331.1415717221155.JavaMail.yahoo@jws10713.mail.gq1.yahoo.com> ----- Original Message ----- > From: Terry Reedy > To: python-list at python.org > Cc: > Sent: Monday, November 10, 2014 9:31 PM > Subject: Re: locale.getlocale() in cmd.exe vs. Idle > > On 11/10/2014 4:22 AM, Albert-Jan Roskam wrote: >> Hi, >> >> Why do I get different output for locale.getlocale() in Idle vs. cmd.exe? > > Idle runs code in an environment that is slightly altered from the > standard python startup environment'. idlelib.IOBinding has this > ''' > # Try setting the locale, so that we can find out > # what encoding to use > try: > import locale > locale.setlocale(locale.LC_CTYPE, "") > ''' Hi Terry, Thank you. Any idea why setlocale (a *setter*) returns something other than None? (this question is not related to the (None, None) thing of getlocale, just curious). Would it be a good idea to put this setlocale line in site.py? Or should it be in __init__.py to make the code more portable? > idlelib.run, which runs in the user-code subprocess, imports IOBinding. > Setting LC_CTYPE is sufficient for getlocale() to not return null values. So then I would have all the locale categories of the 'bare' locale (sorry, I don't know what else I should call it), except for LC_CTYPE, which is derived from my system. So in LC_NUMERIC I'd still have the en_US period/comma for decimal/thousand grouping, respectively, but I switch to the nl_NL LC_CTYPE. I doubt if it matters, but still: will this not introduce an ueber hard-to-find possible bug when I use re.LOCALE? > C:\Users\Terry>python -c "import locale; > print(locale.getlocale())" > > (None, None) > > C:\Users\Terry>python -c "import locale; > locale.setlocale(locale.LC_CTYPE, ''); print(locale.getlocale())" > ('English_United States', '1252') What is the difference between getlocale and getdefaultlocale anyway? The docstrings are even partially the same. The notatation of getlocale appears to be OS-specific ("English_United States" in Windows) and not Unix-like (cf. getdefaultlocale: en_US) regards, Albert-Jan From python at mrabarnett.plus.com Tue Nov 11 10:04:18 2014 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 11 Nov 2014 15:04:18 +0000 Subject: Need some help with NetGroupAddUser In-Reply-To: References: <200212022206.gB2M6oCB006981@smtp-server1.tampabay.rr.com> Message-ID: <54622572.6070009@mrabarnett.plus.com> On 2014-11-11 04:30, Jaimin Ajmeri wrote: > cfl.rr.com> writes: > >> >> New B question -- Need help with win32net.NetGroupAddUser. I used Mark > Hammond >> sample code to create a new user from his book Python Programming on Win32. I >> then added one line to add the newuser to a group. >> def CreateUserAndShare(userName, fullName): >> homeDir = "%s\\%s" % (serverName, userName) >> # Create user data in information level 3 (PyUSER_INFO_3) format. >> userData = {} >> userData['name'] = userName >> userData['full_name'] = fullName >> userData['password'] = userName >> userData['flags'] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT >> userData['priv'] = win32netcon.USER_PRIV_USER >> userData['home_dir'] = homeDir >> userData['home_dir_drive'] = "P:" >> userData['primary_group_id'] = ntsecuritycon.DOMAIN_GROUP_RID_USERS >> userData['password_expired'] = 1 # User must change password next logon. >> >> # Create the user >> win32net.NetUserAdd(serverName, 3, userData) >> win32net.NetGroupAddUser(serverName, "Administrator", userName) >> >> This is my error: >> pywintypes.api_error: (2220, 'NetGroupAddUser', 'The group name could not be >> found.') >> What should I be using for the groupname parameter, I've tried them all, >> Administrator, Guests, Users ext.... Any help will be greatly appreciated. >> Thanks, >> kc >> >> > > Hello kcollins15, > > Just try this..... > > import win32api > import win32net > > ############################### > > Code to create user goes here > > ############################### > > ###################################################################### > > # Code to add created user to a group (on a local machine) > > serverName = "\\\\" + win32api.GetComputerName() > domain = win32api.GetDomainName() > data = [{"domainandname" : domain + "\\TestUser"}] > print "Adding...." > win32net.NetLocalGroupAddMembers(serverName,"Users",3,data) > print "Added Successfully !!" > > ###################################################################### > > This is working piece of code. It worked for me, I needed to add newly > created user to the group called "Users". > > Just replace "Users" with "Administrator". > > I'll get back soon on how and when NetGroupAddUser() should be used. > > Hope it helps...! > Jaimin Ajmeri > I think you're replying to a post that's more than 10 years old! From fomcl at yahoo.com Tue Nov 11 10:20:09 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 11 Nov 2014 15:20:09 +0000 (UTC) Subject: What is \1 here? In-Reply-To: References: Message-ID: <1198270879.38002.1415719209735.JavaMail.yahoo@jws10750.mail.gq1.yahoo.com> ----- Original Message ----- > From: Ned Batchelder > To: python-list at python.org > Cc: > Sent: Tuesday, November 11, 2014 12:52 PM > Subject: Re: What is \1 here? > You need to learn how to find this stuff out for yourself. Ben Finney > even gave you a pointer to a helpful site for experimenting with > regexes: http://pythex.org/ Cool. I also like this one, which hardly anybody appears to use: python C:\Python27\Tools\Scripts\redemo.py The functionality is virtually the same. From larry.martell at gmail.com Tue Nov 11 10:48:41 2014 From: larry.martell at gmail.com (Larry Martell) Date: Tue, 11 Nov 2014 10:48:41 -0500 Subject: Communicating with a PHP script (and pretending I'm a browser) Message-ID: I have a PHP app that I want to convert to django. But I want to do it stages. All the heavy lifting is in the PHP code, so first, I want to just use templates and views to generate the HTML, but still call the PHP code. Then later convert the PHP to python. My issue is that the PHP code expects to get all it's input from the REQUEST object and I've consumed that in the view. Is there any way I can somehow supply that to the PHP code? Is there some way python can communicate like curl ... it needs to send the request string in the body of a POST request to the URL that will route to the PHP script and get the output back. From rosuav at gmail.com Tue Nov 11 10:54:52 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Nov 2014 02:54:52 +1100 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: References: Message-ID: On Wed, Nov 12, 2014 at 2:48 AM, Larry Martell wrote: > Is there some way python can communicate like curl ... it needs to > send the request string in the body of a POST request to the URL that > will route to the PHP script and get the output back. That is possible, but probably more effort than it's worth. It'll likely be easier to just do the translation all at once. ChrisA From glicerinu at gmail.com Tue Nov 11 11:00:09 2014 From: glicerinu at gmail.com (Marc Aymerich) Date: Tue, 11 Nov 2014 17:00:09 +0100 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: References: Message-ID: On Tue, Nov 11, 2014 at 4:48 PM, Larry Martell wrote: > > I have a PHP app that I want to convert to django. But I want to do it > stages. All the heavy lifting is in the PHP code, so first, I want to > just use templates and views to generate the HTML, but still call the > PHP code. Then later convert the PHP to python. > > My issue is that the PHP code expects to get all it's input from the > REQUEST object and I've consumed that in the view. Is there any way I > can somehow supply that to the PHP code? > > Is there some way python can communicate like curl ... it needs to > send the request string in the body of a POST request to the URL that > will route to the PHP script and get the output back. Yes, I supose you can extract the needed information from the django Request object and call the php script passing the needed variables as environment state. as a guideline you can do something like cmd = ( 'REDIRECT_STATUS=200 ' 'REQUEST_METHOD=GET ' 'SCRIPT_FILENAME=htdocs/index.php ' 'SCRIPT_NAME=/index.php ' 'PATH_INFO=/ ' 'SERVER_NAME=site.tld ' 'SERVER_PROTOCOL=HTTP/1.1 ' 'REQUEST_URI=/nl/page ' 'HTTP_HOST=site.tld ' '/usr/bin/php-cgi' ) subprocess.Popen(cmd, stdout=subprocess.PIPE) -- Marc From larry.martell at gmail.com Tue Nov 11 11:37:18 2014 From: larry.martell at gmail.com (Larry Martell) Date: Tue, 11 Nov 2014 11:37:18 -0500 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: References: Message-ID: On Tue, Nov 11, 2014 at 10:54 AM, Chris Angelico wrote: > On Wed, Nov 12, 2014 at 2:48 AM, Larry Martell wrote: >> Is there some way python can communicate like curl ... it needs to >> send the request string in the body of a POST request to the URL that >> will route to the PHP script and get the output back. > > That is possible, but probably more effort than it's worth. It'll > likely be easier to just do the translation all at once. I would tend to agree, but that's not what my client wants. Also, it's A LOT of PHP code so it does make some small amount of sense. From joel.goldstick at gmail.com Tue Nov 11 11:43:51 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 11 Nov 2014 11:43:51 -0500 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: References: Message-ID: On Tue, Nov 11, 2014 at 11:37 AM, Larry Martell wrote: > On Tue, Nov 11, 2014 at 10:54 AM, Chris Angelico wrote: >> On Wed, Nov 12, 2014 at 2:48 AM, Larry Martell wrote: >>> Is there some way python can communicate like curl ... it needs to >>> send the request string in the body of a POST request to the URL that >>> will route to the PHP script and get the output back. >> >> That is possible, but probably more effort than it's worth. It'll >> likely be easier to just do the translation all at once. > > I would tend to agree, but that's not what my client wants. Also, it's > A LOT of PHP code so it does make some small amount of sense. > -- > https://mail.python.org/mailman/listinfo/python-list Is your client technically savvy? If not, then what is he paying you for? It sounds like he may be paying you to implement his bad idea. Maybe you can outline a better approach that he can buy into -- Joel Goldstick http://joelgoldstick.com From larry.martell at gmail.com Tue Nov 11 11:43:53 2014 From: larry.martell at gmail.com (Larry Martell) Date: Tue, 11 Nov 2014 11:43:53 -0500 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: References: Message-ID: On Tue, Nov 11, 2014 at 11:00 AM, Marc Aymerich wrote: > On Tue, Nov 11, 2014 at 4:48 PM, Larry Martell wrote: >> >> I have a PHP app that I want to convert to django. But I want to do it >> stages. All the heavy lifting is in the PHP code, so first, I want to >> just use templates and views to generate the HTML, but still call the >> PHP code. Then later convert the PHP to python. >> >> My issue is that the PHP code expects to get all it's input from the >> REQUEST object and I've consumed that in the view. Is there any way I >> can somehow supply that to the PHP code? >> >> Is there some way python can communicate like curl ... it needs to >> send the request string in the body of a POST request to the URL that >> will route to the PHP script and get the output back. > > > Yes, > I supose you can extract the needed information from the django > Request object and call the php script passing the needed variables as > environment state. > > as a guideline you can do something like > > cmd = ( > 'REDIRECT_STATUS=200 ' > 'REQUEST_METHOD=GET ' > 'SCRIPT_FILENAME=htdocs/index.php ' > 'SCRIPT_NAME=/index.php ' > 'PATH_INFO=/ ' > 'SERVER_NAME=site.tld ' > 'SERVER_PROTOCOL=HTTP/1.1 ' > 'REQUEST_URI=/nl/page ' > 'HTTP_HOST=site.tld ' > '/usr/bin/php-cgi' > ) > subprocess.Popen(cmd, stdout=subprocess.PIPE) Thanks very much Marc. In the example, how is the request string passed in? From luisromano at gmail.com Tue Nov 11 11:59:27 2014 From: luisromano at gmail.com (Luis Roberto Romano) Date: Tue, 11 Nov 2014 13:59:27 -0300 Subject: Problem with autopy and a specific app Message-ID: Hi. I need to manipulate the mouse. I found the "autopy" package. It's working perfectly with any application, except in one of them. The software's name is: AVerMedia Capture Studio. Did anybody use this module? Did anybody get any trouble with some app? Thanks -- ---------------------------------------------------------- Luis R. Romano PS: here is my code: http://pastebin.com/g6fqHsxS -------------- next part -------------- An HTML attachment was scrubbed... URL: From random832 at fastmail.us Tue Nov 11 12:18:40 2014 From: random832 at fastmail.us (random832 at fastmail.us) Date: Tue, 11 Nov 2014 12:18:40 -0500 Subject: locale.getlocale() in cmd.exe vs. Idle In-Reply-To: <595961668.36331.1415717221155.JavaMail.yahoo@jws10713.mail.gq1.yahoo.com> References: <595961668.36331.1415717221155.JavaMail.yahoo@jws10713.mail.gq1.yahoo.com> Message-ID: <1415726320.1112956.189733549.1EBFC0A9@webmail.messagingengine.com> On Tue, Nov 11, 2014, at 09:47, Albert-Jan Roskam wrote: > ----- Original Message ----- > > From: Terry Reedy > > To: python-list at python.org > > Cc: > > Sent: Monday, November 10, 2014 9:31 PM > > Subject: Re: locale.getlocale() in cmd.exe vs. Idle > > > > On 11/10/2014 4:22 AM, Albert-Jan Roskam wrote: > >> Hi, > >> > >> Why do I get different output for locale.getlocale() in Idle vs. cmd.exe? > > > > > > > Idle runs code in an environment that is slightly altered from the > > standard python startup environment'. idlelib.IOBinding has this > > ''' > > # Try setting the locale, so that we can find out > > # what encoding to use > > try: > > import locale > > locale.setlocale(locale.LC_CTYPE, "") > > ''' > > Hi Terry, > > Thank you. Any idea why setlocale (a *setter*) returns something other > than None? setlocale returns the actual value that the locale was set to. (this question is not related to the (None, None) thing of > getlocale, just curious). Would it be a good idea to put this setlocale > line in site.py? Or should it be in __init__.py to make the code more > portable? > > > idlelib.run, which runs in the user-code subprocess, imports IOBinding. > > Setting LC_CTYPE is sufficient for getlocale() to not return null values. > > So then I would have all the locale categories of the 'bare' locale > (sorry, I don't know what else I should call it), except for LC_CTYPE, > which is derived from my system. So in LC_NUMERIC I'd still have the > en_US period/comma for decimal/thousand grouping, respectively, but I > switch to the nl_NL LC_CTYPE. I doubt if it matters, but still: will this > not introduce an ueber hard-to-find possible bug when I use re.LOCALE? > > > C:\Users\Terry>python -c "import locale; > > print(locale.getlocale())" > > > > (None, None) > > > > C:\Users\Terry>python -c "import locale; > > locale.setlocale(locale.LC_CTYPE, ''); print(locale.getlocale())" > > ('English_United States', '1252') > > What is the difference between getlocale and getdefaultlocale anyway? The > docstrings are even partially the same. The notatation of getlocale > appears to be OS-specific ("English_United States" in Windows) and not > Unix-like (cf. getdefaultlocale: en_US) > > regards, > Albert-Jan > -- > https://mail.python.org/mailman/listinfo/python-list -- Random832 From glicerinu at gmail.com Tue Nov 11 12:18:31 2014 From: glicerinu at gmail.com (Marc Aymerich) Date: Tue, 11 Nov 2014 18:18:31 +0100 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: References: Message-ID: On Tue, Nov 11, 2014 at 5:43 PM, Larry Martell wrote: > On Tue, Nov 11, 2014 at 11:00 AM, Marc Aymerich wrote: >> On Tue, Nov 11, 2014 at 4:48 PM, Larry Martell wrote: >>> >>> I have a PHP app that I want to convert to django. But I want to do it >>> stages. All the heavy lifting is in the PHP code, so first, I want to >>> just use templates and views to generate the HTML, but still call the >>> PHP code. Then later convert the PHP to python. >>> >>> My issue is that the PHP code expects to get all it's input from the >>> REQUEST object and I've consumed that in the view. Is there any way I >>> can somehow supply that to the PHP code? >>> >>> Is there some way python can communicate like curl ... it needs to >>> send the request string in the body of a POST request to the URL that >>> will route to the PHP script and get the output back. >> >> >> Yes, >> I supose you can extract the needed information from the django >> Request object and call the php script passing the needed variables as >> environment state. >> >> as a guideline you can do something like >> >> cmd = ( >> 'REDIRECT_STATUS=200 ' >> 'REQUEST_METHOD=GET ' >> 'SCRIPT_FILENAME=htdocs/index.php ' >> 'SCRIPT_NAME=/index.php ' >> 'PATH_INFO=/ ' >> 'SERVER_NAME=site.tld ' >> 'SERVER_PROTOCOL=HTTP/1.1 ' >> 'REQUEST_URI=/nl/page ' >> 'HTTP_HOST=site.tld ' >> '/usr/bin/php-cgi' >> ) >> subprocess.Popen(cmd, stdout=subprocess.PIPE) > > Thanks very much Marc. In the example, how is the request string passed in? Yeah, a more complete example would be cmd = ( 'REDIRECT_STATUS={status} ' 'REQUEST_METHOD={method} ' 'SCRIPT_FILENAME={file} ' 'SCRIPT_NAME=/index.php ' 'PATH_INFO={path} ' 'SERVER_NAME=site.tld ' 'SERVER_PROTOCOL=HTTP/1.1 ' 'REQUEST_URI={path} ' 'HTTP_HOST=site.tld ' '/usr/bin/php-cgi' ).format( status=request.status, method=request.method, path=request.path, file=my_php_path_mapper(request.path), ) php = subprocess.Popen(cmd, stdout=subprocess.PIPE) response, err = php.communicate() if php.return_code != 0: return ResponseError(content=err) return Response(content=response) still incomplete and mostly wrong, but good enough to illustrate the main pattern :) -- Marc From random832 at fastmail.us Tue Nov 11 12:20:14 2014 From: random832 at fastmail.us (random832 at fastmail.us) Date: Tue, 11 Nov 2014 12:20:14 -0500 Subject: locale.getlocale() in cmd.exe vs. Idle In-Reply-To: <595961668.36331.1415717221155.JavaMail.yahoo@jws10713.mail.gq1.yahoo.com> References: <595961668.36331.1415717221155.JavaMail.yahoo@jws10713.mail.gq1.yahoo.com> Message-ID: <1415726414.1113047.189733869.045B4E7A@webmail.messagingengine.com> On Tue, Nov 11, 2014, at 09:47, Albert-Jan Roskam wrote: > ----- Original Message ----- > > From: Terry Reedy > > To: python-list at python.org > > Cc: > > Sent: Monday, November 10, 2014 9:31 PM > > Subject: Re: locale.getlocale() in cmd.exe vs. Idle > > > > On 11/10/2014 4:22 AM, Albert-Jan Roskam wrote: > >> Hi, > >> > >> Why do I get different output for locale.getlocale() in Idle vs. cmd.exe? > > > > > > > Idle runs code in an environment that is slightly altered from the > > standard python startup environment'. idlelib.IOBinding has this > > ''' > > # Try setting the locale, so that we can find out > > # what encoding to use > > try: > > import locale > > locale.setlocale(locale.LC_CTYPE, "") > > ''' > > Hi Terry, > > Thank you. Any idea why setlocale (a *setter*) returns something other > than None? setlocale returns the actual value that the locale was set to, which is often (always in case of "") not the same as the value that was passed in. The C function it is based on would return NULL on an error instead of raising an exception. >>> locale.setlocale(locale.LC_CTYPE,"") 'en_US.UTF-8' (this question is not related to the (None, None) thing of > getlocale, just curious). Would it be a good idea to put this setlocale > line in site.py? Or should it be in __init__.py to make the code more > portable? > > > idlelib.run, which runs in the user-code subprocess, imports IOBinding. > > Setting LC_CTYPE is sufficient for getlocale() to not return null values. > > So then I would have all the locale categories of the 'bare' locale > (sorry, I don't know what else I should call it), except for LC_CTYPE, > which is derived from my system. So in LC_NUMERIC I'd still have the > en_US period/comma for decimal/thousand grouping, respectively, but I > switch to the nl_NL LC_CTYPE. I doubt if it matters, but still: will this > not introduce an ueber hard-to-find possible bug when I use re.LOCALE? > > > C:\Users\Terry>python -c "import locale; > > print(locale.getlocale())" > > > > (None, None) > > > > C:\Users\Terry>python -c "import locale; > > locale.setlocale(locale.LC_CTYPE, ''); print(locale.getlocale())" > > ('English_United States', '1252') > > What is the difference between getlocale and getdefaultlocale anyway? The > docstrings are even partially the same. The notatation of getlocale > appears to be OS-specific ("English_United States" in Windows) and not > Unix-like (cf. getdefaultlocale: en_US) > > regards, > Albert-Jan > -- > https://mail.python.org/mailman/listinfo/python-list -- Random832 From larry.martell at gmail.com Tue Nov 11 12:26:48 2014 From: larry.martell at gmail.com (Larry Martell) Date: Tue, 11 Nov 2014 12:26:48 -0500 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: References: Message-ID: On Tue, Nov 11, 2014 at 12:18 PM, Marc Aymerich wrote: > On Tue, Nov 11, 2014 at 5:43 PM, Larry Martell wrote: >> On Tue, Nov 11, 2014 at 11:00 AM, Marc Aymerich wrote: >>> On Tue, Nov 11, 2014 at 4:48 PM, Larry Martell wrote: >>>> >>>> I have a PHP app that I want to convert to django. But I want to do it >>>> stages. All the heavy lifting is in the PHP code, so first, I want to >>>> just use templates and views to generate the HTML, but still call the >>>> PHP code. Then later convert the PHP to python. >>>> >>>> My issue is that the PHP code expects to get all it's input from the >>>> REQUEST object and I've consumed that in the view. Is there any way I >>>> can somehow supply that to the PHP code? >>>> >>>> Is there some way python can communicate like curl ... it needs to >>>> send the request string in the body of a POST request to the URL that >>>> will route to the PHP script and get the output back. >>> >>> >>> Yes, >>> I supose you can extract the needed information from the django >>> Request object and call the php script passing the needed variables as >>> environment state. >>> >>> as a guideline you can do something like >>> >>> cmd = ( >>> 'REDIRECT_STATUS=200 ' >>> 'REQUEST_METHOD=GET ' >>> 'SCRIPT_FILENAME=htdocs/index.php ' >>> 'SCRIPT_NAME=/index.php ' >>> 'PATH_INFO=/ ' >>> 'SERVER_NAME=site.tld ' >>> 'SERVER_PROTOCOL=HTTP/1.1 ' >>> 'REQUEST_URI=/nl/page ' >>> 'HTTP_HOST=site.tld ' >>> '/usr/bin/php-cgi' >>> ) >>> subprocess.Popen(cmd, stdout=subprocess.PIPE) >> >> Thanks very much Marc. In the example, how is the request string passed in? > > > Yeah, a more complete example would be > > cmd = ( > 'REDIRECT_STATUS={status} ' > 'REQUEST_METHOD={method} ' > 'SCRIPT_FILENAME={file} ' > 'SCRIPT_NAME=/index.php ' > 'PATH_INFO={path} ' > 'SERVER_NAME=site.tld ' > 'SERVER_PROTOCOL=HTTP/1.1 ' > 'REQUEST_URI={path} ' > 'HTTP_HOST=site.tld ' > '/usr/bin/php-cgi' > ).format( > status=request.status, > method=request.method, > path=request.path, > file=my_php_path_mapper(request.path), > ) > > php = subprocess.Popen(cmd, stdout=subprocess.PIPE) > response, err = php.communicate() > if php.return_code != 0: > return ResponseError(content=err) > return Response(content=response) > > > still incomplete and mostly wrong, but good enough to illustrate the > main pattern :) So I would put the contents of what I want in the request object in the file request.path? From larry.martell at gmail.com Tue Nov 11 12:30:48 2014 From: larry.martell at gmail.com (Larry Martell) Date: Tue, 11 Nov 2014 12:30:48 -0500 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: References: Message-ID: On Tue, Nov 11, 2014 at 11:43 AM, Joel Goldstick wrote: > On Tue, Nov 11, 2014 at 11:37 AM, Larry Martell wrote: >> On Tue, Nov 11, 2014 at 10:54 AM, Chris Angelico wrote: >>> On Wed, Nov 12, 2014 at 2:48 AM, Larry Martell wrote: >>>> Is there some way python can communicate like curl ... it needs to >>>> send the request string in the body of a POST request to the URL that >>>> will route to the PHP script and get the output back. >>> >>> That is possible, but probably more effort than it's worth. It'll >>> likely be easier to just do the translation all at once. >> >> I would tend to agree, but that's not what my client wants. Also, it's >> A LOT of PHP code so it does make some small amount of sense. > > Is your client technically savvy? If not, then what is he paying you > for? It sounds like he may be paying you to implement his bad idea. > Maybe you can outline a better approach that he can buy into They are technically savvy. They are a 100% PHP shop. They have a big, complicated app that they've been working on for 10 years. No one there knows python or django. They want to put some new frontends on their app. I was bought in for another project (involving Google Tag Manager and Google Analytics), which I completed. Then they asked me about this project. I told them they should redo their app in Flask or Django. It took some cajoling, but they eventually said OK. But then a few days later they said before I went off and reimplemented everything in python, could I just build the new frontend and call the existing PHP code. This would enable them to get the new frontends out to their clients sooner, and then I could go back and port the PHP to python. I don't see what is so wrong with that. From glicerinu at gmail.com Tue Nov 11 12:31:01 2014 From: glicerinu at gmail.com (Marc Aymerich) Date: Tue, 11 Nov 2014 18:31:01 +0100 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: References: Message-ID: On Tue, Nov 11, 2014 at 6:26 PM, Larry Martell wrote: > On Tue, Nov 11, 2014 at 12:18 PM, Marc Aymerich wrote: >> On Tue, Nov 11, 2014 at 5:43 PM, Larry Martell wrote: >>> On Tue, Nov 11, 2014 at 11:00 AM, Marc Aymerich wrote: >>>> On Tue, Nov 11, 2014 at 4:48 PM, Larry Martell wrote: >>>>> >>>>> I have a PHP app that I want to convert to django. But I want to do it >>>>> stages. All the heavy lifting is in the PHP code, so first, I want to >>>>> just use templates and views to generate the HTML, but still call the >>>>> PHP code. Then later convert the PHP to python. >>>>> >>>>> My issue is that the PHP code expects to get all it's input from the >>>>> REQUEST object and I've consumed that in the view. Is there any way I >>>>> can somehow supply that to the PHP code? >>>>> >>>>> Is there some way python can communicate like curl ... it needs to >>>>> send the request string in the body of a POST request to the URL that >>>>> will route to the PHP script and get the output back. >>>> >>>> >>>> Yes, >>>> I supose you can extract the needed information from the django >>>> Request object and call the php script passing the needed variables as >>>> environment state. >>>> >>>> as a guideline you can do something like >>>> >>>> cmd = ( >>>> 'REDIRECT_STATUS=200 ' >>>> 'REQUEST_METHOD=GET ' >>>> 'SCRIPT_FILENAME=htdocs/index.php ' >>>> 'SCRIPT_NAME=/index.php ' >>>> 'PATH_INFO=/ ' >>>> 'SERVER_NAME=site.tld ' >>>> 'SERVER_PROTOCOL=HTTP/1.1 ' >>>> 'REQUEST_URI=/nl/page ' >>>> 'HTTP_HOST=site.tld ' >>>> '/usr/bin/php-cgi' >>>> ) >>>> subprocess.Popen(cmd, stdout=subprocess.PIPE) >>> >>> Thanks very much Marc. In the example, how is the request string passed in? >> >> >> Yeah, a more complete example would be >> >> cmd = ( >> 'REDIRECT_STATUS={status} ' >> 'REQUEST_METHOD={method} ' >> 'SCRIPT_FILENAME={file} ' >> 'SCRIPT_NAME=/index.php ' >> 'PATH_INFO={path} ' >> 'SERVER_NAME=site.tld ' >> 'SERVER_PROTOCOL=HTTP/1.1 ' >> 'REQUEST_URI={path} ' >> 'HTTP_HOST=site.tld ' >> '/usr/bin/php-cgi' >> ).format( >> status=request.status, >> method=request.method, >> path=request.path, >> file=my_php_path_mapper(request.path), >> ) >> >> php = subprocess.Popen(cmd, stdout=subprocess.PIPE) >> response, err = php.communicate() >> if php.return_code != 0: >> return ResponseError(content=err) >> return Response(content=response) >> >> >> still incomplete and mostly wrong, but good enough to illustrate the >> main pattern :) > > > So I would put the contents of what I want in the request object in > the file request.path? I just invented the attribute names that django actually uses, but you can look at the excellent django documentation for the correct ones https://docs.djangoproject.com/en/dev/ref/request-response/ still this is a toy example and probably it would be a pain in the ass to really map the mixed URLs between the two web applications. -- Marc From larry.martell at gmail.com Tue Nov 11 12:33:43 2014 From: larry.martell at gmail.com (Larry Martell) Date: Tue, 11 Nov 2014 12:33:43 -0500 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: References: Message-ID: On Tue, Nov 11, 2014 at 12:31 PM, Marc Aymerich wrote: > On Tue, Nov 11, 2014 at 6:26 PM, Larry Martell wrote: >> On Tue, Nov 11, 2014 at 12:18 PM, Marc Aymerich wrote: >>> On Tue, Nov 11, 2014 at 5:43 PM, Larry Martell wrote: >>>> On Tue, Nov 11, 2014 at 11:00 AM, Marc Aymerich wrote: >>>>> On Tue, Nov 11, 2014 at 4:48 PM, Larry Martell wrote: >>>>>> >>>>>> I have a PHP app that I want to convert to django. But I want to do it >>>>>> stages. All the heavy lifting is in the PHP code, so first, I want to >>>>>> just use templates and views to generate the HTML, but still call the >>>>>> PHP code. Then later convert the PHP to python. >>>>>> >>>>>> My issue is that the PHP code expects to get all it's input from the >>>>>> REQUEST object and I've consumed that in the view. Is there any way I >>>>>> can somehow supply that to the PHP code? >>>>>> >>>>>> Is there some way python can communicate like curl ... it needs to >>>>>> send the request string in the body of a POST request to the URL that >>>>>> will route to the PHP script and get the output back. >>>>> >>>>> >>>>> Yes, >>>>> I supose you can extract the needed information from the django >>>>> Request object and call the php script passing the needed variables as >>>>> environment state. >>>>> >>>>> as a guideline you can do something like >>>>> >>>>> cmd = ( >>>>> 'REDIRECT_STATUS=200 ' >>>>> 'REQUEST_METHOD=GET ' >>>>> 'SCRIPT_FILENAME=htdocs/index.php ' >>>>> 'SCRIPT_NAME=/index.php ' >>>>> 'PATH_INFO=/ ' >>>>> 'SERVER_NAME=site.tld ' >>>>> 'SERVER_PROTOCOL=HTTP/1.1 ' >>>>> 'REQUEST_URI=/nl/page ' >>>>> 'HTTP_HOST=site.tld ' >>>>> '/usr/bin/php-cgi' >>>>> ) >>>>> subprocess.Popen(cmd, stdout=subprocess.PIPE) >>>> >>>> Thanks very much Marc. In the example, how is the request string passed in? >>> >>> >>> Yeah, a more complete example would be >>> >>> cmd = ( >>> 'REDIRECT_STATUS={status} ' >>> 'REQUEST_METHOD={method} ' >>> 'SCRIPT_FILENAME={file} ' >>> 'SCRIPT_NAME=/index.php ' >>> 'PATH_INFO={path} ' >>> 'SERVER_NAME=site.tld ' >>> 'SERVER_PROTOCOL=HTTP/1.1 ' >>> 'REQUEST_URI={path} ' >>> 'HTTP_HOST=site.tld ' >>> '/usr/bin/php-cgi' >>> ).format( >>> status=request.status, >>> method=request.method, >>> path=request.path, >>> file=my_php_path_mapper(request.path), >>> ) >>> >>> php = subprocess.Popen(cmd, stdout=subprocess.PIPE) >>> response, err = php.communicate() >>> if php.return_code != 0: >>> return ResponseError(content=err) >>> return Response(content=response) >>> >>> >>> still incomplete and mostly wrong, but good enough to illustrate the >>> main pattern :) >> >> >> So I would put the contents of what I want in the request object in >> the file request.path? > > I just invented the attribute names that django actually uses, but you > can look at the excellent django documentation for the correct ones > > https://docs.djangoproject.com/en/dev/ref/request-response/ > > still this is a toy example and probably it would be a pain in the ass > to really map the mixed URLs between the two web applications. OK, I see what you're saying now. Thanks. From denismfmcmahon at gmail.com Tue Nov 11 12:33:32 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 11 Nov 2014 17:33:32 +0000 (UTC) Subject: Communicating with a PHP script (and pretending I'm a browser) References: Message-ID: On Tue, 11 Nov 2014 10:48:41 -0500, Larry Martell wrote: > Is there some way python can communicate like curl ... it needs to send > the request string in the body of a POST request to the URL that will > route to the PHP script and get the output back. http://www.lmgtfy.com/?q=python+http+request and perhaps http://www.lmgtfy.com/?q=python+parse+html Personally I think last time I wanted to do we scraping in python I used requests and beautifulsoup, but ymmv. -- Denis McMahon, denismfmcmahon at gmail.com From denismfmcmahon at gmail.com Tue Nov 11 12:34:33 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 11 Nov 2014 17:34:33 +0000 (UTC) Subject: What is ?s here? References: Message-ID: On Tue, 11 Nov 2014 01:37:21 -0800, satishmlmlml wrote: > What does ?s do in the following piece of code? It tells you to learn about regex. -- Denis McMahon, denismfmcmahon at gmail.com From breamoreboy at yahoo.co.uk Tue Nov 11 12:39:07 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 11 Nov 2014 17:39:07 +0000 Subject: What is \1 here? In-Reply-To: <1198270879.38002.1415719209735.JavaMail.yahoo@jws10750.mail.gq1.yahoo.com> References: <1198270879.38002.1415719209735.JavaMail.yahoo@jws10750.mail.gq1.yahoo.com> Message-ID: On 11/11/2014 15:20, Albert-Jan Roskam wrote: > ----- Original Message ----- >> From: Ned Batchelder >> To: python-list at python.org >> Cc: >> Sent: Tuesday, November 11, 2014 12:52 PM >> Subject: Re: What is \1 here? > > > > >> You need to learn how to find this stuff out for yourself. Ben Finney >> even gave you a pointer to a helpful site for experimenting with >> regexes: http://pythex.org/ > > Cool. I also like this one, which hardly anybody appears to use: > > python C:\Python27\Tools\Scripts\redemo.py > > The functionality is virtually the same. > FTR redemo.py has been removed from Python 3 at some point. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From denismfmcmahon at gmail.com Tue Nov 11 12:35:14 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 11 Nov 2014 17:35:14 +0000 (UTC) Subject: What is \1 here? References: <6720bebb-8263-4fb1-bcef-10dcfdc44905@googlegroups.com> Message-ID: On Tue, 11 Nov 2014 01:18:02 -0800, satishmlmlml wrote: > What does \1 do in the following piece of code(fourth line)? It tells you to learn about regex. http://www.pcre.org/pcre.txt -- Denis McMahon, denismfmcmahon at gmail.com From ethan at stoneleaf.us Tue Nov 11 12:55:30 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 11 Nov 2014 09:55:30 -0800 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: References: Message-ID: <54624D92.4000404@stoneleaf.us> On 11/11/2014 09:30 AM, Larry Martell wrote: > > They are technically savvy. They are a 100% PHP shop. They have a big, > complicated app that they've been working on for 10 years. No one > there knows python or django. They want to put some new frontends on > their app. I was bought in for another project (involving Google Tag > Manager and Google Analytics), which I completed. Then they asked me > about this project. I told them they should redo their app in Flask or > Django. It took some cajoling, but they eventually said OK. But then a > few days later they said before I went off and reimplemented > everything in python, could I just build the new frontend and call the > existing PHP code. This would enable them to get the new frontends out > to their clients sooner, and then I could go back and port the PHP to > python. I don't see what is so wrong with that. Sounds like an excellent game plan to me. :) -- ~Ethan~ From ian.g.kelly at gmail.com Tue Nov 11 12:59:00 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 11 Nov 2014 10:59:00 -0700 Subject: "Natural" use of cmp= in sort In-Reply-To: <534c62e0-2b6c-47ed-9aed-3c4bdbeabdc6@googlegroups.com> References: <534c62e0-2b6c-47ed-9aed-3c4bdbeabdc6@googlegroups.com> Message-ID: On Tue, Nov 11, 2014 at 2:21 AM, Paddy wrote: > On Tuesday, 11 November 2014 09:07:14 UTC, Ian wrote: >> On Tue, Nov 11, 2014 at 12:44 AM, Paddy wrote: >> > Thanks Ian. The original author states "...and it is sure that the given inputs will give an output, i.e., the inputs will always be valid.", which could be taken as meaning that all inputs are sufficient, well formed, and contain all relations as their first example does. >> >> Well, I brought it up because the start of that sentence is "There can >> be multiple inequalities as answer but I need any one which is >> correct...". The only way there would be more than one correct answer >> would be if the inputs were only partially ordered. I take the second >> part of the sentence as meaning only that the input can be safely >> assumed to be consistent. >> >> > Yes, I knew that there are cases where a cmp function is more natural than key; the idea is to squirrel out a few. We have already made the, (well reasoned in my opinion), decision to go down the key= route in Python 3. I also like to track where my algorithms might originally map to cmp=. (It is not often). >> >> Basically any time you have a comparison that isn't easily expressed >> by mapping the values to some bunch of ordered objects. > > Yep. I want to track when this comes up for me and others during their normal programming rather than in examples made to highlight the issue. The example that I posted is one that I recall being brought up on this list in the past, but I don't have a link for you. From MaryFrances.McNamee at epas-ltd.com Tue Nov 11 11:53:18 2014 From: MaryFrances.McNamee at epas-ltd.com (Mary-Frances McNamee) Date: Tue, 11 Nov 2014 16:53:18 +0000 Subject: Advice Message-ID: <56F22D4D97CACC4D804386157B6CFBBC01CF38B5@SERVER1.epas.local> To whom it may concern, I am currently working on a bit of coding for a raspberry pi, I was wondering maybe I could get some advice? I want my program to run for a certain time, for example 7am-2.30am everyday. Is this possible? I would appreciate any help. Thank you for your time. Regards Mary-Frances [cid:image005.jpg at 01CF79CA.AD4CF410] Environmental Products & Services Ltd Email: MaryFrances.McNamee at EPAS-Ltd.com Tel: +44 (0) 28 30833081 Fax: +44 (0) 28 30257556 Address: 5 Shepherd's Drive, Carnbane Industrial Estate, Newry, Co. Down N. Ireland BT35 6JQ Website | Brochure (PDF) | Videos | Product Pack Company Registration No. N.I.34654 All Incoming and Outgoing emails are scanned using Sophos Anti-Virus - Ver 10.2 [cid:image001.jpg at 01CF79CB.9F3A3DF0] -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.jpg Type: image/jpeg Size: 1952 bytes Desc: image001.jpg URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image002.jpg Type: image/jpeg Size: 3981 bytes Desc: image002.jpg URL: From ian.g.kelly at gmail.com Tue Nov 11 13:24:41 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 11 Nov 2014 11:24:41 -0700 Subject: Advice In-Reply-To: <56F22D4D97CACC4D804386157B6CFBBC01CF38B5@SERVER1.epas.local> References: <56F22D4D97CACC4D804386157B6CFBBC01CF38B5@SERVER1.epas.local> Message-ID: On Tue, Nov 11, 2014 at 9:53 AM, Mary-Frances McNamee < MaryFrances.McNamee at epas-ltd.com> wrote: > > I am currently working on a bit of coding for a raspberry pi, I was wondering maybe I could get some advice? I want my program to run for a certain time, for example 7am-2.30am everyday. Is this possible? You can set up a cron job to start your program every day at whatever time you want: http://en.wikipedia.org/wiki/Cron To shut down the program, have your program periodically check the time and exit if the time is past the time you want to shut down. Exactly how you do this would depend on how the program is structured. -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Nov 11 13:26:01 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 11 Nov 2014 13:26:01 -0500 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: <54624D92.4000404@stoneleaf.us> References: <54624D92.4000404@stoneleaf.us> Message-ID: On Tue, Nov 11, 2014 at 12:55 PM, Ethan Furman wrote: > On 11/11/2014 09:30 AM, Larry Martell wrote: >> >> >> They are technically savvy. They are a 100% PHP shop. They have a big, >> complicated app that they've been working on for 10 years. No one >> there knows python or django. They want to put some new frontends on >> their app. I was bought in for another project (involving Google Tag >> Manager and Google Analytics), which I completed. Then they asked me >> about this project. I told them they should redo their app in Flask or >> Django. It took some cajoling, but they eventually said OK. But then a >> few days later they said before I went off and reimplemented >> everything in python, could I just build the new frontend and call the >> existing PHP code. This would enable them to get the new frontends out >> to their clients sooner, and then I could go back and port the PHP to >> python. I don't see what is so wrong with that. > > You obviously have thought this through. It just raises red flags for me. > Sounds like an excellent game plan to me. :) > > -- > ~Ethan~ > -- > https://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick http://joelgoldstick.com From rgaddi at technologyhighland.invalid Tue Nov 11 13:25:52 2014 From: rgaddi at technologyhighland.invalid (Rob Gaddi) Date: Tue, 11 Nov 2014 10:25:52 -0800 Subject: Advice References: Message-ID: <20141111102552.5a2a1ac2@rg.highlandtechnology.com> On Tue, 11 Nov 2014 16:53:18 +0000 Mary-Frances McNamee wrote: > To whom it may concern, > > I am currently working on a bit of coding for a raspberry pi, I was wondering maybe I could get some advice? I want my program to run for a certain time, for example 7am-2.30am everyday. Is this possible? > > I would appreciate any help. Thank you for your time. > > > Regards > Mary-Frances Your keyword search is 'cron'. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From peter.cacioppi at gmail.com Tue Nov 11 14:40:38 2014 From: peter.cacioppi at gmail.com (Peter Cacioppi) Date: Tue, 11 Nov 2014 11:40:38 -0800 (PST) Subject: I love assert Message-ID: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> I get the impression that most Pythonistas aren't as habituated with assert statements as I am. Is that just a misimpression on my part? If not, is there a good reason to assert less with Python than other languages? As far as I can tell, Python supports assert perfectly well. When run with the optimization flagging, the asserts are truly removed. I think one needs to take care with some basic assert coding - it's not a substitute for unit tests, it doesn't absolve you of normal exception responsibilities, and, most of all, it should be used for passive inspection and not action. But given these guidelines, I still find it very useful as "active comments". From willyach07 at gmail.com Tue Nov 11 14:53:28 2014 From: willyach07 at gmail.com (Will Acheson) Date: Tue, 11 Nov 2014 11:53:28 -0800 (PST) Subject: What is rstrip() in python? In-Reply-To: References: Message-ID: On Sunday, November 9, 2014 6:12:24 AM UTC-5, satish... at gmail.com wrote: > What is rstrip() in python? > > What does it do in the following piece of code? > > import sqlite3 > conn = sqlite3.connect('dbase1') > curs = conn.cursor() > > file = open('data.txt') > rows = [line.rstrip().split(',') for line in file] rstrip() removes whitespace, newline characters, tab characters, and carrige return characters (\n \t \r respectively) on the tail of a string. Or it can be used with an input parameter to remove all instances of that parameter from the tail of a string. ex: stringy = "i am helpful \t\t\t\t\n\n " stringy = stringy.rstrip() print stringy stdout: "i am helpful" or: stringy = "my favorite number is 8000000000000000000000" stringy = stringy.rstrip('0') print stringy stdout: "my favorite number is 8" pretty simple method, helpful for parsing out formatting characters from scraped content from webpages. https://docs.python.org/2/library/stdtypes.html?highlight=rstrip#str.rstrip From ben+python at benfinney.id.au Tue Nov 11 15:03:58 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Nov 2014 07:03:58 +1100 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: <85389pcxn5.fsf@benfinney.id.au> Peter Cacioppi writes: > I get the impression that most Pythonistas aren't as habituated with > assert statements as I am. Is that just a misimpression on my part? If > not, is there a good reason to assert less with Python than other > languages? I don't know about comparisons like ?use less with Python than other languages?. But I can explain why I don't use ?assert? much. > As far as I can tell, Python supports assert perfectly well. When run > with the optimization flagging, the asserts are truly removed. Exactly. I prefer the code I write to have as few surprises as possible. A reader familiar with Python should be able to read it and know what it does; ideally, even if that reader doesn't recall every detail of how Python operates. An ?assert? statement in the code will sometimes be active, and sometimes be a no-op, for *exactly* the same code under different circumstances. That's a trap for the reader, and I'd rather not set it. > I think one needs to take care with some basic assert coding - it's > not a substitute for unit tests, it doesn't absolve you of normal > exception responsibilities, and, most of all, it should be used for > passive inspection and not action. But given these guidelines, I still > find it very useful as "active comments". It's fine for debugging code while developing. But, in my opinion, it should never stay there, and should be removed before committing to VCS. -- \ ?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 denismfmcmahon at gmail.com Tue Nov 11 15:04:04 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 11 Nov 2014 20:04:04 +0000 (UTC) Subject: Python script that does batch find and replace in txt files References: Message-ID: On Sun, 09 Nov 2014 11:58:49 -0800, Syed Khalid wrote: > Python script that does batch find and replace in txt files Need a > python script that opens all .txt files in a folder find replace/delete > text and save files. Sounds like you need sed, not python. -- Denis McMahon, denismfmcmahon at gmail.com From ethan at stoneleaf.us Tue Nov 11 15:08:16 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 11 Nov 2014 12:08:16 -0800 Subject: I love assert In-Reply-To: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: <54626CB0.5080405@stoneleaf.us> On 11/11/2014 11:40 AM, Peter Cacioppi wrote: > > I get the impression that most Pythonistas aren't as habituated with assert statements > as I am. Is that just a misimpression on my part? If not, is there a good reason to > assert less with Python than other languages? > > As far as I can tell, Python supports assert perfectly well. When run with the optimization > flagging, the asserts are truly removed. > > I think one needs to take care with some basic assert coding - it's not a substitute for > unit tests, it doesn't absolve you of normal exception responsibilities, and, most of all, > it should be used for passive inspection and not action. But given these guidelines, I > still find it very useful as "active comments". asserts are a specialized tool, easily abused. Sounds like you are using them exactly as intended. The key question to ask (if one is curious whether one is using assert correctly) is: if all the asserts are removed, and my programs gets bad data, will it keep going as if it had gotten good data? Or, will it fail at the point it should have failed, or will it fail somewhere else? -- ~Ethan~ From willyach07 at gmail.com Tue Nov 11 15:06:07 2014 From: willyach07 at gmail.com (Will Acheson) Date: Tue, 11 Nov 2014 12:06:07 -0800 (PST) Subject: Python modules In-Reply-To: References: Message-ID: On Sunday, November 9, 2014 11:51:41 PM UTC-5, Steve Hayes wrote: > I have a book on Python that advocates dividing programs into modules, and > importing them when needed. > > I have a question about this. > > I can understand doing that in a compiled language, where different modules > can be imported from all sorts of places when the program is compiled. > > But I understand that Python is an interpreted language, and If I wrote a > program in Python like that, and wanted to run it on another computer, how > would it find all the modules to import at run-time, unless I copied the whole > directory structure over to the other computer? > > > > > -- > Steve Hayes from Tshwane, South Africa > Web: http://www.khanya.org.za/stevesig.htm > Blog: http://khanya.wordpress.com > E-mail - see web page, or parse: shayes at dunelm full stop org full stop uk I have had a lot of trouble with executing relative imports with some of my projects in python. Are there any best practices or methods besides '../../' type hard-coding? In one project, a spider using scrapy, I used this method to import a module from 'the other side' of a file directory. ---- spider_lib_path = os.path.realpath(os.path.dirname(__file__) + '/../../../../../library/python') object_builder_printer = imp.load_source('object_builder_printer', spider_lib_path + '/object_builder_printer.py') object_builder = object_builder_printer.object_builder_printer(settings) ---- the file structure was: spiders/ -current/ --app/ ---spiders/ ----scrapy/ -----Charlotte/ ------1.0/ -------pipelines.py (the file that needs to import object_builder_printer.py) --library/ ---python/ ----object_builder_printer.py I think the issue had something to do with there being duplicitous file names, as in, there are multiple directories named 'spiders'. From rgaddi at technologyhighland.invalid Tue Nov 11 15:20:37 2014 From: rgaddi at technologyhighland.invalid (Rob Gaddi) Date: Tue, 11 Nov 2014 12:20:37 -0800 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: <20141111122037.6753b57f@rg.highlandtechnology.com> On Tue, 11 Nov 2014 11:40:38 -0800 (PST) Peter Cacioppi wrote: > I get the impression that most Pythonistas aren't as habituated with assert statements as I am. Is that just a misimpression on my part? If not, is there a good reason to assert less with Python than other languages? > > As far as I can tell, Python supports assert perfectly well. When run with the optimization flagging, the asserts are truly removed. > > I think one needs to take care with some basic assert coding - it's not a substitute for unit tests, it doesn't absolve you of normal exception responsibilities, and, most of all, it should be used for passive inspection and not action. But given these guidelines, I still find it very useful as "active comments". > I tend to be a big fan, but it is easy to forget about the one big rake assert leaves in your lawn. You CAN NOT use an assert with any function that has a side effect or you break everything. assert test_and_set(var) That line there is pretty obvious about what's going on, but with the ability to turn class data members transparently into properties, using asserts safely actually requires a shocking amount of self-discipline. assert obj.read_accesses < 10 -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From breamoreboy at yahoo.co.uk Tue Nov 11 15:34:01 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 11 Nov 2014 20:34:01 +0000 Subject: I love assert In-Reply-To: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: On 11/11/2014 19:40, Peter Cacioppi wrote: > I get the impression that most Pythonistas aren't as habituated with assert statements as I am. Is that just a misimpression on my part? If not, is there a good reason to assert less with Python than other languages? > > As far as I can tell, Python supports assert perfectly well. When run with the optimization flagging, the asserts are truly removed. > > I think one needs to take care with some basic assert coding - it's not a substitute for unit tests, it doesn't absolve you of normal exception responsibilities, and, most of all, it should be used for passive inspection and not action. But given these guidelines, I still find it very useful as "active comments". > Please check this out https://mail.python.org/pipermail/python-list/2013-November/660401.html as it was released to critical acclaim :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From denismfmcmahon at gmail.com Tue Nov 11 15:43:01 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 11 Nov 2014 20:43:01 +0000 (UTC) Subject: Combining lists to dictionary Message-ID: Hi Given x,y are a lists of keys and value that I wish to combine to a dictionary, such that x[n] is the key for value y[n], which is preferred: z = {a:b for (a,b) in zip(x,y)} z = {x[n]:y[n] for n in range(min(len(x),len(y)))} The zip feels more elegant, but it seems clunky to use the zip method to create a list of tuples just to split them up into key:value pairs. However the zip method handles the inequal length list problem. Granted it would probably be advisable to check that x and y are the same length before starting anyway. -- Denis McMahon, denismfmcmahon at gmail.com From wingusr at gmail.com Tue Nov 11 15:57:45 2014 From: wingusr at gmail.com (TP) Date: Tue, 11 Nov 2014 12:57:45 -0800 Subject: I love assert In-Reply-To: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: On Tue, Nov 11, 2014 at 11:40 AM, Peter Cacioppi wrote: > I think one needs to take care with some basic assert coding - it's not a > substitute for unit tests, it doesn't absolve you of normal exception > responsibilities, and, most of all, it should be used for passive > inspection and not action. But given these guidelines, I still find it very > useful as "active comments". I first came across asserts when using Wing IDE. See "Helping Wing Analyze Code" [1] explains why using assert and isinstance will let Wing IDE autocomplete things it otherwise couldn't. PyCharm uses docstrings to accomplish the same task [2] but can also use asserts/isinstance [3]. [1] https://wingware.com/doc/edit/helping-wing-analyze-code [2] https://www.jetbrains.com/pycharm/webhelp/type-hinting-in-pycharm.html [3] http://stackoverflow.com/questions/9040387/is-there-a-way-to-explicitly-tell-pycharm-what-class-an-attribute-is-an-instance -------------- next part -------------- An HTML attachment was scrubbed... URL: From gherron at digipen.edu Tue Nov 11 15:55:49 2014 From: gherron at digipen.edu (Gary Herron) Date: Tue, 11 Nov 2014 12:55:49 -0800 Subject: Combining lists to dictionary In-Reply-To: References: Message-ID: <546277D5.9050406@digipen.edu> On 11/11/2014 12:43 PM, Denis McMahon wrote: > Hi > > Given x,y are a lists of keys and value that I wish to combine to a > dictionary, such that x[n] is the key for value y[n], which is preferred: > > z = {a:b for (a,b) in zip(x,y)} > z = {x[n]:y[n] for n in range(min(len(x),len(y)))} > > The zip feels more elegant, but it seems clunky to use the zip method to > create a list of tuples just to split them up into key:value pairs. > However the zip method handles the inequal length list problem. Granted > it would probably be advisable to check that x and y are the same length > before starting anyway. > Are you using python 2 or 3. (It ought to be 3 :-) .) In Python3, zip does not create a list, but rather an iterator which returns tuples. Not clunky at all, but rather an efficient implementation of the loop which you hand coded in your other example. From help(zip): class zip(object) | zip(iter1 [,iter2 [...]]) --> zip object | | Return a zip object whose .__next__() method returns a tuple where | the i-th element comes from the i-th iterable argument. The .__next__() | method continues until the shortest iterable in the argument sequence | is exhausted and then it raises StopIteration. ... Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From fomcl at yahoo.com Tue Nov 11 16:09:16 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 11 Nov 2014 21:09:16 +0000 (UTC) Subject: I love assert In-Reply-To: <54626CB0.5080405@stoneleaf.us> References: <54626CB0.5080405@stoneleaf.us> Message-ID: <1900956607.76400.1415740156398.JavaMail.yahoo@jws10772.mail.gq1.yahoo.com> ----- Original Message ----- > From: Ethan Furman > To: python-list at python.org > Cc: > Sent: Tuesday, November 11, 2014 9:08 PM > Subject: Re: I love assert > > On 11/11/2014 11:40 AM, Peter Cacioppi wrote: >> >> I get the impression that most Pythonistas aren't as habituated with > assert statements >> as I am. Is that just a misimpression on my part? If not, is there a good > reason to >> assert less with Python than other languages? >> >> As far as I can tell, Python supports assert perfectly well. When run with > the optimization >> flagging, the asserts are truly removed. >> >> I think one needs to take care with some basic assert coding - it's not > a substitute for >> unit tests, it doesn't absolve you of normal exception > responsibilities, and, most of all, >> it should be used for passive inspection and not action. But given these > guidelines, I >> still find it very useful as "active comments". > > asserts are a specialized tool, easily abused. Sounds like you are using them > exactly as intended. Would you say that assert is baaadly abused in nose?*) I never tried it, but probably all tests pass when Python is run with -O or -OO. *) Actually, I love that package. Much cleaner than unittest. From ethan at stoneleaf.us Tue Nov 11 16:15:54 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 11 Nov 2014 13:15:54 -0800 Subject: I love assert In-Reply-To: <1900956607.76400.1415740156398.JavaMail.yahoo@jws10772.mail.gq1.yahoo.com> References: <54626CB0.5080405@stoneleaf.us> <1900956607.76400.1415740156398.JavaMail.yahoo@jws10772.mail.gq1.yahoo.com> Message-ID: <54627C8A.6080003@stoneleaf.us> On 11/11/2014 01:09 PM, Albert-Jan Roskam wrote: > Ethan Furman wrote: >> >> asserts are a specialized tool, easily abused. Sounds like you are using them >> exactly as intended. > > Would you say that assert is baaadly abused in nose?*) I never tried it, but > probably all tests pass when Python is run with -O or -OO. I don't know, haven't used it nor read the code. It would certainly not be good if it failed in optimized mode. -- ~Ethan~ From steve.motola at channelfactory.com Tue Nov 11 16:26:01 2014 From: steve.motola at channelfactory.com (mojo) Date: Tue, 11 Nov 2014 13:26:01 -0800 (PST) Subject: PDF Library with full CSS3 Support Message-ID: Looking for a Python PDF Generation library that supports CSS3. Suggestions? From rgaddi at technologyhighland.invalid Tue Nov 11 16:42:30 2014 From: rgaddi at technologyhighland.invalid (Rob Gaddi) Date: Tue, 11 Nov 2014 13:42:30 -0800 Subject: Combining lists to dictionary References: Message-ID: <20141111134230.4a597eb6@rg.highlandtechnology.com> On Tue, 11 Nov 2014 20:43:01 +0000 (UTC) Denis McMahon wrote: > Hi > > Given x,y are a lists of keys and value that I wish to combine to a > dictionary, such that x[n] is the key for value y[n], which is preferred: > > z = {a:b for (a,b) in zip(x,y)} > z = {x[n]:y[n] for n in range(min(len(x),len(y)))} > > The zip feels more elegant, but it seems clunky to use the zip method to > create a list of tuples just to split them up into key:value pairs. > However the zip method handles the inequal length list problem. Granted > it would probably be advisable to check that x and y are the same length > before starting anyway. > > -- > Denis McMahon, denismfmcmahon at gmail.com To add to what Gary said, the explicit dict() init knows how to handle an iterable that emits pairs of data. So you can simplify further down to: z = dict(zip(x, y)) If you're running Python2, and really that concerned about the extra memory used by zip returning a list rather than an iterator, you can use itertools.izip -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From invalid at invalid.invalid Tue Nov 11 16:43:45 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 11 Nov 2014 21:43:45 +0000 (UTC) Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: On 2014-11-11, Ben Finney wrote: > An ?assert? statement in the code will sometimes be active, and > sometimes be a no-op, for *exactly* the same code under different > circumstances. Yep, it's the same in C, C++, Java, PHP, and other languages. I think most people know that asserts can be disabled (either at run-time or compile time), and often are for performance reasons. > That's a trap for the reader, and I'd rather not set it. Personally, I find that too many asserts often makes code hard to read just because of the visual clutter and the veritical "spread" it induces. -- Grant Edwards grant.b.edwards Yow! I hope I bought the at right relish ... zzzzzzzzz gmail.com ... From fomcl at yahoo.com Tue Nov 11 16:46:04 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 11 Nov 2014 21:46:04 +0000 (UTC) Subject: I love assert In-Reply-To: <54627C8A.6080003@stoneleaf.us> References: <54627C8A.6080003@stoneleaf.us> Message-ID: <1247729521.81958.1415742364915.JavaMail.yahoo@jws10723.mail.gq1.yahoo.com> ----- Original Message ----- > From: Ethan Furman > To: Albert-Jan Roskam > Cc: "python-list at python.org" > Sent: Tuesday, November 11, 2014 10:15 PM > Subject: Re: I love assert > > On 11/11/2014 01:09 PM, Albert-Jan Roskam wrote: >> Ethan Furman wrote: >>> >>> asserts are a specialized tool, easily abused. Sounds like you are > using them >>> exactly as intended. >> >> Would you say that assert is baaadly abused in nose?*) I never tried it, > but >> probably all tests pass when Python is run with -O or -OO. > > I don't know, haven't used it nor read the code. It would certainly not > be good if it failed in optimized mode. antonia at antonia-HP-2133 /tmp $ cat test.py def test_func_1(): assert 1 == 2 def test_func_2(): x = 1; y = 2 assert x == y if __name__ == "__main__": import nose nose.main() antonia at antonia-HP-2133 /tmp $ python -O test.py .. ---------------------------------------------------------------------- Ran 2 tests in 0.015s OK antonia at antonia-HP-2133 /tmp $ python -O -m nose test.py .. ---------------------------------------------------------------------- Ran 2 tests in 0.003s OK antonia at antonia-HP-2133 /tmp $ python test.py FF ====================================================================== FAIL: test.test_func_1 ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest self.test(*self.arg) File "/tmp/test.py", line 2, in test_func_1 assert 1 == 2 AssertionError ====================================================================== FAIL: test.test_func_2 ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest self.test(*self.arg) File "/tmp/test.py", line 6, in test_func_2 assert x == y AssertionError ---------------------------------------------------------------------- Ran 2 tests in 0.044s FAILED (failures=2) antonia at antonia-HP-2133 /tmp $ python -m nose test.py ... (same as previous) antonia at antonia-HP-2133 /tmp $ nosetests -O -v test.py Usage: nosetests [options] nosetests: error: no such option: -O # phweeew From rosuav at gmail.com Tue Nov 11 16:56:56 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Nov 2014 08:56:56 +1100 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: <54624D92.4000404@stoneleaf.us> References: <54624D92.4000404@stoneleaf.us> Message-ID: On Wed, Nov 12, 2014 at 4:55 AM, Ethan Furman wrote: > On 11/11/2014 09:30 AM, Larry Martell wrote: >> >> >> They are technically savvy. They are a 100% PHP shop. They have a big, >> complicated app that they've been working on for 10 years. No one >> there knows python or django. They want to put some new frontends on >> their app. I was bought in for another project (involving Google Tag >> Manager and Google Analytics), which I completed. Then they asked me >> about this project. I told them they should redo their app in Flask or >> Django. It took some cajoling, but they eventually said OK. But then a >> few days later they said before I went off and reimplemented >> everything in python, could I just build the new frontend and call the >> existing PHP code. This would enable them to get the new frontends out >> to their clients sooner, and then I could go back and port the PHP to >> python. I don't see what is so wrong with that. > > > Sounds like an excellent game plan to me. :) I wouldn't go so far as "excellent", but certainly it's not nonsensical. It's just a question of balancing the cost of the hybridization (development effort that, once the Python rewrite is complete, will be discarded) against the time gain of getting *something* sooner. Also, this will probably have a significant impact on performance/throughput, so everyone needs to be aware that benchmarking Python by looking at the new app's performance would be horribly unfair. But this is a viable proposal. ChrisA From ben+python at benfinney.id.au Tue Nov 11 17:18:50 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Nov 2014 09:18:50 +1100 Subject: Python modules References: Message-ID: <85bnod754l.fsf@benfinney.id.au> Will Acheson writes: > I have had a lot of trouble with executing relative imports with some > of my projects in python. > > Are there any best practices or methods besides '../../' type > hard-coding? The important point to learn with Python's import system, as contrasted with various other languages, is that it is *intentionally* abstracted from the filesystem hierarchy. That allows all kinds of helpful infrastructure, but it also comes with the cost of learning how to let Python know where modules are to be imported from; it's not a simple case of stating filesystem locations. The point which tripped me up for a long time, and which I have to keep reminding myself of: Python looks for modules in its import search path. Corollary: structure your project into a hierarchy of packages, including the top level, and specify all relative imports starting at that top-level package. Often the cause of my intra-project import woes comes from having several *discrete* packages, but trying to do relative imports between them:: hurgen/ # Note: ?hurgen? is not a Python package. foo/ __init__.py spam.py beans.py bar/ __init__.py eggs.py ham.py This is a poor structure, because Python needs to be told about each of ?foo? and ?bar? separately if relative imports are to work. Worse, a module invoked as the top-level module (e.g. ?eggs.py?) can't do imports relative to itself, because it isn't even aware it's in a package! Better is to structure the project explicitly under a top-level named Python package:: hurgen/ __init__.py foo/ __init__.py spam.py beans.py bar/ __init__.py eggs.py ham.py and import all the project's modules relative to the ?hurgen? package. From tjreedy at udel.edu Tue Nov 11 17:34:27 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Nov 2014 17:34:27 -0500 Subject: I love assert In-Reply-To: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: On 11/11/2014 2:40 PM, Peter Cacioppi wrote: > I get the impression that most Pythonistas aren't as habituated with > assert statements as I am. Is that just a misimpression on my part? > If not, is there a good reason to assert less with Python than other > languages? We love 'assert' so much that we have 20-30 'assertXYZ' variations in unittest. The statement 'assert expression' is almost equivalent to if not expression: raise AssertionError('expression') We have perhaps 100 mostly more specialized exceptions builtin and in the stdlib. There is nearly always a better, more specific exception and error message. > As far as I can tell, Python supports assert perfectly well. When run > with the optimization flagging, the asserts are truly removed. Separating tests from main code removes test asserts from the main code. Removal by -0 relegates bare assert to specialized usage. > I think one needs to take care with some basic assert coding - it's > not a substitute for unit tests, it doesn't absolve you of normal > exception responsibilities, and, most of all, it should be used for > passive inspection and not action. But given these guidelines, I > still find it very useful as "active comments". How much usage depends considerably on the programmer. -- Terry Jan Reedy From ben+python at benfinney.id.au Tue Nov 11 17:52:23 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Nov 2014 09:52:23 +1100 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: <857fz173ko.fsf@benfinney.id.au> Terry Reedy writes: > We love 'assert' so much that we have 20-30 'assertXYZ' variations in > unittest. A function will not be disabled by a run-time option to the Python interpreter. > The statement 'assert expression' is almost equivalent to > > if not expression: raise AssertionError('expression') With the important difference that this will be active no matter what options Python's interpreter is run with. That makes it quite a different proposition from using ?assert? statements. -- \ ?You don't need a book of any description to help you have some | `\ kind of moral awareness.? ?Dr. Francesca Stavrakoloulou, bible | _o__) scholar, 2011-05-08 | Ben Finney From python.list at tim.thechases.com Tue Nov 11 18:03:26 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 11 Nov 2014 17:03:26 -0600 Subject: I love assert In-Reply-To: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: <20141111170326.43e58f6a@bigbox.christie.dr> On 2014-11-11 11:40, Peter Cacioppi wrote: > I get the impression that most Pythonistas aren't as habituated > with assert statements as I am. Is that just a misimpression on my > part? I tend to use it to catch my bone-headedness rather than actual tests. I'm particularly fond of one that catches me typing "obj.exceptions" rather than "obj.exemptions" (both are common and occasionally interchangeable terms in $DAYJOB) something along the lines of assert hasattr(obj, "exceptions"), "idiot programmer" -tkc From peter.cacioppi at gmail.com Tue Nov 11 18:02:41 2014 From: peter.cacioppi at gmail.com (Peter Cacioppi) Date: Tue, 11 Nov 2014 15:02:41 -0800 Subject: I love assert In-Reply-To: References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: On Tue, Nov 11, 2014 at 12:57 PM, TP wrote: > On Tue, Nov 11, 2014 at 11:40 AM, Peter Cacioppi > wrote: > >> I think one needs to take care with some basic assert coding - it's not a >> substitute for unit tests, it doesn't absolve you of normal exception >> responsibilities, and, most of all, it should be used for passive >> inspection and not action. But given these guidelines, I still find it very >> useful as "active comments". > > > I first came across asserts when using Wing IDE. See "Helping Wing Analyze > Code" [1] explains why using assert and isinstance will let Wing IDE > autocomplete things it otherwise couldn't. > > PyCharm uses docstrings to accomplish the same task [2] but can also use > asserts/isinstance [3]. > > [1] https://wingware.com/doc/edit/helping-wing-analyze-code > > [2] https://www.jetbrains.com/pycharm/webhelp/type-hinting-in-pycharm.html > > > [3] > http://stackoverflow.com/questions/9040387/is-there-a-way-to-explicitly-tell-pycharm-what-class-an-attribute-is-an-instance > > I use PyCharm. Thanks for [2], it's a keeper -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Tue Nov 11 18:38:00 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 11 Nov 2014 15:38:00 -0800 Subject: I love assert In-Reply-To: References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: <54629DD8.9040701@stoneleaf.us> On 11/11/2014 03:02 PM, Peter Cacioppi wrote: > On Tue, Nov 11, 2014 at 12:57 PM, TP wrote: >> >> PyCharm uses docstrings to accomplish the same task [2] but can also use asserts/isinstance [3]. >> >> [2] https://www.jetbrains.com/pycharm/webhelp/type-hinting-in-pycharm.html >> > > I use PyCharm. Thanks for [2], it's a keeper Please, please don't use isinstance when you don't need to. It just makes your code unusable to anybody who wants/needs to use a different-yet-compatible type than the one you checked for. -- ~Ethan~ From tokyodweller at gmail.com Tue Nov 11 19:22:13 2014 From: tokyodweller at gmail.com (Michael Weems) Date: Tue, 11 Nov 2014 16:22:13 -0800 (PST) Subject: pip Install errors for bcrypt on OSX 10.10 Yosemite Message-ID: <8ef24031-f903-4e91-815d-49e18c1f93b4@googlegroups.com> $ sudo pip install bcrypt Downloading/unpacking bcrypt Downloading bcrypt-1.0.2.tar.gz (40kB): 40kB downloaded Running setup.py (path:/private/tmp/pip_build_root/bcrypt/setup.py) egg_info for package bcrypt Package libffi was not found in the pkg-config search path. Perhaps you should add the directory containing `libffi.pc' to the PKG_CONFIG_PATH environment variable No package 'libffi' found Package libffi was not found in the pkg-config search path. Perhaps you should add the directory containing `libffi.pc' to the PKG_CONFIG_PATH environment variable No package 'libffi' found Package libffi was not found in the pkg-config search path. Perhaps you should add the directory containing `libffi.pc' to the PKG_CONFIG_PATH environment variable No package 'libffi' found Package libffi was not found in the pkg-config search path. Perhaps you should add the directory containing `libffi.pc' to the PKG_CONFIG_PATH environment variable No package 'libffi' found Package libffi was not found in the pkg-config search path. Perhaps you should add the directory containing `libffi.pc' to the PKG_CONFIG_PATH environment variable No package 'libffi' found c/_cffi_backend.c:13:10: fatal error: 'ffi.h' file not found #include ^ 1 error generated. Traceback (most recent call last): File "", line 17, in File "/private/tmp/pip_build_root/bcrypt/setup.py", line 104, in "Programming Language :: Python :: 3.3", File "/usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 111, in setup _setup_distribution = dist = klass(attrs) File "build/bdist.macosx-10.10-x86_64/egg/setuptools/dist.py", line 262, in __init__ File "build/bdist.macosx-10.10-x86_64/egg/setuptools/dist.py", line 287, in fetch_build_eggs File "build/bdist.macosx-10.10-x86_64/egg/pkg_resources.py", line 631, in resolve File "build/bdist.macosx-10.10-x86_64/egg/pkg_resources.py", line 874, in best_match File "build/bdist.macosx-10.10-x86_64/egg/pkg_resources.py", line 886, in obtain File "build/bdist.macosx-10.10-x86_64/egg/setuptools/dist.py", line 338, in fetch_build_egg File "build/bdist.macosx-10.10-x86_64/egg/setuptools/command/easy_install.py", line 613, in easy_install File "build/bdist.macosx-10.10-x86_64/egg/setuptools/command/easy_install.py", line 643, in install_item File "build/bdist.macosx-10.10-x86_64/egg/setuptools/command/easy_install.py", line 833, in install_eggs File "build/bdist.macosx-10.10-x86_64/egg/setuptools/command/easy_install.py", line 1055, in build_and_install File "build/bdist.macosx-10.10-x86_64/egg/setuptools/command/easy_install.py", line 1043, in run_setup distutils.errors.DistutilsError: Setup script exited with error: command 'clang' failed with exit status 1 Complete output from command python setup.py egg_info: Package libffi was not found in the pkg-config search path. Perhaps you should add the directory containing `libffi.pc' to the PKG_CONFIG_PATH environment variable No package 'libffi' found Package libffi was not found in the pkg-config search path. Perhaps you should add the directory containing `libffi.pc' to the PKG_CONFIG_PATH environment variable No package 'libffi' found Package libffi was not found in the pkg-config search path. Perhaps you should add the directory containing `libffi.pc' to the PKG_CONFIG_PATH environment variable No package 'libffi' found Package libffi was not found in the pkg-config search path. Perhaps you should add the directory containing `libffi.pc' to the PKG_CONFIG_PATH environment variable No package 'libffi' found Package libffi was not found in the pkg-config search path. Perhaps you should add the directory containing `libffi.pc' to the PKG_CONFIG_PATH environment variable No package 'libffi' found c/_cffi_backend.c:13:10: fatal error: 'ffi.h' file not found #include ^ 1 error generated. Traceback (most recent call last): File "", line 17, in File "/private/tmp/pip_build_root/bcrypt/setup.py", line 104, in "Programming Language :: Python :: 3.3", File "/usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 111, in setup _setup_distribution = dist = klass(attrs) File "build/bdist.macosx-10.10-x86_64/egg/setuptools/dist.py", line 262, in __init__ File "build/bdist.macosx-10.10-x86_64/egg/setuptools/dist.py", line 287, in fetch_build_eggs File "build/bdist.macosx-10.10-x86_64/egg/pkg_resources.py", line 631, in resolve File "build/bdist.macosx-10.10-x86_64/egg/pkg_resources.py", line 874, in best_match File "build/bdist.macosx-10.10-x86_64/egg/pkg_resources.py", line 886, in obtain File "build/bdist.macosx-10.10-x86_64/egg/setuptools/dist.py", line 338, in fetch_build_egg File "build/bdist.macosx-10.10-x86_64/egg/setuptools/command/easy_install.py", line 613, in easy_install File "build/bdist.macosx-10.10-x86_64/egg/setuptools/command/easy_install.py", line 643, in install_item File "build/bdist.macosx-10.10-x86_64/egg/setuptools/command/easy_install.py", line 833, in install_eggs File "build/bdist.macosx-10.10-x86_64/egg/setuptools/command/easy_install.py", line 1055, in build_and_install File "build/bdist.macosx-10.10-x86_64/egg/setuptools/command/easy_install.py", line 1043, in run_setup distutils.errors.DistutilsError: Setup script exited with error: command 'clang' failed with exit status 1 ---------------------------------------- Cleaning up... Command python setup.py egg_info failed with error code 1 in /private/tmp/pip_build_root/bcrypt From ethan at stoneleaf.us Tue Nov 11 20:04:03 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 11 Nov 2014 17:04:03 -0800 Subject: html page mail link to webmail program Message-ID: <5462B203.7070201@stoneleaf.us> Just in case that subject line is not perfectly clear: ;) My wife (using a Win7 machine) will be on a web page that has a link to mail somebody. She clicks on it, and it opens the currently installed but unused Thunderbird. Ideally, what would happen is a new window/tab would open to gmail with a new compose window with the email address in place and the cursor in the subject line. Is this already done somewhere? If not, any ideas on which libs/packages to use to make it happen? -- ~Ethan~ From ben+python at benfinney.id.au Tue Nov 11 20:08:58 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Nov 2014 12:08:58 +1100 Subject: html page mail link to webmail program References: <5462B203.7070201@stoneleaf.us> Message-ID: <85y4rh5iol.fsf@benfinney.id.au> Ethan Furman writes: > My wife (using a Win7 machine) will be on a web page that has a link > to mail somebody. She clicks on it, and it opens the currently > installed but unused Thunderbird. > > Ideally, what would happen is a new window/tab would open to gmail > with a new compose window with the email address in place and the > cursor in the subject line. What is the Python question? I can't see anywhere that you would be using Python code to address this. -- \ ?Some people, when confronted with a problem, think ?I know, | `\ I'll use regular expressions?. Now they have two problems.? | _o__) ?Jamie Zawinski, in alt.religion.emacs | Ben Finney From roy at panix.com Tue Nov 11 20:06:47 2014 From: roy at panix.com (Roy Smith) Date: Tue, 11 Nov 2014 20:06:47 -0500 Subject: Combining lists to dictionary References: Message-ID: In article , Denis McMahon wrote: > Hi > > Given x,y are a lists of keys and value that I wish to combine to a > dictionary, such that x[n] is the key for value y[n], which is preferred: > > z = {a:b for (a,b) in zip(x,y)} > z = {x[n]:y[n] for n in range(min(len(x),len(y)))} > > The zip feels more elegant, but it seems clunky to use the zip method to > create a list of tuples just to split them up into key:value pairs. I would definitely use the first one. It's so much easier to read. If I was worried that the lists might be so long that the cost of building the intermediate list mattered, I'd use izip() instead of zip(). From ben+python at benfinney.id.au Tue Nov 11 20:16:59 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Nov 2014 12:16:59 +1100 Subject: Combining lists to dictionary References: Message-ID: <85tx255ib8.fsf@benfinney.id.au> Denis McMahon writes: > Hi > > Given x,y are a lists of keys and value that I wish to combine to a > dictionary, such that x[n] is the key for value y[n], which is preferred: > > z = {a:b for (a,b) in zip(x,y)} This one, with the caveat to use PEP-8 compatible formatting:: z = {a: b for (a, b) in zip(x, y)} > z = {x[n]:y[n] for n in range(min(len(x),len(y)))} Too much indirection for no gain that I can see. > The zip feels more elegant, but it seems clunky to use the zip method to > create a list of tuples just to split them up into key:value pairs. I think ?zip? has this as a primary intended purpose, so it seems fine to me. -- \ ?Of all classes the rich are the most noticed and the least | `\ studied.? ?John Kenneth Galbraith, _The Age of Uncertainty_, | _o__) 1977 | Ben Finney From ethan at stoneleaf.us Tue Nov 11 20:24:27 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 11 Nov 2014 17:24:27 -0800 Subject: I love assert In-Reply-To: <1247729521.81958.1415742364915.JavaMail.yahoo@jws10723.mail.gq1.yahoo.com> References: <54627C8A.6080003@stoneleaf.us> <1247729521.81958.1415742364915.JavaMail.yahoo@jws10723.mail.gq1.yahoo.com> Message-ID: <5462B6CB.9030102@stoneleaf.us> On 11/11/2014 01:46 PM, Albert-Jan Roskam wrote: > Ethan Furman wrote: >> >> I don't know, haven't used it nor read the code. It would certainly not >> be good if it failed in optimized mode. > > antonia at antonia-HP-2133 /tmp $ python -O test.py > Ran 2 tests in 0.015s > OK > > antonia at antonia-HP-2133 /tmp $ python -O -m nose test.py > Ran 2 tests in 0.003s > OK > > antonia at antonia-HP-2133 /tmp $ python test.py > Ran 2 tests in 0.044s > FAILED (failures=2) > > antonia at antonia-HP-2133 /tmp $ python -m nose test.py > Ran 2 tests in 0.044s > FAILED (failures=2) > > antonia at antonia-HP-2133 /tmp $ nosetests -O -v test.py > Usage: nosetests [options] > > nosetests: error: no such option: -O # phweeew In other words, nose the module doesn't handle optimized mode, and apparently nosetests cannot run in optimized mode. On the other hand, unittest: -------------------------------------- from unittest import TestCase, main class TestTest(TestCase): def test_optimized(self): self.assertTrue(1 == 2) if __name__ == '__main__': main() -------------------------------------- ethan at media:~/source$ python3.4 test.py Ran 1 test in 0.001s FAILED (failures=1) ethan at media:~/source$ python3.4 -O test.py Ran 1 test in 0.001s FAILED (failures=1) I'll stick with unittest. -- ~Ethan~ From ethan at stoneleaf.us Tue Nov 11 20:35:11 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 11 Nov 2014 17:35:11 -0800 Subject: html page mail link to webmail program In-Reply-To: <85y4rh5iol.fsf@benfinney.id.au> References: <5462B203.7070201@stoneleaf.us> <85y4rh5iol.fsf@benfinney.id.au> Message-ID: <5462B94F.4070809@stoneleaf.us> On 11/11/2014 05:08 PM, Ben Finney wrote: > Ethan Furman writes: > >> My wife (using a Win7 machine) will be on a web page that has a link >> to mail somebody. She clicks on it, and it opens the currently >> installed but unused Thunderbird. >> >> Ideally, what would happen is a new window/tab would open to gmail >> with a new compose window with the email address in place and the >> cursor in the subject line. > > What is the Python question? I can't see anywhere that you would be > using Python code to address this. Really? Huh. Okay, the explicit Python question: Clicking on a mail link in a web browser can start an external program. I would like that external program to be a Python script that: opens a new tab in the currently running browser (or a new default browser window), loads up the default web mail client (or one specified if there is no way to know/have a default), navigates to the compose pane (or starts there if possible), enters in the email address from the link that was passed to it, and, if not too much more, move the cursor to the subject field. Surely this can be done in Python. -- ~Ethan~ From ben+python at benfinney.id.au Tue Nov 11 20:42:07 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Nov 2014 12:42:07 +1100 Subject: html page mail link to webmail program References: <5462B203.7070201@stoneleaf.us> <85y4rh5iol.fsf@benfinney.id.au> <5462B94F.4070809@stoneleaf.us> Message-ID: <85ppct5h5c.fsf@benfinney.id.au> Ethan Furman writes: > Okay, the explicit Python question: Clicking on a mail link in a web > browser can start an external program. I would like that external > program to be a Python script that [controls an already-running web > browser to visit a URL and operate a web application]. > > Surely this can be done in Python. Perhaps. I'd advise a web search for ?python script web browser?, and be prepared for also learning how your specific operating system allows programs to control each other in separate processes. -- \ ?Either he's dead or my watch has stopped.? ?Groucho Marx | `\ | _o__) | Ben Finney From drsalists at gmail.com Tue Nov 11 20:56:18 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Tue, 11 Nov 2014 17:56:18 -0800 Subject: I love assert In-Reply-To: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: On Tue, Nov 11, 2014 at 11:40 AM, Peter Cacioppi wrote: > I get the impression that most Pythonistas aren't as habituated with assert statements as I am. Is that just a misimpression on my part? If not, is there a good reason to assert less with Python than other languages? > > As far as I can tell, Python supports assert perfectly well. When run with the optimization flagging, the asserts are truly removed. > > I think one needs to take care with some basic assert coding - it's not a substitute for unit tests, it doesn't absolve you of normal exception responsibilities, and, most of all, it should be used for passive inspection and not action. But given these guidelines, I still find it very useful as "active comments". assert is terrific (stops bugs in their tracks), though many things should be done with more targeted exceptions. I guess you could do a survey. From rosuav at gmail.com Tue Nov 11 21:21:42 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Nov 2014 13:21:42 +1100 Subject: I love assert In-Reply-To: <85389pcxn5.fsf@benfinney.id.au> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <85389pcxn5.fsf@benfinney.id.au> Message-ID: On Wed, Nov 12, 2014 at 7:03 AM, Ben Finney wrote: > An ?assert? statement in the code will sometimes be active, and > sometimes be a no-op, for *exactly* the same code under different > circumstances. That's a trap for the reader, and I'd rather not set it. This is no worse than other forms of preprocessor magic. I've seen this kind of thing in plenty of C projects: #ifdef DEBUG_MODE #define DEBUG print #else #define DEBUG(...) #endif ... further down ... DEBUG("We're here: %d:%d", foo, bar); If you're not in debug mode, this won't be evaluated. You can have "active code" inside its args if you want to, but only if it's exclusively part of the debugging output: DEBUG("We've hit this line %d times", ++hitcount); Again, not materially different from assert, and plenty of projects have this. Maybe people just need to understand "assert == DEBUG" and all's clear? ChrisA From rosuav at gmail.com Tue Nov 11 21:28:24 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Nov 2014 13:28:24 +1100 Subject: html page mail link to webmail program In-Reply-To: <85ppct5h5c.fsf@benfinney.id.au> References: <5462B203.7070201@stoneleaf.us> <85y4rh5iol.fsf@benfinney.id.au> <5462B94F.4070809@stoneleaf.us> <85ppct5h5c.fsf@benfinney.id.au> Message-ID: On Wed, Nov 12, 2014 at 12:42 PM, Ben Finney wrote: > Ethan Furman writes: > >> Okay, the explicit Python question: Clicking on a mail link in a web >> browser can start an external program. I would like that external >> program to be a Python script that [controls an already-running web >> browser to visit a URL and operate a web application]. >> >> Surely this can be done in Python. > > Perhaps. I'd advise a web search for ?python script web browser?, and be > prepared for also learning how your specific operating system allows > programs to control each other in separate processes. Or just look at antigravity.py in the standard library, which has a way of invoking a web browser - probably something trivially easy, like calling on the webbrowser module, but it's more fun to look it up via the arcane. ChrisA From ben+python at benfinney.id.au Tue Nov 11 21:35:53 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Nov 2014 13:35:53 +1100 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <85389pcxn5.fsf@benfinney.id.au> Message-ID: <85lhnh5enq.fsf@benfinney.id.au> Chris Angelico writes: > On Wed, Nov 12, 2014 at 7:03 AM, Ben Finney wrote: > > An ?assert? statement in the code will sometimes be active, and > > sometimes be a no-op, for *exactly* the same code under different > > circumstances. That's a trap for the reader, and I'd rather not set > > it. > > This is no worse than other forms of preprocessor magic. That other languages do it doesn't argue in favour of it. It argues, rather, that we should be glad not to have it in our Python code. > Again, not materially different from assert, and plenty of projects > have this. Maybe people just need to understand "assert == DEBUG" and > all's clear? The more things people need to keep in mind when reading my code that isn't stated explicitly in the code, the worse I consider the code to be. Python is a small, clear, expressive language. It has the valuable property that one does not need to keep in mind a lot of reminders of unexpected behaviour; good Python code behaves as it explicitly says it will, with very few implied surprises. To preserve this valuable but fragile property, I recommend treating ?assert? as a clever but obfuscatory trick, opposed to that property of Python. So an ?assert? statement should, IMO, not remain in the code past a debugging session. -- \ ?The entertainment industry calls DRM "security" software, | `\ because it makes them secure from their customers.? ?Cory | _o__) Doctorow, 2014-02-05 | Ben Finney From rosuav at gmail.com Tue Nov 11 21:44:10 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Nov 2014 13:44:10 +1100 Subject: I love assert In-Reply-To: <85lhnh5enq.fsf@benfinney.id.au> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <85389pcxn5.fsf@benfinney.id.au> <85lhnh5enq.fsf@benfinney.id.au> Message-ID: On Wed, Nov 12, 2014 at 1:35 PM, Ben Finney wrote: > The more things people need to keep in mind when reading my code that > isn't stated explicitly in the code, the worse I consider the code to > be. Then the ternary if/else operator should also be abolished. track["APIC:"].data if "APIC:" in track else None (With PEP 463, this would be: track["APIC:"].data except KeyError: None But this is from Python 2.7 code, so that was never going to happen anyway.) When you read the if/else version, you need to remember that it's evaluated middle-to-outside rather than outside-to-inside, and more importantly, that the first expression won't be evaluated at all if the key isn't present. So should we treat if/else as a "clever but obfuscatory trick, opposed to that property of Python" too? Or should people just get to know the language they're using? At least with 'assert', it's consistent across all Python programs; with my DEBUG example, it's per-project, as it's custom crafted. ChrisA From davea at davea.name Wed Nov 12 01:13:33 2014 From: davea at davea.name (Dave Angel) Date: Wed, 12 Nov 2014 01:13:33 -0500 (EST) Subject: Combining lists to dictionary References: <85tx255ib8.fsf@benfinney.id.au> Message-ID: Ben Finney Wrote in message: > Denis McMahon writes: > >> Hi >> >> Given x,y are a lists of keys and value that I wish to combine to a >> dictionary, such that x[n] is the key for value y[n], which is preferred: >> >> z = {a:b for (a,b) in zip(x,y)} > > This one, with the caveat to use PEP-8 compatible formatting:: > > z = {a: b for (a, b) in zip(x, y)} Or just z = dict(zip (x, y)) > -- DaveA From wxjmfauth at gmail.com Wed Nov 12 02:14:20 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Tue, 11 Nov 2014 23:14:20 -0800 (PST) Subject: I love assert In-Reply-To: References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <85389pcxn5.fsf@benfinney.id.au> <85lhnh5enq.fsf@benfinney.id.au> Message-ID: <38046f07-13b3-4e7e-8286-1110a498fe52@googlegroups.com> %%%%%%%% Does "assert" work, if Python fails (ev. crashes) on valid strings? :-) jmf From paddy3118 at gmail.com Wed Nov 12 03:09:09 2014 From: paddy3118 at gmail.com (Paddy) Date: Wed, 12 Nov 2014 00:09:09 -0800 (PST) Subject: "Natural" use of cmp= in sort In-Reply-To: References: <534c62e0-2b6c-47ed-9aed-3c4bdbeabdc6@googlegroups.com> Message-ID: <2081449f-0e39-463a-bd0a-344e0f46e6ba@googlegroups.com> On Tuesday, 11 November 2014 18:07:27 UTC, Ian wrote: > The example that I posted is one that I recall being brought up on > this list in the past, but I don't have a link for you. THanks Ian for your help in this. From tjreedy at udel.edu Wed Nov 12 03:29:13 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Nov 2014 03:29:13 -0500 Subject: I love assert In-Reply-To: <857fz173ko.fsf@benfinney.id.au> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <857fz173ko.fsf@benfinney.id.au> Message-ID: On 11/11/2014 5:52 PM, Ben Finney wrote: > Terry Reedy writes: > >> We love 'assert' so much that we have 20-30 'assertXYZ' variations in >> unittest. > > A function will not be disabled by a run-time option to the Python > interpreter. > >> The statement 'assert expression' is almost equivalent to >> >> if not expression: raise AssertionError('expression') > > With the important difference that this will be active no matter what > options Python's interpreter is run with. That makes it quite a > different proposition from using ?assert? statements. Which importand difference I pointed out (and you snipped) as a reason to seldom use bare assert. -- Terry Jan Reedy From joel.goldstick at gmail.com Tue Nov 11 13:22:43 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 11 Nov 2014 13:22:43 -0500 Subject: Advice In-Reply-To: <56F22D4D97CACC4D804386157B6CFBBC01CF38B5@SERVER1.epas.local> References: <56F22D4D97CACC4D804386157B6CFBBC01CF38B5@SERVER1.epas.local> Message-ID: On Tue, Nov 11, 2014 at 11:53 AM, Mary-Frances McNamee < MaryFrances.McNamee at epas-ltd.com> wrote: > To whom it may concern, > > > > I am currently working on a bit of coding for a raspberry pi, I was > wondering maybe I could get some advice? I want my program to run for a > certain time, for example 7am-2.30am everyday. Is this possible? > > > > I would appreciate any help. Thank you for your time. > > > > > > Regards > > Mary-Frances > > > > [image: cid:image005.jpg at 01CF79CA.AD4CF410] > > *Environmental Products & Services Ltd* > > Email: MaryFrances.McNamee at EPAS-Ltd.com > > Tel: +44 (0) 28 30833081 Fax: +44 (0) 28 30257556 > > Address: 5 Shepherd?s Drive, Carnbane Industrial Estate, Newry, Co. Down > N. Ireland BT35 6JQ > > Website | Brochure (PDF) > | Videos > | Product Pack > > > Company Registration No. N.I.34654 > All Incoming and Outgoing emails are scanned using Sophos Anti-Virus ? Ver > 10.2 > > > > [image: cid:image001.jpg at 01CF79CB.9F3A3DF0] > > > You may get more specific advice in a RPi mailing list, but you can start your program with a cron job (google that), and check the time in your code so as to exit at the required time > > -- > https://mail.python.org/mailman/listinfo/python-list > > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.jpg Type: image/jpeg Size: 1952 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image002.jpg Type: image/jpeg Size: 3981 bytes Desc: not available URL: From crk at godblessthe.us Wed Nov 12 00:39:43 2014 From: crk at godblessthe.us (Clayton Kirkwood) Date: Tue, 11 Nov 2014 21:39:43 -0800 Subject: I don't read docs and don't know how to use Google. What does the print function do? In-Reply-To: References: <019e01cffd3d$18b60c50$4a2224f0$@us> Message-ID: <036301cffe3b$1055d5a0$310180e0$@us> >-----Original Message----- >From: Python-list [mailto:python-list- >bounces+crk=godblessthe.us at python.org] On Behalf Of Chris Angelico >Sent: Tuesday, November 11, 2014 12:36 AM >Cc: python-list at python.org >Subject: Re: I don't read docs and don't know how to use Google. What >does the print function do? > >On Tue, Nov 11, 2014 at 10:21 AM, Clayton Kirkwood >wrote: >> Uh, how are you going to maintain a programming job if you don't know >> how to program? I don't want to act but I know Brad Pitt makes lots of >> money doing it, so I want to be Brad Pitt. Not! Not going to happen. >> Although I suspect for a price you could bring all of your >> professional programming jobs to somebody here, but I think you would >pay out more than you would make. >> > >I'm not entirely sure how it works, but it does happen. I've been >writing code for over two decades, and trying to earn a living at it for >one and a bit, and in all that time, I have *never even once* found a >job by applying in the classic way and sending in a resume. >There are blog posts out there about how large proportions of applicants >can't even write simple code on command... and I've taken the questions >and shown them to my siblings (who protest that they're definitely not >programmers), proving that a basic smattering of mathematical nous puts >you above people who are trying to earn money from coding. > >It's like a carpenter, looking for a skilled assistant, and getting >people who don't know which end of a saw to hold. > >It's like a prospective accountant not knowing the words "credit" and >"debit". > >It's like someone trying to rule a country just on the basis of looking >good on television... okay, so maybe there's one other "industry" where >the incompetent have a shot at it. > >But fortunately, it's not everyone. There are the "bad eggs" who waste >everyone's time, but there are plenty of truly competent people too. >It's just a matter of figuring out which are the "will-be-competent" >and which are the "totally lazy and not going anywhere", and there's not >always a lot to distinguish them by. > >ChrisA Chris, you're kidding, right? People get programming jobs without the knowledge? How do they keep them? Don't hiring people look at code examples, or previous employment? Ask relevant questions? My wife works for the county district attorney's office, and she tells me a lot about the incompetence of her co-workers and how they just kind of don't do their job, the petty personalities. My daughter works for AAA and tells how little co-workers know and are not willing to learn anything, but expect raises, etc. It's really hard for me to believe. I've worked in professional environs like Intel and Lockheed. You didn't keep a job long if you screwed around, and except for one person, everyone worked hard and earned their living, learning as much as they could, and generally got along. Some were great work groups that were incredibly rewarding and enjoyable. I have trouble believing the work ethics and behavior my family tells me about. Totally foreign to me. Clayton >-- >https://mail.python.org/mailman/listinfo/python-list From alister.nospam.ware at ntlworld.com Wed Nov 12 03:56:07 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Wed, 12 Nov 2014 08:56:07 GMT Subject: html page mail link to webmail program References: <5462B203.7070201@stoneleaf.us> <85y4rh5iol.fsf@benfinney.id.au> Message-ID: On Tue, 11 Nov 2014 17:35:11 -0800, Ethan Furman wrote: > On 11/11/2014 05:08 PM, Ben Finney wrote: >> Ethan Furman writes: >> >>> My wife (using a Win7 machine) will be on a web page that has a link >>> to mail somebody. She clicks on it, and it opens the currently >>> installed but unused Thunderbird. >>> >>> Ideally, what would happen is a new window/tab would open to gmail >>> with a new compose window with the email address in place and the >>> cursor in the subject line. >> >> What is the Python question? I can't see anywhere that you would be >> using Python code to address this. > > Really? Huh. > > Okay, the explicit Python question: Clicking on a mail link in a web > browser can start an external program. I would like that external > program to be a Python script that: opens a new tab in the currently > running browser (or a new default browser window), loads up the default > web mail client (or one specified if there is no way to know/have a > default), navigates to the compose pane (or starts there if possible), > enters in the email address from the link that was passed to it, and, if > not too much more, move the cursor to the subject field. > > Surely this can be done in Python. any chance you could fix your broken news reader? -- Life is to you a dashing and bold adventure. From alister.nospam.ware at ntlworld.com Wed Nov 12 03:58:39 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Wed, 12 Nov 2014 08:58:39 GMT Subject: html page mail link to webmail program References: <5462B203.7070201@stoneleaf.us> <85y4rh5iol.fsf@benfinney.id.au> Message-ID: <3jF8w.618086$XH2.407153@fx23.am4> On Wed, 12 Nov 2014 08:56:07 +0000, alister wrote: > On Tue, 11 Nov 2014 17:35:11 -0800, Ethan Furman wrote: > >> On 11/11/2014 05:08 PM, Ben Finney wrote: >>> Ethan Furman writes: >>> >>>> My wife (using a Win7 machine) will be on a web page that has a link >>>> to mail somebody. She clicks on it, and it opens the currently >>>> installed but unused Thunderbird. >>>> >>>> Ideally, what would happen is a new window/tab would open to gmail >>>> with a new compose window with the email address in place and the >>>> cursor in the subject line. >>> >>> What is the Python question? I can't see anywhere that you would be >>> using Python code to address this. >> >> Really? Huh. >> >> Okay, the explicit Python question: Clicking on a mail link in a web >> browser can start an external program. I would like that external >> program to be a Python script that: opens a new tab in the currently >> running browser (or a new default browser window), loads up the default >> web mail client (or one specified if there is no way to know/have a >> default), navigates to the compose pane (or starts there if possible), >> enters in the email address from the link that was passed to it, and, >> if not too much more, move the cursor to the subject field. >> >> Surely this can be done in Python. > > any chance you could fix your broken news reader? Apologies, all posts seem broken today. I am not sure of the cause yet -- Boren's Laws: (1) When in charge, ponder. (2) When in trouble, delegate. (3) When in doubt, mumble. From rosuav at gmail.com Wed Nov 12 04:15:57 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Nov 2014 20:15:57 +1100 Subject: I don't read docs and don't know how to use Google. What does the print function do? In-Reply-To: <036301cffe3b$1055d5a0$310180e0$@us> References: <019e01cffd3d$18b60c50$4a2224f0$@us> <036301cffe3b$1055d5a0$310180e0$@us> Message-ID: On Wed, Nov 12, 2014 at 4:39 PM, Clayton Kirkwood wrote: > Chris, you're kidding, right? People get programming jobs without the > knowledge? How do they keep them? Don't hiring people look at code examples, > or previous employment? Ask relevant questions? Oh, I didn't say they *keep* the jobs, nor necessarily even get them! (Although that can happen too - check out http://thedailywtf.com/ and some of the stories of what former employees' code can look like.) I'm talking about them applying, and then the potential employers have to weed through the utter incompetents to find the few who actually know what they're talking about. If the employer is himself/herself a programmer, this is a huge waste of a skilled person's time; if not, the short-listing of applicants will be highly flawed. Hence the problem: it's so hard to pick the right applicants that the right applicants end up not being picked - and so jobs remain unfilled (as I can attest to - the same job postings keep coming up in my RSS feeds), or incompetents get jobs and then get moved on. Sure, you could figure out whether one person is worth hiring or not. But when you have two hundred applications, can you afford to talk to every single one of them? I doubt it. And that's the problem. ChrisA From poalman at gmail.com Wed Nov 12 05:10:23 2014 From: poalman at gmail.com (Paul Wiseman) Date: Wed, 12 Nov 2014 10:10:23 +0000 Subject: ssl error with the python mac binary In-Reply-To: References: Message-ID: On 10 November 2014 22:51, Ned Deily wrote: > In article > , > Paul Wiseman wrote: >> I've been using the latest mac ppc/i386 binaries from python.org >> (https://www.python.org/ftp/python/2.7.8/python-2.7.8-macosx10.5.dmg). >> From what I can tell this version is linked against a pretty old >> version of OpenSSL (OpenSSL 0.9.7l 28 Sep 2006) which doesn't seem to >> be able to handle new sha-256 certificates. >> >> For example I'm unable to use pip (I guess the certificate was updated >> recently) > > Yes, the current python.org certificate does seem to cause problems for > that version of OpenSSL, unfortunately. > >> Am I right in thinking this is an issue with the build of python >> itself? Is there a way I can upgrade the version of OpenSSL linked >> with python- or force the python build to look elsewhere for the >> library? Or will I have to build my own from source? > > In the Pythons from the python.org OS X installers, the Python _ssl and > _hashlib extension modules are dynamically linked with the > system-supplied OpenSSL libraries. If actually running on OS X 10.5, > one would have to rebuild _ssl.so and _hashlib.so, linking them with a > locally-supplied version of a newer OpenSSL, since different versions of > OpenSSL are not ABI-compatible, e.g. 0.9.7 vs 0.9.8 vs 1.0.1. If > running on OS X 10.6 or later, another option might be to install from > the 64-bit/32-bit installer which is a good idea to do anyway. I'm currently using the installer with py2app to make a distributable app that targets 10.5+ (including ppc). To save having more than one build I use this for all downloads. Although I'm starting to consider making a second 32/64 distributable. Are there many major drawbacks for distributing this i386/ppc binary for all versions of OSX up 10.9 and 10.10? > For pip > usage, a workaround would be to manually download distributions from > PyPI (or elsewhere) using a web browser and then use pip to install from > the downloaded file. The next version of pip is expected to have a > --no-check-certificate option that bypasses the certificate check at the > cost of reduced security. Unfortunately the app is contacting a service which I'm unable to contact via plain http, which also happens to have the same type of certificate resulting in the same ssl error. (I have been going directly to pypi though :) > For the upcoming Python 2.7.9 release > (planned for early December), I intend to have the Pythons in the > python.org OS X installers use their own versions of OpenSSL and thus no > longer depend on the now-deprecated system OpenSSL. > That's great news! Thanks for this! I've always found building things on mac a huge pain and wasn't much looking forward to the prospect of trying to build a 32/ppc python build on a 64 bit 10.10 machine (would that even be possible?). > -- > Ned Deily, > nad at acm.org > > -- > https://mail.python.org/mailman/listinfo/python-list From joel.goldstick at gmail.com Wed Nov 12 07:34:18 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 12 Nov 2014 07:34:18 -0500 Subject: html page mail link to webmail program In-Reply-To: <3jF8w.618086$XH2.407153@fx23.am4> References: <5462B203.7070201@stoneleaf.us> <85y4rh5iol.fsf@benfinney.id.au> <3jF8w.618086$XH2.407153@fx23.am4> Message-ID: On Wed, Nov 12, 2014 at 3:58 AM, alister wrote: > On Wed, 12 Nov 2014 08:56:07 +0000, alister wrote: > >> On Tue, 11 Nov 2014 17:35:11 -0800, Ethan Furman wrote: >> >>> On 11/11/2014 05:08 PM, Ben Finney wrote: >>>> Ethan Furman writes: >>>> >>>>> My wife (using a Win7 machine) will be on a web page that has a link >>>>> to mail somebody. She clicks on it, and it opens the currently >>>>> installed but unused Thunderbird. >>>>> >>>>> Ideally, what would happen is a new window/tab would open to gmail >>>>> with a new compose window with the email address in place and the >>>>> cursor in the subject line. There are plugins on chrome to make gmail the mail client. Firefox I think has a setting to do the same. You should look into the browser/OS settings before rolling your own, since using python means setting up a web site.. all this to pick the default mail client? >>>> >>>> What is the Python question? I can't see anywhere that you would be >>>> using Python code to address this. >>> >>> Really? Huh. >>> >>> Okay, the explicit Python question: Clicking on a mail link in a web >>> browser can start an external program. I would like that external >>> program to be a Python script that: opens a new tab in the currently >>> running browser (or a new default browser window), loads up the default >>> web mail client (or one specified if there is no way to know/have a >>> default), navigates to the compose pane (or starts there if possible), >>> enters in the email address from the link that was passed to it, and, >>> if not too much more, move the cursor to the subject field. >>> >>> Surely this can be done in Python. >> >> any chance you could fix your broken news reader? > > Apologies, all posts seem broken today. I am not sure of the cause yet > > > > -- > Boren's Laws: > (1) When in charge, ponder. > (2) When in trouble, delegate. > (3) When in doubt, mumble. > -- > https://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick http://joelgoldstick.com From nomail at invalid.com Wed Nov 12 08:07:14 2014 From: nomail at invalid.com (ast) Date: Wed, 12 Nov 2014 14:07:14 +0100 Subject: Curious function argument Message-ID: <54635bce$0$2384$426a74cc@news.free.fr> Hello I saw in a code from a previous message in this forum a curious function argument. def test(x=[0]): print(x[0]) ## Poor man's object x[0] += 1 >>> test() 0 >>> test() 1 >>> test() 2 >>> I understand that the author wants to implement a global variable x . It would be better to write 'global x' inside the function. At first test() function call, it prints 0, that's OK. But at the second call, since we dont pass any argument to test(), x should be equal to its default value [0] (a single item list). But it seems that Python keeps the original object whose content has been changed to 1. Is it a usual way to implement a global variable ? thx From denismfmcmahon at gmail.com Wed Nov 12 09:03:58 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Wed, 12 Nov 2014 14:03:58 +0000 (UTC) Subject: Curious function argument References: <54635bce$0$2384$426a74cc@news.free.fr> Message-ID: On Wed, 12 Nov 2014 14:07:14 +0100, ast wrote: [function def with mutable default parameter] > I understand that the author wants to implement a global variable x . It > would be better to write 'global x' inside the function. It may not be the case that the purpose was to implement a global variable, but rather to illustrate what happens when you use a mutable default parameter. > At first test() function call, it prints 0, that's OK. > But at the second call, since we dont pass any argument to test(), x > should be equal to its default value [0] (a single item list). But it > seems that Python keeps the original object whose content has been > changed to 1. This is explained in the docs: https://docs.python.org/3/reference/compound_stmts.html#function- definitions Default parameter values are evaluated from left to right *when the function definition is executed*[1]. This means that the expression is evaluated once, when the function is defined, and that the same ?pre- computed? value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. [1] ie when the function is 'compiled', not each time it executes. -- Denis McMahon, denismfmcmahon at gmail.com From invalid at invalid.invalid Wed Nov 12 09:10:10 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 12 Nov 2014 14:10:10 +0000 (UTC) Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <85389pcxn5.fsf@benfinney.id.au> Message-ID: On 2014-11-12, Ben Finney wrote: > Chris Angelico writes: > >> On Wed, Nov 12, 2014 at 7:03 AM, Ben Finney wrote: >> > An ?assert? statement in the code will sometimes be active, and >> > sometimes be a no-op, for *exactly* the same code under different >> > circumstances. That's a trap for the reader, and I'd rather not set >> > it. >> >> This is no worse than other forms of preprocessor magic. > > That other languages do it doesn't argue in favour of it. It argues, > rather, that we should be glad not to have it in our Python code. Technically it's not an argument for assert, but I think it is a refutation of one of your arguments against assert. It refutes your statement that the fact that asserts may not always be active is a suprise to people and therefore acts as a "trap". -- Grant Edwards grant.b.edwards Yow! Is it clean in other at dimensions? gmail.com From rosuav at gmail.com Wed Nov 12 09:37:12 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Nov 2014 01:37:12 +1100 Subject: __missing__ for the top-level Python script In-Reply-To: References: Message-ID: On Mon, Nov 10, 2014 at 10:31 AM, Chris Angelico wrote: > So the semantics should be: If NameError would be raised (not > including UnboundLocalError, which still represents an error), attempt > to import the absent name. If successful, continue as if it had > already been done. If ImportError is raised, suppress it and let the > original NameError happen. No bites? I'd have thought there'd be a few crazy ideas thrown out in answer to this. What if it's worded as a feature for interactive Python? Save you the trouble of explicitly importing modules, by auto-importing them in response to usage. In theory, it's as simple as adding __missing__ to globals(), but I don't know of a way to do that for the main module. ChrisA From ethan at stoneleaf.us Wed Nov 12 09:54:56 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 12 Nov 2014 06:54:56 -0800 Subject: __missing__ for the top-level Python script In-Reply-To: References: Message-ID: <546374C0.9010103@stoneleaf.us> On 11/12/2014 06:37 AM, Chris Angelico wrote: > On Mon, Nov 10, 2014 at 10:31 AM, Chris Angelico wrote: >> So the semantics should be: If NameError would be raised (not >> including UnboundLocalError, which still represents an error), attempt >> to import the absent name. If successful, continue as if it had >> already been done. If ImportError is raised, suppress it and let the >> original NameError happen. > > No bites? I'd have thought there'd be a few crazy ideas thrown out in > answer to this. > > What if it's worded as a feature for interactive Python? Save you the > trouble of explicitly importing modules, by auto-importing them in > response to usage. In theory, it's as simple as adding __missing__ to > globals(), but I don't know of a way to do that for the main module. You might check out https://docs.python.org/3/library/sys.html#sys.excepthook -- ~Ethan~ From skip.montanaro at gmail.com Wed Nov 12 09:56:58 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Wed, 12 Nov 2014 09:56:58 -0500 Subject: __missing__ for the top-level Python script In-Reply-To: References: Message-ID: > No bites? I'd have thought there'd be a few crazy ideas thrown out in > answer to this. I was on vacation for a few days, so haven't been all that attentive to my mail. I have an autoload module which does something similar (note the Python 2.x syntax): import sys, inspect, traceback, re def autoload_exc(ty, va, tb): mat = re.search("name '([^']*)' is not defined", va.args[0]) if mat is not None: modulename = mat.group(1) print >> sys.stderr, "autoloading", modulename f_locals = tb.tb_frame.f_locals f_globals = tb.tb_frame.f_globals exec "import " + modulename in f_locals, f_globals exec tb.tb_frame.f_code in f_locals, f_globals else: traceback.print_exception(ty, va, tb) sys.excepthook = autoload_exc which works about as you'd expect: >>> sys.excepthook >>> math.sin(42) autoloading math -0.9165215479156338 >>> string.uppercase autoloading string 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' I can't see a lot of people wanting this (I normally have its import commented out in my PYTHONSTARTUP file), and I think it would probably be bad practice for new users of the language. Skip From davea at davea.name Wed Nov 12 10:16:15 2014 From: davea at davea.name (Dave Angel) Date: Wed, 12 Nov 2014 10:16:15 -0500 (EST) Subject: __missing__ for the top-level Python script References: Message-ID: Chris Angelico Wrote in message: > On Mon, Nov 10, 2014 at 10:31 AM, Chris Angelico wrote: >> So the semantics should be: If NameError would be raised (not >> including UnboundLocalError, which still represents an error), attempt >> to import the absent name. If successful, continue as if it had >> already been done. If ImportError is raised, suppress it and let the >> original NameError happen. > > No bites? I'd have thought there'd be a few crazy ideas thrown out in > answer to this. > > What if it's worded as a feature for interactive Python? Save you the > trouble of explicitly importing modules, by auto-importing them in > response to usage. In theory, it's as simple as adding __missing__ to > globals(), but I don't know of a way to do that for the main module. > > ChrisA > I gave it a short whirl, just trying to make __missing__ work. The type of globals () is a dict. I was able to add a __missing__:myfunct to the instance but in order to work, the __missing__ must be added as a class attribute, a method. And dict, being implemented in C, doesn't let you add class attributes. Presumably the C code does the equivalent of slots. So the next thing to try would be to try to force the module dictionary to be a userdict without slots. Then we could add the necessary method. But that would be changing the python source. I wasn't sure that was within the challenge constraints. -- DaveA From fabiofz at gmail.com Wed Nov 12 10:33:57 2014 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Wed, 12 Nov 2014 13:33:57 -0200 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> <87a943qyvn.fsf@handshake.de> <545CC204.2010301@stoneleaf.us> <8761eq424e.fsf@handshake.de> Message-ID: On Tue, Nov 11, 2014 at 5:43 AM, Ian Kelly wrote: > On Sat, Nov 8, 2014 at 3:31 PM, Gregory Ewing > wrote: > > (BTW, I'm actually surprised that this technique makes c callable. > > There must be more going on that just "look up __call__ in the class > > object", because evaluating C.__call__ just returns the descriptor > > and doesn't invoking the descriptor mechanism.) > > But of course it doesn't just lookup C.__call__, because it has to > bind the method to the instance before calling it, which means > invoking the descriptor protocol. The actual lookup is more like: > > type(a).__dict__['__call__'].__get__(a, type(a)) > -- > https://mail.python.org/mailman/listinfo/python-list > As a reference, I recently found a blog post related to that: http://lucumr.pocoo.org/2014/8/16/the-python-i-would-like-to-see/ (the Slots part comments on that). It does seem a bit counter-intuitive that this happens the way it does though, so, can someone from python-dev give some background of why that's the way it is? i.e.: instead of the approach which would seem simpler which would do getattr(a, '__call__') instead of type(a).__dict__['__call__'].__get__(a, type(a)) -- it seems to me it's mostly because of historical reasons, but I'm really curious why is it so (and if maybe it's something which python-dev would consider worth changing in the future -- not sure how much could break because of that though). Thanks and Best Regards, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Wed Nov 12 11:50:28 2014 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 12 Nov 2014 11:50:28 -0500 Subject: html page mail link to webmail program In-Reply-To: <5462B203.7070201@stoneleaf.us> References: <5462B203.7070201@stoneleaf.us> Message-ID: On Tue, Nov 11, 2014 at 8:04 PM, Ethan Furman wrote: > My wife (using a Win7 machine) will be on a web page that has a link to mail > somebody. She clicks on it, and it opens the currently installed but unused > Thunderbird. As others have mentioned, this is more a question of configuring your browser than anything involving python. That said, those links on a web page that open an email window are called "mailto" links. A google search for "open mailto links in gmail" (without the quotes) gets a bunch of general information, and if you add your wife's browser of choice to the search terms, you should get some explicit instructions for setting everything up properly. -- Jerry From larry.martell at gmail.com Wed Nov 12 11:57:10 2014 From: larry.martell at gmail.com (Larry Martell) Date: Wed, 12 Nov 2014 11:57:10 -0500 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: References: Message-ID: On Tue, Nov 11, 2014 at 10:48 AM, Larry Martell wrote: > I have a PHP app that I want to convert to django. But I want to do it > stages. All the heavy lifting is in the PHP code, so first, I want to > just use templates and views to generate the HTML, but still call the > PHP code. Then later convert the PHP to python. > > My issue is that the PHP code expects to get all it's input from the > REQUEST object and I've consumed that in the view. Is there any way I > can somehow supply that to the PHP code? > > Is there some way python can communicate like curl ... it needs to > send the request string in the body of a POST request to the URL that > will route to the PHP script and get the output back. We were all making this much harder than it is. I ended up doing this: wp = urllib.request.urlopen('http://php_page/?' + request.POST.urlencode()) pw = wp.read() From torriem at gmail.com Wed Nov 12 12:16:25 2014 From: torriem at gmail.com (Michael Torrie) Date: Wed, 12 Nov 2014 10:16:25 -0700 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: References: Message-ID: <546395E9.40902@gmail.com> On 11/11/2014 10:30 AM, Larry Martell wrote: > They are technically savvy. They are a 100% PHP shop. They have a big, > complicated app that they've been working on for 10 years. No one > there knows python or django. They want to put some new frontends on > their app. I was bought in for another project (involving Google Tag > Manager and Google Analytics), which I completed. Then they asked me > about this project. I told them they should redo their app in Flask or > Django. Hmm, this is a red flag to me (unlike the other red flags others have seen!). If the shop is entire a PHP shop, and no one knows python, then rewriting things in Python and Django is a really bad idea. Who is going to maintain the code after you're gone? PHP might be a horrible and insecure language, but at least they have a whole team of folks who can hack on it. With Python it seems like you are the only one. In this case, I'd say Python and Django, however superior, are not appropriate. I've worked in shops before where one person comes in with a new language, writes some code, then leaves, leaving us stranded as it were. I'd say the same thing about Linux in an all-Windows shop. From rosuav at gmail.com Wed Nov 12 12:49:35 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Nov 2014 04:49:35 +1100 Subject: __missing__ for the top-level Python script In-Reply-To: References: Message-ID: On Thu, Nov 13, 2014 at 1:56 AM, Skip Montanaro wrote: > sys.excepthook = autoload_exc > > I can't see a lot of people wanting this (I normally have its import > commented out in my PYTHONSTARTUP file), and I think it would probably > be bad practice for new users of the language. Interesting data point there - that you actually have it handy and choose not to use it. It's clearly designed for interactive mode, as it assumes that it can restart entire blocks of code: >>> for x in (1,2,3): ... print x ... if x==2: print os.pathsep ... 1 2 autoloading os 1 2 : 3 But that's about as good a "now go try this again" as will ever be achieved with sys.excepthook, I expect. ChrisA From rosuav at gmail.com Wed Nov 12 12:52:20 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Nov 2014 04:52:20 +1100 Subject: __missing__ for the top-level Python script In-Reply-To: References: Message-ID: On Thu, Nov 13, 2014 at 2:16 AM, Dave Angel wrote: > I gave it a short whirl, just trying to make __missing__ work. > > The type of globals () is a dict. I was able to add a > __missing__:myfunct to the instance but in order to work, the > __missing__ must be added as a class attribute, a method. And > dict, being implemented in C, doesn't let you add class > attributes. Presumably the C code does the equivalent of > slots. Yeah, I tried doing some of that kind of work and failed. Was hoping someone with more knowledge of internals could pull it off. > So the next thing to try would be to try to force the module > dictionary to be a userdict without slots. Then we could add the > necessary method. But that would be changing the python source. I > wasn't sure that was within the challenge constraints. Haha! Well, unless we can convince people that this would really be a good feature (which, somehow, I doubt...), not really. Though if it can be enabled with a tiny patch to Python and then most of the magic worked in PYTHONSTARTUP, that might do... but I suspect it'd need to be fairly specifically coded. ChrisA From ben+python at benfinney.id.au Wed Nov 12 12:54:45 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 13 Nov 2014 04:54:45 +1100 Subject: Converting a PHP app to Python + Django (was: Communicating with a PHP script (and pretending I'm a browser)) References: <546395E9.40902@gmail.com> Message-ID: <858ujg5moq.fsf_-_@benfinney.id.au> Michael Torrie writes: > If the shop is entire a PHP shop, and no one knows python, then > rewriting things in Python and Django is a really bad idea. It can be done well; see ?Transitioning from PHP to Django on the sly? . The presenter emphasises that one of the more important requirements is to convince everyone: the management, the developers, even stakeholder customers/users. > I've worked in shops before where one person comes in with a new > language, writes some code, then leaves, leaving us stranded as it > were. Right. On the other hand, I've worked in shops where the big PHP code base is seen by all as a legacy code base, and the stakeholders were quite open to being convinced to migrate ? provided a clear migration path. That's what the above presentation goes into. I recommend it. -- \ ?The double standard that exempts religious activities from | `\ almost all standards of accountability should be dismantled | _o__) once and for all.? ?Daniel Dennett, 2010-01-12 | Ben Finney From skip.montanaro at gmail.com Wed Nov 12 13:09:53 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Wed, 12 Nov 2014 13:09:53 -0500 Subject: __missing__ for the top-level Python script In-Reply-To: References: Message-ID: On Wed, Nov 12, 2014 at 12:49 PM, Chris Angelico wrote: > Interesting data point there - that you actually have it handy and > choose not to use it. And, I believe I wrote it. Can't have a worse recommendation than that. A cook who doesn't eat his own cooking. :-) I think I disabled its import sometime in the distant past when it interacted badly with something else, but for the life of me, I can't remember the details anymore. I will occasionally paste functions from Python source files into the interactive interpreter. This autoload functionality can be kind of handy there so you don't have to go back and also grab the imports from the top of the source file. Skip From rosuav at gmail.com Wed Nov 12 13:12:37 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Nov 2014 05:12:37 +1100 Subject: __missing__ for the top-level Python script In-Reply-To: References: Message-ID: On Thu, Nov 13, 2014 at 5:09 AM, Skip Montanaro wrote: > On Wed, Nov 12, 2014 at 12:49 PM, Chris Angelico wrote: >> Interesting data point there - that you actually have it handy and >> choose not to use it. > > And, I believe I wrote it. Can't have a worse recommendation than > that. A cook who doesn't eat his own cooking. :-) I think I disabled > its import sometime in the distant past when it interacted badly with > something else, but for the life of me, I can't remember the details > anymore. It doesn't ideally handle loops, as it'll go back to the top of the loop - that was my first thought. As it has to go and exec stuff all over again, it's entirely possible it'll have other issues. > I will occasionally paste functions from Python source files into the > interactive interpreter. This autoload functionality can be kind of > handy there so you don't have to go back and also grab the imports > from the top of the source file. Yeah, that does help. Of course, it can't handle a from import, but I wouldn't expect anything to catch those. ChrisA From marko at pacujo.net Wed Nov 12 13:37:04 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 12 Nov 2014 20:37:04 +0200 Subject: Communicating with a PHP script (and pretending I'm a browser) References: Message-ID: <87oascqn8v.fsf@elektro.pacujo.net> Michael Torrie : > I've worked in shops before where one person comes in with a new > language, writes some code, then leaves, leaving us stranded as it > were. Programming languages come and go. If you can handle a Philips screwdriver, you should be able to learn the use of a Torq screwdriver within a few weeks of open-minded study. Marko From ian.g.kelly at gmail.com Wed Nov 12 13:58:53 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 12 Nov 2014 11:58:53 -0700 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> <87a943qyvn.fsf@handshake.de> <545CC204.2010301@stoneleaf.us> <8761eq424e.fsf@handshake.de> Message-ID: On Wed, Nov 12, 2014 at 8:33 AM, Fabio Zadrozny wrote: > As a reference, I recently found a blog post related to that: > http://lucumr.pocoo.org/2014/8/16/the-python-i-would-like-to-see/ (the Slots > part comments on that). > > It does seem a bit counter-intuitive that this happens the way it does > though, so, can someone from python-dev give some background of why that's > the way it is? i.e.: instead of the approach which would seem simpler which > would do getattr(a, '__call__') instead of > type(a).__dict__['__call__'].__get__(a, type(a)) -- it seems to me it's > mostly because of historical reasons, but I'm really curious why is it so > (and if maybe it's something which python-dev would consider worth changing > in the future -- not sure how much could break because of that though). I'm not "someone from python-dev", but I think it's done to keep the look-up logic predictable and avoid having to call __getattribute__ and __getattr__ when looking up magic methods. For at least __getattribute__ and __getattr__ themselves we *can't* invoke those methods while trying to look them up, so there's a case to be made for consistency in that this way we don't have to remember which magic methods use __getattribute__ and which ones don't. Performance is also part of it, since these methods tend to be invoked frequently. From larry.martell at gmail.com Wed Nov 12 14:03:28 2014 From: larry.martell at gmail.com (Larry Martell) Date: Wed, 12 Nov 2014 14:03:28 -0500 Subject: Converting a PHP app to Python + Django (was: Communicating with a PHP script (and pretending I'm a browser)) In-Reply-To: <858ujg5moq.fsf_-_@benfinney.id.au> References: <546395E9.40902@gmail.com> <858ujg5moq.fsf_-_@benfinney.id.au> Message-ID: On Wed, Nov 12, 2014 at 12:54 PM, Ben Finney wrote: > Michael Torrie writes: > >> If the shop is entire a PHP shop, and no one knows python, then >> rewriting things in Python and Django is a really bad idea. > > It can be done well; see ?Transitioning from PHP to Django on the sly? > . > > The presenter emphasises that one of the more important requirements is > to convince everyone: the management, the developers, even stakeholder > customers/users. > >> I've worked in shops before where one person comes in with a new >> language, writes some code, then leaves, leaving us stranded as it >> were. > > Right. On the other hand, I've worked in shops where the big PHP code > base is seen by all as a legacy code base, and the stakeholders were > quite open to being convinced to migrate ? provided a clear migration > path. > > That's what the above presentation goes into. I recommend it. Thanks Ben! From nad at acm.org Wed Nov 12 14:52:04 2014 From: nad at acm.org (Ned Deily) Date: Wed, 12 Nov 2014 11:52:04 -0800 Subject: ssl error with the python mac binary References: Message-ID: In article , Paul Wiseman wrote: > I'm currently using the installer with py2app to make a distributable > app that targets 10.5+ (including ppc). To save having more than one > build I use this for all downloads. Although I'm starting to consider > making a second 32/64 distributable. Are there many major drawbacks > for distributing this i386/ppc binary for all versions of OSX up 10.9 > and 10.10? For a standalone app, not really. The main difference is that, by using the older 10.5 ABI, a few functions in the os module are not available (if they were implemented first in OS X 10.6 or later) and/or they may work a little differently. AFAIK, the most impactful difference, by far, is the OpenSSL version difference you have run into. Up to now, I don't recall any compatibility problems with 10.5 ABI programs running on later versions of OS X or, for the most part, mixing extension modules compiled to later ABIs with a 10.5 Python, although there might be issues with mixing versions of C++ modules (Python and its standard library do not use C++ themselves). But, of course, there's no guarantee that something won't break in a future release of OS X. So far, so good. > That's great news! Thanks for this! I've always found building things > on mac a huge pain and wasn't much looking forward to the prospect of > trying to build a 32/ppc python build on a 64 bit 10.10 machine (would > that even be possible?). It's possible: I do it. But I cheat a bit: I have 10.5 running in a virtual machine on a 10.10 host. In theory, it's possible to build natively on 10.10. The trick is getting a version of Xcode 3 installed on 10.10 since support for building ppc archs was removed in Xcode 4. I also cheat a bit there: I happen to still have copies of Xcode 3.1.4 and 3.2.6 installed on 10.10 because I made sure to preserve them through upgrades from 10.6 days. IIRC, directly installing the necessary components from 3.2.6 on newer systems would require some hacking. Then you have to be really vigilant that the build never strays from the old SDK and tools, which is not something we claim to support at the moment. The VM approach is quite safe and reliable. -- Ned Deily, nad at acm.org From tjreedy at udel.edu Wed Nov 12 15:06:43 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Nov 2014 15:06:43 -0500 Subject: Moving a window on the screen In-Reply-To: <87a9418mef.fsf@gmail.com> References: <545b321a$0$2396$426a34cc@news.free.fr> <545b3cd8$0$2306$426a34cc@news.free.fr> <87oash8xbd.fsf@gmail.com> <87a9418mef.fsf@gmail.com> Message-ID: On 11/8/2014 3:31 PM, Akira Li wrote: > Terry Reedy writes: >> On my Win7 machine, your complicated code is much worse as it causes >> the window to jump about every half second After cutting and pasting again, I do not see the jumps. I do not have the code I ran before to compare. I do remember that I deleted, added back, and re-deleted the phase correction, and ran a couple of times each, to be sure that the aberrant behavior was reproducible in general effect. -- Terry Jan Reedy From anton.schattenfeld at gmail.com Wed Nov 12 15:31:28 2014 From: anton.schattenfeld at gmail.com (Anton) Date: Wed, 12 Nov 2014 12:31:28 -0800 (PST) Subject: Python Style Question In-Reply-To: <54521c8f$0$12982$c3e8da3$5496439d@news.astraweb.com> References: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> <54521c8f$0$12982$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thursday, October 30, 2014 4:10:23 AM UTC-7, Steven D'Aprano wrote: > I don't particularly like either version. I prefer this: > > def load_int(obj): > if isinstance(obj, int): > # Case 1), an int, e.g. 7 > return obj > elif isinstance(obj, str): > # Case 2) and 3), a str or JSON serialised int. > # E.g. '7' or '"7"'. > try: > return int(obj) > except ValueError: > return int(json.loads(obj)) > raise TypeError('require int or str, got %s' % type(obj).__name__) This will definitely work, but then I don't see a benefit of EAFP and duck-typing: Let's say I have a class class FakeInt(object): def __int__(self): return 42 In this case: >>> fi = FakeInt() >>> isinstance(fi, int) False >>> int(fi) 42 So probably I need to rephrase 1) something, that I can cast to int. Same for > elif isinstance(obj, str): As long as it behaves like string (can be some sort if bytearray). For particularly this case, it will probably won't happen, but again, it looks like an overloaded function with strongly typed argument. or a functional form: > def tolerant_load_int(obj, default=None): > try: > return load_int(obj) > except (ValueError, TypeError): > return default > values = [n for n in map(tolerant_load_int, l) if n is not None] > # alternative to using map > values = [n for n in (tolerant_load_int(obj) for obj in l) if n is not None] I like the idea of wrapping it up in a function and being able to use it in these functional forms. From anton.schattenfeld at gmail.com Wed Nov 12 15:53:30 2014 From: anton.schattenfeld at gmail.com (Anton) Date: Wed, 12 Nov 2014 12:53:30 -0800 (PST) Subject: I love assert In-Reply-To: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: On Tuesday, November 11, 2014 11:41:06 AM UTC-8, Peter Cacioppi wrote: > I get the impression that most Pythonistas aren't as habituated with assert statements as I am. Is that just a misimpression on my part? If not, is there a good reason to assert less with Python than other languages? > > As far as I can tell, Python supports assert perfectly well. When run with the optimization flagging, the asserts are truly removed. > > I think one needs to take care with some basic assert coding - it's not a substitute for unit tests, it doesn't absolve you of normal exception responsibilities, and, most of all, it should be used for passive inspection and not action. But given these guidelines, I still find it very useful as "active comments". I am not sure how and when you use assert, but something that stops me from using assert is that in many cases I would use them to 1) Check type of an incoming argument/returned value 2) Check value of an incoming argument/returned value But the issues I can see here is that assert throws AssertError, while there is a specialized error for each of the case: 1) TypeError 2) ValueError. Moreover for the 1) case it makes it impossible to dynamically substitute an object with another object that implements the same interface. From john_ladasky at sbcglobal.net Wed Nov 12 16:02:33 2014 From: john_ladasky at sbcglobal.net (John Ladasky) Date: Wed, 12 Nov 2014 13:02:33 -0800 (PST) Subject: How about some syntactic sugar for " __name__ == '__main__' "? Message-ID: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> I have taught Python to several students over the past few years. As I have worked with my students, I find myself bothered by the programming idiom that we use to determine whether a module is being executed or merely imported: "if __name__ == '__main__':" The use of two dunder tokens -- one as a name in a namespace, and the other as a string, is intimidating. It exposes too much of Python's guts. As such, I think that it is less Pythonic than we might want. Myself, I've been programming in Python for a decade, and I still haven't dug very deeply into what exactly __name__ means or does. I would like to start a discussion about whether Python should include a function which executes this evaluation, and hides all of the unfriendly dunderish details. And if that's a good idea, I would invite a discussion of how, exactly, it should be implemented. I'm nowhere near proposing a PEP, but that may come later. Thanks for your thoughts. From joel.goldstick at gmail.com Wed Nov 12 16:07:55 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 12 Nov 2014 16:07:55 -0500 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> Message-ID: On Wed, Nov 12, 2014 at 4:02 PM, John Ladasky wrote: > I have taught Python to several students over the past few years. As I have worked with my students, I find myself bothered by the programming idiom that we use to determine whether a module is being executed or merely imported: > > "if __name__ == '__main__':" > > The use of two dunder tokens -- one as a name in a namespace, and the other as a string, is intimidating. It exposes too much of Python's guts. As such, I think that it is less Pythonic than we might want. Myself, I've been programming in Python for a decade, and I still haven't dug very deeply into what exactly __name__ means or does. > > I would like to start a discussion about whether Python should include a function which executes this evaluation, and hides all of the unfriendly dunderish details. And if that's a good idea, I would invite a discussion of how, exactly, it should be implemented. I'm nowhere near proposing a PEP, but that may come later. > > Thanks for your thoughts. > -- > https://mail.python.org/mailman/listinfo/python-list How about a decorator? -- Joel Goldstick http://joelgoldstick.com From ethan at stoneleaf.us Wed Nov 12 16:19:45 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 12 Nov 2014 13:19:45 -0800 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> Message-ID: <5463CEF1.1040008@stoneleaf.us> On 11/12/2014 01:02 PM, John Ladasky wrote: > > I would like to start a discussion about whether Python should include > a function which executes this evaluation, and hides all of the unfriendly > dunderish details. And if that's a good idea, I would invite a discussion > of how, exactly, it should be implemented. I'm nowhere near proposing a > PEP, but that may come later. I believe this has come up before. You might check the Python-Ideas list to see. If you do, please write up a summary of the past discussions so we can move forward instead of rehashing the same things as before. -- ~Ethan~ From john_ladasky at sbcglobal.net Wed Nov 12 16:17:58 2014 From: john_ladasky at sbcglobal.net (John Ladasky) Date: Wed, 12 Nov 2014 13:17:58 -0800 (PST) Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> Message-ID: It appears that I'm not the first person to have thoughts along these lines. Here's a relevant article: http://aliles.tumblr.com/post/7455032885/sugar-for-pythons-main From torriem at gmail.com Wed Nov 12 16:28:52 2014 From: torriem at gmail.com (Michael Torrie) Date: Wed, 12 Nov 2014 14:28:52 -0700 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: <87oascqn8v.fsf@elektro.pacujo.net> References: <87oascqn8v.fsf@elektro.pacujo.net> Message-ID: <5463D114.8050304@gmail.com> On 11/12/2014 11:37 AM, Marko Rauhamaa wrote: > Michael Torrie : > >> I've worked in shops before where one person comes in with a new >> language, writes some code, then leaves, leaving us stranded as it >> were. > > Programming languages come and go. If you can handle a Philips > screwdriver, you should be able to learn the use of a Torq screwdriver > within a few weeks of open-minded study. Sure, but that's not a good enough reason to switch to Python, as excellent as it is. From ckaynor at zindagigames.com Wed Nov 12 16:33:51 2014 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Wed, 12 Nov 2014 13:33:51 -0800 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> Message-ID: On Wed, Nov 12, 2014 at 1:07 PM, Joel Goldstick wrote: > On Wed, Nov 12, 2014 at 4:02 PM, John Ladasky > wrote: > > I have taught Python to several students over the past few years. As I > have worked with my students, I find myself bothered by the programming > idiom that we use to determine whether a module is being executed or merely > imported: > > > > "if __name__ == '__main__':" > > > > The use of two dunder tokens -- one as a name in a namespace, and the > other as a string, is intimidating. It exposes too much of Python's guts. > As such, I think that it is less Pythonic than we might want. Myself, I've > been programming in Python for a decade, and I still haven't dug very > deeply into what exactly __name__ means or does. > > > > I would like to start a discussion about whether Python should include a > function which executes this evaluation, and hides all of the unfriendly > dunderish details. And if that's a good idea, I would invite a discussion > of how, exactly, it should be implemented. I'm nowhere near proposing a > PEP, but that may come later. > > > > Thanks for your thoughts. > > How about a decorator? > A decorator is an interesting idea, and should be easy to implement (only lightly tested): def main(func): if func.__module__ == "__main__": func() return func # The return could be omitted to block the function from being manually called after import. Just decorate the "main" function of the script with that, and it will be automatically called when ran as a script, but not when imported as a module. -------------- next part -------------- An HTML attachment was scrubbed... URL: From marko at pacujo.net Wed Nov 12 16:41:08 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 12 Nov 2014 23:41:08 +0200 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: <87a93wqeq3.fsf@elektro.pacujo.net> Anton : > I am not sure how and when you use assert, but something that stops me > from using assert is that in many cases I would use them to > 1) Check type of an incoming argument/returned value > 2) Check value of an incoming argument/returned value You use asserts to boldly state that the asserted condition never fails. If it should fail anyway, the world could come tumbling down and you would hang your head in shame. Asserts help the reader of the code understand why some possibilities are not considered by the code. They are not considered because the writer of the code asserts they are not really possible. Asserts help not only lay the blame to the writer of the code but might also make it easier to troubleshoot failures. I use asserts sparingly, just like comments (which asserts are). I use them to communicate nonobvious truths to the future maintainer of the code. For example, instead of # never reached I will write assert False Or I might indicate the exhaustion of possibilities: if status == OK: ... elif status == ERROR: ... else: assert status == WARNING ... Marko From ian.g.kelly at gmail.com Wed Nov 12 16:51:57 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 12 Nov 2014 14:51:57 -0700 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> Message-ID: On Wed, Nov 12, 2014 at 2:33 PM, Chris Kaynor wrote: > A decorator is an interesting idea, and should be easy to implement (only > lightly tested): > > def main(func): > if func.__module__ == "__main__": > func() > return func # The return could be omitted to block the function from > being manually called after import. > > Just decorate the "main" function of the script with that, and it will be > automatically called when ran as a script, but not when imported as a > module. This calls it at the wrong time, though. Typically the way this idiom is used is that you define everything you need (functions, classes, etc.) within the main script, and then you call the main function. This would call the main function at the time it's defined, when other things in the main script may not have been defined yet. One could place the main function last, but it would be preferable not to be forced. This also calls the function before it's been assigned to the global, which would prevent recursive calls of the main function. Instead of a decorator, I'd prefer to just have this: def main(func, *args, **kwargs): if func.__module__ == '__main__': func(*args, **kwargs) And then I can easily invoke it wherever I want in the main script. From ethan at stoneleaf.us Wed Nov 12 16:52:48 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 12 Nov 2014 13:52:48 -0800 Subject: I love assert In-Reply-To: <87a93wqeq3.fsf@elektro.pacujo.net> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> Message-ID: <5463D6B0.2010709@stoneleaf.us> On 11/12/2014 01:41 PM, Marko Rauhamaa wrote: > > Or I might indicate the exhaustion of possibilities: > > if status == OK: > ... > elif status == ERROR: > ... > else: > assert status == WARNING > ... And here's a nice example of what one should NOT do. Imagine that a new status, CONFUSED is added, the above code is not modified to handle it, and for whatever reason the program is being run optimized -- the assert is not there, and CONFUSED is treated the same as WARNING. -- ~Ethan~ From marko at pacujo.net Wed Nov 12 16:52:41 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 12 Nov 2014 23:52:41 +0200 Subject: How about some syntactic sugar for " __name__ == '__main__' "? References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> Message-ID: <8761ekqe6u.fsf@elektro.pacujo.net> John Ladasky : > I find myself bothered by the programming idiom that we use to > determine whether a module is being executed or merely imported: > > "if __name__ == '__main__':" I find the idiom cute and loveably silly. A typing tongue twister of sorts. That boilerplate is far less cumbersome than, say, in Java. > Myself, I've been programming in Python for a decade, and I still > haven't dug very deeply into what exactly __name__ means or does. The idiom allows you to include a main function in auxiliary modules. When imported, the module acts as a library. When executed, it acts as a command. I have done this a couple of times IRL. > I would like to start a discussion about whether Python should include > a function which executes this evaluation, and hides all of the > unfriendly dunderish details. Probably not. Idioms are important in that they are immediately spotted by a casual reader of the code. However ugly you consider those two lines, it will not waste a measurable amount of your precious time to begin your brand new project by typing: import sys def main(): pass if __name__ == "__main__": main() Yes, I always type those in again. I don't copy them over as I do, say, Java main programs or static HTML pages. Marko From skip.montanaro at gmail.com Wed Nov 12 16:55:04 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Wed, 12 Nov 2014 15:55:04 -0600 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> Message-ID: > def main(func): > if func.__module__ == "__main__": > func() > return func # The return could be omitted to block the function from > being manually called after import. > > Just decorate the "main" function of the script with that, and it will be > automatically called when ran as a script, but not when imported as a > module. This won't work (I don't think) if you want to call the "main" function from another place (like the interpreter prompt). Skip From marko at pacujo.net Wed Nov 12 16:56:18 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 12 Nov 2014 23:56:18 +0200 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> Message-ID: <87y4rgozgd.fsf@elektro.pacujo.net> Ethan Furman : > On 11/12/2014 01:41 PM, Marko Rauhamaa wrote: >> >> Or I might indicate the exhaustion of possibilities: >> >> if status == OK: >> ... >> elif status == ERROR: >> ... >> else: >> assert status == WARNING >> ... > > And here's a nice example of what one should NOT do. Imagine that a > new status, CONFUSED is added, the above code is not modified to > handle it, and for whatever reason the program is being run optimized > -- the assert is not there, and CONFUSED is treated the same as > WARNING. How would it be better if you removed the assert then? Marko From anschatten at gmail.com Wed Nov 12 17:00:24 2014 From: anschatten at gmail.com (Anton) Date: Wed, 12 Nov 2014 14:00:24 -0800 (PST) Subject: I love assert In-Reply-To: <87a93wqeq3.fsf@elektro.pacujo.net> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> Message-ID: On Wednesday, November 12, 2014 1:41:20 PM UTC-8, Marko Rauhamaa wrote: > Asserts help the reader of the code understand why some possibilities > are not considered by the code. They are not considered because the > writer of the code asserts they are not really possible. I can see how assert statement can point out what should not happen, can you give an example. > I use asserts sparingly, just like comments (which asserts are). I use > them to communicate nonobvious truths to the future maintainer of the > code. > > Or I might indicate the exhaustion of possibilities: > > if status == OK: > ... > elif status == ERROR: > ... > else: > assert status == WARNING > ... Could you elaborate your example here? Basically, this type of error checking does not look familiar to me in Python code. In C when one works with descriptors and has to check status codes after every call it looks natural. Maybe I just haven't used it this way, so I'd really appreciate a more specific use case. From anschatten at gmail.com Wed Nov 12 17:04:49 2014 From: anschatten at gmail.com (Anton) Date: Wed, 12 Nov 2014 14:04:49 -0800 (PST) Subject: I love assert In-Reply-To: References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> Message-ID: On Wednesday, November 12, 2014 2:00:35 PM UTC-8, Anton wrote: > On Wednesday, November 12, 2014 1:41:20 PM UTC-8, Marko Rauhamaa wrote: > > Asserts help the reader of the code understand why some possibilities > > are not considered by the code. They are not considered because the > > writer of the code asserts they are not really possible. > I can see how assert statement can point out what should not happen, can you give an example. I messed up, meant to say: I can see how assert statement can point out what should not happen, can you give an example when a single assert statement would explain why it should never happen? From ian.g.kelly at gmail.com Wed Nov 12 17:04:16 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 12 Nov 2014 15:04:16 -0700 Subject: I love assert In-Reply-To: <87y4rgozgd.fsf@elektro.pacujo.net> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> Message-ID: On Wed, Nov 12, 2014 at 2:56 PM, Marko Rauhamaa wrote: > Ethan Furman : > >> On 11/12/2014 01:41 PM, Marko Rauhamaa wrote: >>> >>> Or I might indicate the exhaustion of possibilities: >>> >>> if status == OK: >>> ... >>> elif status == ERROR: >>> ... >>> else: >>> assert status == WARNING >>> ... >> >> And here's a nice example of what one should NOT do. Imagine that a >> new status, CONFUSED is added, the above code is not modified to >> handle it, and for whatever reason the program is being run optimized >> -- the assert is not there, and CONFUSED is treated the same as >> WARNING. > > How would it be better if you removed the assert then? You don't need to remove it. Just reorganize it to make sure it indicates actual exhaustion of possibilities. E.g. using the "assert False" pattern from your post: if status == OK: ... elif status == ERROR: ... elif status == WARNING: ... else: assert False From ian.g.kelly at gmail.com Wed Nov 12 17:07:19 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 12 Nov 2014 15:07:19 -0700 Subject: I love assert In-Reply-To: References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> Message-ID: On Wed, Nov 12, 2014 at 3:04 PM, Ian Kelly wrote: > On Wed, Nov 12, 2014 at 2:56 PM, Marko Rauhamaa wrote: >> How would it be better if you removed the assert then? > > You don't need to remove it. Just reorganize it to make sure it > indicates actual exhaustion of possibilities. E.g. using the "assert > False" pattern from your post: > > if status == OK: > ... > elif status == ERROR: > ... > elif status == WARNING: > ... > else: > assert False Although to be honest I'd rather use something like "raise RuntimeError('Unreachable code reached')" than "assert False" here. If the expectation is that the code will never be executed, then there's no reason to ever optimize it out. From ckaynor at zindagigames.com Wed Nov 12 17:09:09 2014 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Wed, 12 Nov 2014 14:09:09 -0800 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> Message-ID: On Wed, Nov 12, 2014 at 1:51 PM, Ian Kelly wrote: > On Wed, Nov 12, 2014 at 2:33 PM, Chris Kaynor > wrote: > > A decorator is an interesting idea, and should be easy to implement (only > > lightly tested): > > > > def main(func): > > if func.__module__ == "__main__": > > func() > > return func # The return could be omitted to block the function from > > being manually called after import. > > > > Just decorate the "main" function of the script with that, and it will be > > automatically called when ran as a script, but not when imported as a > > module. > > This calls it at the wrong time, though. Typically the way this idiom > is used is that you define everything you need (functions, classes, > etc.) within the main script, and then you call the main function. > This would call the main function at the time it's defined, when other > things in the main script may not have been defined yet. One could > place the main function last, but it would be preferable not to be > forced. > > I was thinking along the lines of replacing: if __name__ == "__main__": <<>> with @main def myFunction() <<<> Both blocks of code will be called at the same time. > This also calls the function before it's been assigned to the global, > which would prevent recursive calls of the main function. > > Instead of a decorator, I'd prefer to just have this: > > def main(func, *args, **kwargs): > if func.__module__ == '__main__': > func(*args, **kwargs) > > And then I can easily invoke it wherever I want in the main script. > On Wed, Nov 12, 2014 at 1:55 PM, Skip Montanaro wrote: > > This won't work (I don't think) if you want to call the "main" function from another place (like the interpreter prompt). With the plain if block, you absolutely cannot call it elsewhere, without wrapping it in a function anyways. There is the issue, as mentioned by Ian, that the function will not be in the module namespace at the time it is called. That does block it, however it is also easy to work around: make the main function extremely simple, such as just calling another function. -------------- next part -------------- An HTML attachment was scrubbed... URL: From anschatten at gmail.com Wed Nov 12 17:13:59 2014 From: anschatten at gmail.com (Anton) Date: Wed, 12 Nov 2014 14:13:59 -0800 (PST) Subject: I love assert In-Reply-To: References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> Message-ID: <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> On Wednesday, November 12, 2014 2:05:17 PM UTC-8, Ian wrote: > On Wed, Nov 12, 2014 at 2:56 PM, Marko Rauhamaa wrote: > > Ethan Furman: > > > >> On 11/12/2014 01:41 PM, Marko Rauhamaa wrote: > >>> > >>> Or I might indicate the exhaustion of possibilities: > >>> > >>> if status == OK: > >>> ... > >>> elif status == ERROR: > >>> ... > >>> else: > >>> assert status == WARNING > >>> ... > >> > >> And here's a nice example of what one should NOT do. Imagine that a > >> new status, CONFUSED is added, the above code is not modified to > >> handle it, and for whatever reason the program is being run optimized > >> -- the assert is not there, and CONFUSED is treated the same as > >> WARNING. > > > > How would it be better if you removed the assert then? > > You don't need to remove it. Just reorganize it to make sure it > indicates actual exhaustion of possibilities. E.g. using the "assert > False" pattern from your post: > > if status == OK: > ... > elif status == ERROR: > ... > elif status == WARNING: > ... > else: > assert False If the code is run optimized and asserts are ignore CONFUSED statement would still not be handled and you will not know about it. I would do something like: if status == OK: ... elif status == ERROR: ... elif status == WARNING: ... else: raise RuntimeError("Unknown errorno") Or if it is at the end of the function, then: if status == OK: ... elif status == ERROR: ... elif status == WARNING: ... raise RuntimeError("Unknown errorno") unless there is a customer exception type I can use for this situation. From ian.g.kelly at gmail.com Wed Nov 12 17:19:09 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 12 Nov 2014 15:19:09 -0700 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> Message-ID: On Wed, Nov 12, 2014 at 3:09 PM, Chris Kaynor wrote: > I was thinking along the lines of replacing: > > if __name__ == "__main__": > <<>> > > with > > @main > def myFunction() > <<<> > > Both blocks of code will be called at the same time. 99% of the time the content of <<>> is just "main()", so then you're proposing replacing this: if __name__ == "__main__": main() with this: @main def myFunction(): my_main() Which feels redundant to me. Why have a function here that does nothing but call another function? I think if this is the goal then a simple predicate would be clearer: if is_main_module(): main() From marko at pacujo.net Wed Nov 12 17:34:49 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 13 Nov 2014 00:34:49 +0200 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> Message-ID: <87ppcsoxo6.fsf@elektro.pacujo.net> Anton : > I can see how assert statement can point out what should not happen, > can you give an example when a single assert statement would explain > why it should never happen? Asserts don't communicate justifications. They simply assert something to be the case, period. Any other elaborations must go in comments. Marko From ian.g.kelly at gmail.com Wed Nov 12 17:41:22 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 12 Nov 2014 15:41:22 -0700 Subject: I love assert In-Reply-To: <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> Message-ID: On Wed, Nov 12, 2014 at 3:13 PM, Anton wrote: > On Wednesday, November 12, 2014 2:05:17 PM UTC-8, Ian wrote: >> You don't need to remove it. Just reorganize it to make sure it >> indicates actual exhaustion of possibilities. E.g. using the "assert >> False" pattern from your post: >> >> if status == OK: >> ... >> elif status == ERROR: >> ... >> elif status == WARNING: >> ... >> else: >> assert False > > If the code is run optimized and asserts are ignore CONFUSED statement would still not be handled and you will not know about it. > I would do something like: There's no way to make the CONFUSED status be handled without actually changing the code. The difference is that this version will not incorrectly treat CONFUSED as WARNING; it just won't do anything at all if the code is optimized. From rosuav at gmail.com Wed Nov 12 17:43:22 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Nov 2014 09:43:22 +1100 Subject: I love assert In-Reply-To: References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: On Thu, Nov 13, 2014 at 7:53 AM, Anton wrote: > I am not sure how and when you use assert, but something that stops me from using assert is that in many cases I would use them to > 1) Check type of an incoming argument/returned value > 2) Check value of an incoming argument/returned value > But the issues I can see here is that assert throws AssertError, while there is a specialized error for each of the case: 1) TypeError 2) ValueError. > Moreover for the 1) case it makes it impossible to dynamically substitute an object with another object that implements the same interface. The fact that there's a better exception type that's obviously more correct is a strong hint that you shouldn't use assert for these two cases. And your "Moreover" concern is a strong hint that you shouldn't be checking at all :) If you need to check this sort of thing, an explicit "if condition: raise SomeError('message')" construct is a lot more useful. Otherwise, there's no reason to have the line of code at all. ChrisA From ethan at stoneleaf.us Wed Nov 12 17:47:06 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 12 Nov 2014 14:47:06 -0800 Subject: I love assert In-Reply-To: References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> Message-ID: <5463E36A.5050002@stoneleaf.us> On 11/12/2014 02:41 PM, Ian Kelly wrote: > On Wed, Nov 12, 2014 at 3:13 PM, Anton wrote: >> On Wednesday, November 12, 2014 2:05:17 PM UTC-8, Ian wrote: >>> You don't need to remove it. Just reorganize it to make sure it >>> indicates actual exhaustion of possibilities. E.g. using the "assert >>> False" pattern from your post: >>> >>> if status == OK: >>> ... >>> elif status == ERROR: >>> ... >>> elif status == WARNING: >>> ... >>> else: >>> assert False >> >> If the code is run optimized and asserts are ignore CONFUSED statement would still not be handled and you will not know about it. >> I would do something like: > > There's no way to make the CONFUSED status be handled without actually > changing the code. The difference is that this version will not > incorrectly treat CONFUSED as WARNING; it just won't do anything at > all if the code is optimized. So, a different wrong thing, but still a wrong thing. ;) -- ~Ethan~ From marko at pacujo.net Wed Nov 12 17:47:31 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 13 Nov 2014 00:47:31 +0200 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> Message-ID: <87lhngox30.fsf@elektro.pacujo.net> Ian Kelly : > Although to be honest I'd rather use something like "raise > RuntimeError('Unreachable code reached')" than "assert False" here. If > the expectation is that the code will never be executed, then there's > no reason to ever optimize it out. Asserts have nothing to do with them being optimized out. Asserts are communication. Apart from idiomatic style, there is no difference between # never reached assert False raise RuntimeError('Unreachable code reached') 1 / 0 print("Hello world") since, after all, that line is never reached! Out of these variants, I find assert False to be the most tasteful. It is concise, to the point and provided by the core language. If it didn't exist, I'd have to resort to one of the other alternatives. Marko From anschatten at gmail.com Wed Nov 12 17:48:38 2014 From: anschatten at gmail.com (Anton) Date: Wed, 12 Nov 2014 14:48:38 -0800 (PST) Subject: I love assert In-Reply-To: References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> Message-ID: <28e159ff-3d64-4793-9082-05cf1553c7c2@googlegroups.com> On Wednesday, November 12, 2014 2:42:19 PM UTC-8, Ian wrote: > On Wed, Nov 12, 2014 at 3:13 PM, Anton wrote: > > If the code is run optimized and asserts are ignore CONFUSED statement would still not be handled and you will not know about it. > > I would do something like: > > There's no way to make the CONFUSED status be handled without actually > changing the code. The difference is that this version will not > incorrectly treat CONFUSED as WARNING; it just won't do anything at > all if the code is optimized. Right, but the goal is not to make the CONFUSED status be handled without coding, but to be notified about an unknown status code and act accordingly. From ethan at stoneleaf.us Wed Nov 12 17:56:46 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 12 Nov 2014 14:56:46 -0800 Subject: I love assert In-Reply-To: <87lhngox30.fsf@elektro.pacujo.net> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <87lhngox30.fsf@elektro.pacujo.net> Message-ID: <5463E5AE.1060701@stoneleaf.us> On 11/12/2014 02:47 PM, Marko Rauhamaa wrote: > Ian Kelly : > >> Although to be honest I'd rather use something like "raise >> RuntimeError('Unreachable code reached')" than "assert False" here. If >> the expectation is that the code will never be executed, then there's >> no reason to ever optimize it out. > > Asserts have nothing to do with them being optimized out. Asserts are > communication. Asserts are code that can stop your program. That's a bit more than just communication. And your example of how you use asserts shows a bad way to use them, which has been explained. Apparently you refuse to learn from that, but hopefully somebody else will. -- ~Ethan~ From rosuav at gmail.com Wed Nov 12 17:58:47 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Nov 2014 09:58:47 +1100 Subject: I love assert In-Reply-To: <87lhngox30.fsf@elektro.pacujo.net> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <87lhngox30.fsf@elektro.pacujo.net> Message-ID: On Thu, Nov 13, 2014 at 9:47 AM, Marko Rauhamaa wrote: > Apart from idiomatic style, there is no difference between > > # never reached > > assert False > > raise RuntimeError('Unreachable code reached') > > 1 / 0 > > print("Hello world") > > since, after all, that line is never reached! If it truly is never reached, there's no difference between any of the above and "pass". (With the possible exception of 1/0, which might plausibly be optimized to a constant, which would mean it'd throw an error at compile time.) But what if, one day, it is reached? What should happen? RuntimeError implies that there's an error that couldn't be detected until run time. AssertionError might not get raised. Printing "Hello world" to standard out will almost certainly be misinterpreted. ZeroDivisionError makes almost no sense for "shouldn't happen". Think about what your code ought to do *if it is reached*, because if you really don't care about that case, you won't have a line of code at all. ChrisA From ian.g.kelly at gmail.com Wed Nov 12 18:02:21 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 12 Nov 2014 16:02:21 -0700 Subject: I love assert In-Reply-To: <28e159ff-3d64-4793-9082-05cf1553c7c2@googlegroups.com> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> <28e159ff-3d64-4793-9082-05cf1553c7c2@googlegroups.com> Message-ID: On Wed, Nov 12, 2014 at 3:48 PM, Anton wrote: > On Wednesday, November 12, 2014 2:42:19 PM UTC-8, Ian wrote: >> On Wed, Nov 12, 2014 at 3:13 PM, Anton wrote: >> > If the code is run optimized and asserts are ignore CONFUSED statement would still not be handled and you will not know about it. >> > I would do something like: >> >> There's no way to make the CONFUSED status be handled without actually >> changing the code. The difference is that this version will not >> incorrectly treat CONFUSED as WARNING; it just won't do anything at >> all if the code is optimized. > > Right, but the goal is not to make the CONFUSED status be handled without coding, but to be notified about an unknown status code and act accordingly. Sure, which is why you and I have both suggested raising a RuntimeError instead. From marko at pacujo.net Wed Nov 12 18:01:07 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 13 Nov 2014 01:01:07 +0200 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> <28e159ff-3d64-4793-9082-05cf1553c7c2@googlegroups.com> Message-ID: <87h9y4owgc.fsf@elektro.pacujo.net> Anton : > Right, but the goal is not to make the CONFUSED status be handled > without coding, but to be notified about an unknown status code and > act accordingly. Asserts are not about notification, checking or optimization. They are about communicating what's going on in the programmer's mind. They are comments. So why use asserts instead of comments? Asserts *could* help in fixing bugs: 1. An assertion failure immediately, unambiguously, declares even to customer service representatives that this is a terrible bug and should be brought to R&D's attention instead of hazing the poor customer with standard questions ("have you updated?", "have you rebooted?"). 2. An assertion failure probably gives the developer an very good clue as to what has gone wrong. There is a good chance of quickly finding an accurate analysis and fix to the bug. Marko From ian.g.kelly at gmail.com Wed Nov 12 18:05:46 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 12 Nov 2014 16:05:46 -0700 Subject: I love assert In-Reply-To: <87lhngox30.fsf@elektro.pacujo.net> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <87lhngox30.fsf@elektro.pacujo.net> Message-ID: On Wed, Nov 12, 2014 at 3:47 PM, Marko Rauhamaa wrote: > Ian Kelly : > >> Although to be honest I'd rather use something like "raise >> RuntimeError('Unreachable code reached')" than "assert False" here. If >> the expectation is that the code will never be executed, then there's >> no reason to ever optimize it out. > > Asserts have nothing to do with them being optimized out. Asserts are > communication. > > Apart from idiomatic style, there is no difference between > > # never reached > > assert False > > raise RuntimeError('Unreachable code reached') If the purpose is communication, then the comment is most effective, as it can easily convey anything you want. If the purpose is to detect programming errors, then the RuntimeError is most effective, as it will always raise an error in the event it is reached. assert False is a strange hybrid of the two that is less effective at both purposes. From rosuav at gmail.com Wed Nov 12 18:10:42 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Nov 2014 10:10:42 +1100 Subject: I love assert In-Reply-To: References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> <28e159ff-3d64-4793-9082-05cf1553c7c2@googlegroups.com> Message-ID: On Thu, Nov 13, 2014 at 10:02 AM, Ian Kelly wrote: > On Wed, Nov 12, 2014 at 3:48 PM, Anton wrote: >> On Wednesday, November 12, 2014 2:42:19 PM UTC-8, Ian wrote: >>> On Wed, Nov 12, 2014 at 3:13 PM, Anton wrote: >>> > If the code is run optimized and asserts are ignore CONFUSED statement would still not be handled and you will not know about it. >>> > I would do something like: >>> >>> There's no way to make the CONFUSED status be handled without actually >>> changing the code. The difference is that this version will not >>> incorrectly treat CONFUSED as WARNING; it just won't do anything at >>> all if the code is optimized. >> >> Right, but the goal is not to make the CONFUSED status be handled without coding, but to be notified about an unknown status code and act accordingly. > > Sure, which is why you and I have both suggested raising a RuntimeError instead. Or, in as many cases as possible, raise an implicit KeyError and save yourself a lot of typing. Any time these kinds of elif trees can be turned into dict lookups, you get non-assert error checking for free. ChrisA From marko at pacujo.net Wed Nov 12 18:12:44 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 13 Nov 2014 01:12:44 +0200 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <87lhngox30.fsf@elektro.pacujo.net> Message-ID: <87d28sovwz.fsf@elektro.pacujo.net> Ian Kelly : > On Wed, Nov 12, 2014 at 3:47 PM, Marko Rauhamaa wrote: >> Asserts have nothing to do with them being optimized out. Asserts are >> communication. >> >> Apart from idiomatic style, there is no difference between >> >> # never reached >> >> assert False >> >> raise RuntimeError('Unreachable code reached') > > If the purpose is communication, then the comment is most effective, > as it can easily convey anything you want. If the purpose is to detect > programming errors, then the RuntimeError is most effective, as it > will always raise an error in the event it is reached. > > assert False is a strange hybrid of the two that is less effective at > both purposes. If assert weren't there, I would likely choose one of those two alternatives. But assert is there so there's no reason to avoid it. Marko From tjreedy at udel.edu Wed Nov 12 18:19:53 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Nov 2014 18:19:53 -0500 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> Message-ID: On 11/12/2014 4:02 PM, John Ladasky wrote: > I have taught Python to several students over the past few years. As > I have worked with my students, I find myself bothered by the > programming idiom that we use to determine whether a module is being > executed or merely imported: > > "if __name__ == '__main__':" > > The use of two dunder tokens -- one as a name in a namespace, and the > other as a string, is intimidating. It exposes too much of Python's > guts. As such, I think that it is less Pythonic than we might want. > Myself, I've been programming in Python for a decade, and I still > haven't dug very deeply into what exactly __name__ means or does. > > I would like to start a discussion about whether Python should > include a function which executes this evaluation, and hides all of > the unfriendly dunderish details. And if that's a good idea, I would > invite a discussion of how, exactly, it should be implemented. I'm > nowhere near proposing a PEP, but that may come later. Functions have an implicit 'return None' at the end (which, in CPython, become an explicit pair of bytecodes, even when the function already ends with return something'. The simplest proposal is that modules have an implicit "if __name__ == '__main__': main()" at the end. I think this would not have to be added to the bytecode. This magical invocation mimics C and some other languages, and I think it works well. -- Terry Jan Reedy From marko at pacujo.net Wed Nov 12 18:23:08 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 13 Nov 2014 01:23:08 +0200 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> <28e159ff-3d64-4793-9082-05cf1553c7c2@googlegroups.com> Message-ID: <878ujgovfn.fsf@elektro.pacujo.net> Chris Angelico : > Or, in as many cases as possible, raise an implicit KeyError and save > yourself a lot of typing. Any time these kinds of elif trees can be > turned into dict lookups, you get non-assert error checking for free. I agree that you shouldn't sprinkle asserts around the code. But consider this example: count = next_size / len(choices) The casual reader of the code might be left wondering if "choices" could be zero-length and if the programmer had overlooked the possibility, leading to a lengthy analysis and bewilderment. However, the programmer could have played this frustration out already in his head and written: assert len(choices) > 0 count = next_size / len(choices) or, equivalently: # here len(choices) > 0 count = next_size / len(choices) and the casual maintainer would be able to read on. Marko From rosuav at gmail.com Wed Nov 12 18:26:50 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Nov 2014 10:26:50 +1100 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> Message-ID: On Thu, Nov 13, 2014 at 10:19 AM, Terry Reedy wrote: > Functions have an implicit 'return None' at the end (which, in CPython, > become an explicit pair of bytecodes, even when the function already ends > with return something'. The simplest proposal is that modules have an > implicit "if __name__ == '__main__': main()" at the end. I think this would > not have to be added to the bytecode. > > This magical invocation mimics C and some other languages, and I think it > works well. Yes, but it conflicts with the existing and common usage of having that explicitly in the code. Safer - and more in line with the way other such functions are written - would be a dunder function: if __name__ == '__main__': __main__() ChrisA From rosuav at gmail.com Wed Nov 12 18:27:53 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Nov 2014 10:27:53 +1100 Subject: I love assert In-Reply-To: <878ujgovfn.fsf@elektro.pacujo.net> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> <28e159ff-3d64-4793-9082-05cf1553c7c2@googlegroups.com> <878ujgovfn.fsf@elektro.pacujo.net> Message-ID: On Thu, Nov 13, 2014 at 10:23 AM, Marko Rauhamaa wrote: > However, the programmer could have played this frustration out already > in his head and written: > > assert len(choices) > 0 > count = next_size / len(choices) assert choices count = next_size / len(choices) Or even just: count = next_size / len(choices) # choices won't be empty ChrisA From marko at pacujo.net Wed Nov 12 18:31:21 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 13 Nov 2014 01:31:21 +0200 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> <28e159ff-3d64-4793-9082-05cf1553c7c2@googlegroups.com> <878ujgovfn.fsf@elektro.pacujo.net> Message-ID: <874mu4ov1y.fsf@elektro.pacujo.net> Chris Angelico : > On Thu, Nov 13, 2014 at 10:23 AM, Marko Rauhamaa wrote: >> However, the programmer could have played this frustration out already >> in his head and written: >> >> assert len(choices) > 0 >> count = next_size / len(choices) > > assert choices > count = next_size / len(choices) > > Or even just: > > count = next_size / len(choices) # choices won't be empty Precisely. Marko From anschatten at gmail.com Wed Nov 12 18:43:25 2014 From: anschatten at gmail.com (Anton) Date: Wed, 12 Nov 2014 15:43:25 -0800 (PST) Subject: I love assert In-Reply-To: References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> <28e159ff-3d64-4793-9082-05cf1553c7c2@googlegroups.com> Message-ID: <67aae3c9-85bd-4968-af62-a8cf1e4602da@googlegroups.com> On Wednesday, November 12, 2014 3:03:18 PM UTC-8, Ian wrote: > On Wed, Nov 12, 2014 at 3:48 PM, Anton wrote: > Sure, which is why you and I have both suggested raising a RuntimeError instead. Yeah, I actually read it after sending my response :) From tjreedy at udel.edu Wed Nov 12 19:35:59 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Nov 2014 19:35:59 -0500 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> Message-ID: On 11/12/2014 6:26 PM, Chris Angelico wrote: > On Thu, Nov 13, 2014 at 10:19 AM, Terry Reedy wrote: >> Functions have an implicit 'return None' at the end (which, in CPython, >> become an explicit pair of bytecodes, even when the function already ends >> with return something'. The simplest proposal is that modules have an >> implicit "if __name__ == '__main__': main()" at the end. I think this would >> not have to be added to the bytecode. >> >> This magical invocation mimics C and some other languages, and I think it >> works well. > > Yes, but it conflicts with the existing and common usage of having > that explicitly in the code. Yeh, calling main twice could be a problem. > Safer - and more in line with the way > other such functions are written - would be a dunder function: > > if __name__ == '__main__': __main__() I presume you mean that calling __main__ implicitly would be both consistent and safer. No code should be using that now. -- Terry Jan Reedy From rosuav at gmail.com Wed Nov 12 19:54:55 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Nov 2014 11:54:55 +1100 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> Message-ID: On Thu, Nov 13, 2014 at 11:35 AM, Terry Reedy wrote: >> Safer - and more in line with the way >> other such functions are written - would be a dunder function: >> >> if __name__ == '__main__': __main__() > > > I presume you mean that calling __main__ implicitly would be both consistent > and safer. No code should be using that now. That's what I mean. Like changing iter.next() to iter.__next__() in Py3, it'd be using a name that emphasizes that the interpreter, not userland code, should be calling this function. Of course, it'd still be optional. Top-level code would be executed top-down, same as it now is. ChrisA From greg.ewing at canterbury.ac.nz Wed Nov 12 23:20:22 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 13 Nov 2014 17:20:22 +1300 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> <87a943qyvn.fsf@handshake.de> <545CC204.2010301@stoneleaf.us> <8761eq424e.fsf@handshake.de> Message-ID: Fabio Zadrozny wrote: > can someone from python-dev give some background of why > that's the way it is? It's because, with new-style classes, a class is also an instance (of class "type" or a subclass thereof). So without that rule, it would be ambiguous whether a dunder method applied to instances of a class or to the class itself. > and if maybe it's something which python-dev would consider worth > changing in the future -- not sure how much could break because of that > though Something fairly fundamental that would break is classs instantiation! You instantiate a class by calling it, so if a(x) were implemented as a.__call__(x), and class C had a __call__ method, then C() would invoke that method instead of instantiating C. -- Greg From nagle at animats.com Wed Nov 12 23:39:50 2014 From: nagle at animats.com (John Nagle) Date: Wed, 12 Nov 2014 20:39:50 -0800 Subject: SSLsocket.getpeercert - request to return ALL the fields of the certificate. Message-ID: <54643616.3090402@animats.com> In each revision of "getpeercert", a few more fields are returned. Python 3.2 added "issuer" and "notBefore". Python 3.4 added "crlDistributionPoints", "caIssuers", and OCSP URLS. But some fields still aren't returned. I happen to need CertificatePolicies, which is how you distinguish DV, OV, and EV certs. Here's what you get now: {'OCSP': ('http://EVSecure-ocsp.verisign.com',), 'caIssuers': ('http://EVSecure-aia.verisign.com/EVSecure2006.cer',), 'crlDistributionPoints': ('http://EVSecure-crl.verisign.com/EVSecure2006.crl',), 'issuer': ((('countryName', 'US'),), (('organizationName', 'VeriSign, Inc.'),), (('organizationalUnitName', 'VeriSign Trust Network'),), (('organizationalUnitName', 'Terms of use at https://www.verisign.com/rpa (c)06'),), (('commonName', 'VeriSign Class 3 Extended Validation SSL CA'),)), 'notAfter': 'Mar 22 23:59:59 2015 GMT', 'notBefore': 'Feb 20 00:00:00 2014 GMT', 'serialNumber': '69A7BC85C106DDE1CF4FA47D5ED813DC', 'subject': ((('1.3.6.1.4.1.311.60.2.1.3', 'US'),), (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),), (('businessCategory', 'Private Organization'),), (('serialNumber', '2927442'),), (('countryName', 'US'),), (('postalCode', '60603'),), (('stateOrProvinceName', 'Illinois'),), (('localityName', 'Chicago'),), (('streetAddress', '135 S La Salle St'),), (('organizationName', 'Bank of America Corporation'),), (('organizationalUnitName', 'Network Infrastructure'),), (('commonName', 'www.bankofamerica.com'),)), 'subjectAltName': (('DNS', 'mobile.bankofamerica.com'), ('DNS', 'www.bankofamerica.com')), 'version': 3} How about just returning ALL the remaining fields and finishing the job? Thanks. John Nagle From ethan at stoneleaf.us Wed Nov 12 23:52:19 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 12 Nov 2014 20:52:19 -0800 Subject: SSLsocket.getpeercert - request to return ALL the fields of the certificate. In-Reply-To: <54643616.3090402@animats.com> References: <54643616.3090402@animats.com> Message-ID: <54643903.1070701@stoneleaf.us> On 11/12/2014 08:39 PM, John Nagle wrote: > In each revision of "getpeercert", a few more fields are returned. > Python 3.2 added "issuer" and "notBefore". Python 3.4 added > "crlDistributionPoints", "caIssuers", and OCSP URLS. But some fields > still aren't returned. I happen to need CertificatePolicies, which > is how you distinguish DV, OV, and EV certs. > > Here's what you get now: > > {'OCSP': ('http://EVSecure-ocsp.verisign.com',), > 'caIssuers': ('http://EVSecure-aia.verisign.com/EVSecure2006.cer',), > 'crlDistributionPoints': > ('http://EVSecure-crl.verisign.com/EVSecure2006.crl',), > 'issuer': ((('countryName', 'US'),), > (('organizationName', 'VeriSign, Inc.'),), > (('organizationalUnitName', 'VeriSign Trust Network'),), > (('organizationalUnitName', > 'Terms of use at https://www.verisign.com/rpa (c)06'),), > (('commonName', 'VeriSign Class 3 Extended Validation SSL > CA'),)), > 'notAfter': 'Mar 22 23:59:59 2015 GMT', > 'notBefore': 'Feb 20 00:00:00 2014 GMT', > 'serialNumber': '69A7BC85C106DDE1CF4FA47D5ED813DC', > 'subject': ((('1.3.6.1.4.1.311.60.2.1.3', 'US'),), > (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),), > (('businessCategory', 'Private Organization'),), > (('serialNumber', '2927442'),), > (('countryName', 'US'),), > (('postalCode', '60603'),), > (('stateOrProvinceName', 'Illinois'),), > (('localityName', 'Chicago'),), > (('streetAddress', '135 S La Salle St'),), > (('organizationName', 'Bank of America Corporation'),), > (('organizationalUnitName', 'Network Infrastructure'),), > (('commonName', 'www.bankofamerica.com'),)), > 'subjectAltName': (('DNS', 'mobile.bankofamerica.com'), > ('DNS', 'www.bankofamerica.com')), > 'version': 3} > > How about just returning ALL the remaining fields and finishing > the job? Thanks. This would be much better on the issue tracker: https://bugs.python.org -- ~Ethan~ From cs at zip.com.au Thu Nov 13 02:23:57 2014 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 13 Nov 2014 18:23:57 +1100 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: Message-ID: <20141113072357.GA72514@cskk.homeip.net> On 12Nov2014 14:51, Ian Kelly wrote: >On Wed, Nov 12, 2014 at 2:33 PM, Chris Kaynor wrote: >> A decorator is an interesting idea, and should be easy to implement (only >> lightly tested): [...] >> Just decorate the "main" function of the script with that, and it will be >> automatically called when ran as a script, but not when imported as a >> module. > >This calls it at the wrong time, though. [...] >This would call the main function at the time it's defined, when other >things in the main script may not have been defined yet. One could >place the main function last, but it would be preferable not to be >forced. Indeed. This aspect is a deal breaker for me; I'd never use it. I make a point of putting the module's main function right up the top, immediately after the imports and any "constants" (let's not dither over that term). I _want_ the main function to in the reader's face when they visit the module code. All the cogs come later. And lots of my modules have "main" functions. Terribly useful. Cheers, Cameron Simpson We're in the business of putting goo on a substrate. - overhead by WIRED at the Intelligent Printing conference Oct2006 From rosuav at gmail.com Thu Nov 13 03:04:22 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Nov 2014 19:04:22 +1100 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: <20141113072357.GA72514@cskk.homeip.net> References: <20141113072357.GA72514@cskk.homeip.net> Message-ID: On Thu, Nov 13, 2014 at 6:23 PM, Cameron Simpson wrote: > Indeed. This aspect is a deal breaker for me; I'd never use it. > > I make a point of putting the module's main function right up the top, > immediately after the imports and any "constants" (let's not dither over > that term). I _want_ the main function to in the reader's face when they > visit the module code. All the cogs come later. > > And lots of my modules have "main" functions. Terribly useful. Hmm, I go the other way. As much as possible, I prefer functions to call what's above them, not what's below them - so the main function would always be at the end of the file. The very top of the file should have comments/docstrings etc, then imports, then pure utility functions that don't call on anything else, then "guts" functions, and finally routines that are called externally but never internally (like main). That way, if you're wondering at what some name means, you go to the top of the file and find the first occurrence; that'll usually be its definition. Most people already do this with their imports, putting them all at the top - I like to go further and make it unusual for this not to be the case. (Of course, the nature of live projects and constant editing is that there will be violations of the principle, and I don't code-churn just to fix it. But that's still the ideal.) ChrisA From vek.m1234 at gmail.com Thu Nov 13 02:03:27 2014 From: vek.m1234 at gmail.com (Veek M) Date: Thu, 13 Nov 2014 13:33:27 +0630 Subject: Python: package root, root-node, __init__.py in the package root Message-ID: I have a package structured like so on the file system: PKG LIBS are stored here: /usr/lib/python3.2/ Pkg-name: foo-1.0.0 1. What is the root directory, or root-node or 'root' of my package? My understanding is that it's: /usr/lib/python3.2/foo-1.0.0/ on the file-system and this is referred to the root of the pkg. 2. Can, foo-1.0.0 contain __init__.py or do i have to do: foo-1.0.0/foo/__init__.py ? Take a look at what this guy is saying on his blog: http://blog.habnab.it/blog/2013/07/21/python-packages-and-you/ ------------------- (bottom of the page) "Your project root should contain a python package, not be a package itself. If you do this, your setup.py will be very confusing (or not work at all) and it will be very difficult to run your code." (top of the page) passacre/__init__.py passacre/__main__.py 3. Could someone elucidate, explain what it is he's talking about? ----------------------------- Don?t directly run modules inside packages "What I mean specifically is doing python passacre/__main__.py, or python passacre/test/test_application.py, or anything else that starts with python passacre/. This will prevent python from knowing where the root of your package is, and so absolute imports and explicit relative imports will fail, or not import the code you think it should be importing." 4. In this particular case, how does the interpreter determine pkg-root? From torque.india at gmail.com Wed Nov 12 22:58:48 2014 From: torque.india at gmail.com (OmPs) Date: Thu, 13 Nov 2014 09:28:48 +0530 Subject: xml problem in parsing the great grandchildren Message-ID: http://pastebin.com/GCD6J0wd I am stuck here. What I am looking for is description of the system memory, but system has lot of places where class=memory is used and hence i can't use it. i need the one's which has id=bank:0 .. n and collect the decryption of it. I don't have option to use lxml. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: lshw-a105.xml Type: text/xml Size: 37148 bytes Desc: not available URL: From cs at zip.com.au Thu Nov 13 03:47:25 2014 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 13 Nov 2014 19:47:25 +1100 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: Message-ID: <20141113084725.GA97979@cskk.homeip.net> On 13Nov2014 19:04, Chris Angelico wrote: >On Thu, Nov 13, 2014 at 6:23 PM, Cameron Simpson wrote: >> Indeed. This aspect is a deal breaker for me; I'd never use it. >> >> I make a point of putting the module's main function right up the top, >> immediately after the imports and any "constants" (let's not dither over >> that term). I _want_ the main function to in the reader's face when they >> visit the module code. All the cogs come later. >> >> And lots of my modules have "main" functions. Terribly useful. > >Hmm, I go the other way. As much as possible, I prefer functions to >call what's above them, not what's below them - so the main function >would always be at the end of the file. [...] My view is that if there's a main (i.e. the module implements a small app all on its own, however tiny), then the main program logic should come first. The details follow later. For a pureply functional module (utility functions, classes built on them, etc) I tend to go your way. But the main, if there is one, comes first. >The very top of the file >should have comments/docstrings etc, then imports, then pure utility >functions that don't call on anything else, then "guts" functions, and >finally routines that are called externally but never internally (like >main). That way, if you're wondering at what some name means, you go >to the top of the file and find the first occurrence; that'll usually >be its definition. Sounds effective. I probably prefer my code (main aside, again) organised the same way. Needless to say, I have a heap of modules that could do with a cleanup along these lines. Cheers, Cameron Simpson If you make people think they're thinking, they'll love you; but if you really make them think, they'll hate you. - Don Marquis From rosuav at gmail.com Thu Nov 13 03:58:56 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Nov 2014 19:58:56 +1100 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: <20141113084725.GA97979@cskk.homeip.net> References: <20141113084725.GA97979@cskk.homeip.net> Message-ID: On Thu, Nov 13, 2014 at 7:47 PM, Cameron Simpson wrote: > My view is that if there's a main (i.e. the module implements a small app > all on its own, however tiny), then the main program logic should come > first. The details follow later. Ah, I see. Makes sense. It's kinda like an executable docstring. Still not my preferred style, but makes its own sense. ChrisA From __peter__ at web.de Thu Nov 13 04:47:04 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Nov 2014 10:47:04 +0100 Subject: xml problem in parsing the great grandchildren References: Message-ID: OmPs wrote: > import xml.etree.ElementTree as ET > > inv = open('lshw.xml', 'r') > inv = inv.read() > inv = ET.XML(inv) > > find_memory =inventory.findall(".//node[@id='bank:*']") > > # I am stuck here. What is required is description of the system memory, > but system has lot of places where class=memory is used and hence i can't > use it. i need the one's which has id=bank:0 .. n and collect the > decryption of it. > I am stuck here. What I am looking for is description of the system > memory, but system has lot of places where class=memory is used and hence > i can't use it. i need the one's which has id=bank:0 .. n and collect the > decryption of it. > > I don't have option to use lxml. Take the candidates and then find criteria the further reduce the matching nodes until only those are left that you are interested in: import xml.etree.ElementTree as ET inv = ET.parse("lshw-a105.xml") nodes = inv.findall(".//node[@class='memory']") for node in nodes: description = node.find("./description") if description.text == "System Memory": for subnode in node.findall("./node"): print(subnode.attrib["id"], subnode.find("./description").text) break From fabiofz at gmail.com Thu Nov 13 05:35:07 2014 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Thu, 13 Nov 2014 08:35:07 -0200 Subject: PyDev 3.9.0 Released Message-ID: What is PyDev? --------------------------- PyDev is an open-source Python IDE on top of Eclipse for Python, Jython and IronPython development. It comes with goodies such as code completion, syntax highlighting, syntax analysis, code analysis, refactor, debug, interactive console, etc. Details on PyDev: http://pydev.org Details on its development: http://pydev.blogspot.com What is LiClipse? --------------------------- LiClipse is a PyDev standalone with goodies such as support for Multiple cursors, theming and a number of other languages such as Django Templates, Kivy Language, Mako Templates, Html, Javascript, etc. It's also a commercial counterpart which helps supporting the development of PyDev. Details on LiClipse: http://www.liclipse.com/ Release Highlights: ------------------------------- * **Important**: PyDev requires Eclipse 3.8 or 4.3 onwards and Java 7! For older versions, keep using PyDev 2.x (use LiClipse: http://www.liclipse.com for a PyDev standalone with all requirements bundled). * **Vertical Indent Guide** is now available (may be customized in PyDev > Editor > Vertical Indent Guide. PyDev-359). * **Minimap** * The horizontal scrollbar is shown by default (again). It's still possible to hide it in the Preferences > PyDev > Editor > Overview Ruler Minimap. * Fixed critical issue where the minimap could lead to a repaint recursion on some Linux versions (reproduced on Ubuntu 12. LiClipse-120). * The PYTHONPATH is now properly passed to PyLint when using an external executable (PyDev-475). * Fixed issue where breakpoints in other editors (i.e.: CDT) where wrongly being handled by PyDev (patch by Danny Yoo. PyDev-482). * Fixed issue doing code-completion for builtins in Jython (PyDev-457). * **Interactive Console** * When doing a code-completion with Ctrl+Space, let tab change the focus instead of doing the tab-enabled completion. * Output given from the backend could end up being editable (PyDev-465). * input() was including the prompt in the input string (PyDev-465). * Debugger console was outputting greeting message when it shouldn't (PyDev-464). * **pep8**: --exclude can now be used in pep8 parameters (patch by Sebastian Elsner. PyDev-466). * **autopep8**: end line delimiter is now being kept (patch by Ben Blank. PyDev-461). * Unittest integration: Making sure we don't import the unittest module before executing pytest (PyDev-455). * Unittest integration: Fix to use the proper encoding when passing stdout/stderr to the java side. * Fixed issue when debugging file without extension (when there was no default editor associated to the file name). * Debugger: getpass properly working with additional arguments (PyDev-460). Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer LiClipse http://www.liclipse.com PyDev - Python Development Environment for Eclipse http://pydev.org http://pydev.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From nomail at invalid.com Thu Nov 13 05:50:34 2014 From: nomail at invalid.com (ast) Date: Thu, 13 Nov 2014 11:50:34 +0100 Subject: Synchronizing a sound with a widget change Message-ID: <54648d03$0$1981$426a74cc@news.free.fr> Hello, here is a small test code: ---------------- from tkinter import Tk, Frame from winsound import Beep root = Tk() f = Frame(root, width=300, height=300) f.pack() f.config(bg='Yellow') Beep(2000, 1000) -------------- I intended to change the frame color to yellow (f.config(bg='Yellow')) and at the same time to emit a sound (Beep(2000, 1000)) But I first have the sound and when the sound is over the window appears. Is there a way to fix that ? I have the idea to run an other thread to emit the sound, but I didn't try yet. Is it the solution ? Thanks From nomail at invalid.com Thu Nov 13 05:56:43 2014 From: nomail at invalid.com (ast) Date: Thu, 13 Nov 2014 11:56:43 +0100 Subject: Synchronizing a sound with a widget change In-Reply-To: <54648d03$0$1981$426a74cc@news.free.fr> References: <54648d03$0$1981$426a74cc@news.free.fr> Message-ID: <54648e75$0$12771$426a74cc@news.free.fr> "ast" a ?crit dans le message de news:54648d03$0$1981$426a74cc at news.free.fr... > > I have the idea to run an other thread to emit the sound, but I didn't try yet. > Is it the solution ? > nope, still doesn't work ! ------------------------------------------- from tkinter import Tk, Frame from winsound import Beep def mybeep(): Beep(2000, 1000) root = Tk() f = Frame(root, width=300, height=300) f.pack() f.config(bg='Yellow') root.after(1, mybeep) -------------------------------------------- From nomail at invalid.com Thu Nov 13 06:06:32 2014 From: nomail at invalid.com (ast) Date: Thu, 13 Nov 2014 12:06:32 +0100 Subject: Synchronizing a sound with a widget change In-Reply-To: <54648e75$0$12771$426a74cc@news.free.fr> References: <54648d03$0$1981$426a74cc@news.free.fr> <54648e75$0$12771$426a74cc@news.free.fr> Message-ID: <546490c1$0$2890$426a74cc@news.free.fr> "ast" a ?crit dans le message de news:54648e75$0$12771$426a74cc at news.free.fr... > > "ast" a ?crit dans le message de > news:54648d03$0$1981$426a74cc at news.free.fr... > >> >> I have the idea to run an other thread to emit the sound, but I didn't try yet. >> Is it the solution ? >> > > nope, still doesn't work ! > > root.after(1, mybeep) with: f = Frame(root, width=300, height=300) f.pack() f.config(bg='Yellow') root.after(80, mybeep) it works and with: f = Frame(root, width=300, height=300) f.pack() f.config(bg='Yellow') root.after(60, mybeep) it doesn't work I understand that Python takes times to create the root window and to color the frame. It the sound arrives before the end of the drawing, Python goes to the sound emitting,and when finished it goes back to drawing. This is annoying I would like sometuhing stable if possible thx From davea at davea.name Thu Nov 13 06:42:55 2014 From: davea at davea.name (Dave Angel) Date: Thu, 13 Nov 2014 06:42:55 -0500 (EST) Subject: Synchronizing a sound with a widget change References: <54648d03$0$1981$426a74cc@news.free.fr> <54648e75$0$12771$426a74cc@news.free.fr> <546490c1$0$2890$426a74cc@news.free.fr> Message-ID: "ast" Wrote in message: > > "ast" a ?crit dans le message de news:54648e75$0$12771$426a74cc at news.free.fr... >> >> "ast" a ?crit dans le message de >> news:54648d03$0$1981$426a74cc at news.free.fr... >> >>> >>> I have the idea to run an other thread to emit the sound, but I didn't try yet. >>> Is it the solution ? >>> >> >> nope, still doesn't work ! >> > >> root.after(1, mybeep) > > > with: > > f = Frame(root, width=300, height=300) > f.pack() > f.config(bg='Yellow') > root.after(80, mybeep) > > it works and with: > > f = Frame(root, width=300, height=300) > f.pack() > f.config(bg='Yellow') > root.after(60, mybeep) > > it doesn't work > > I understand that Python takes times to create the root > window and to color the frame. It the sound arrives > before the end of the drawing, Python goes to the sound > emitting,and when finished it goes back to drawing. > > This is annoying > I would like sometuhing stable if possible > I don't use Windows, but from what I read, winsound.Beep is a blocking call, and therefore must not be used in the main thread of a gui environment. Once the function is called, no events are processed. It seems like you need winsound.SND_ASYNC -- DaveA From nomail at invalid.com Thu Nov 13 08:25:43 2014 From: nomail at invalid.com (ast) Date: Thu, 13 Nov 2014 14:25:43 +0100 Subject: Synchronizing a sound with a widget change In-Reply-To: References: <54648d03$0$1981$426a74cc@news.free.fr> <54648e75$0$12771$426a74cc@news.free.fr> <546490c1$0$2890$426a74cc@news.free.fr> Message-ID: <5464b162$0$5112$426a74cc@news.free.fr> "Dave Angel" a ?crit dans le message de news:mailman.15773.1415878987.18130.python-list at python.org... > > I don't use Windows, but from what I read, winsound.Beep is a > blocking call, and therefore must not be used in the main thread > of a gui environment. > Once the function is called, no events are > processed. > > > It seems like you need winsound.SND_ASYNC > Yes, you are right. I have to use winsound.PlaySound(sound, flags) with flag = winsound.SND_ASYNC thx From roy at panix.com Thu Nov 13 08:33:30 2014 From: roy at panix.com (Roy Smith) Date: Thu, 13 Nov 2014 08:33:30 -0500 Subject: How about some syntactic sugar for " __name__ == '__main__' "? References: <20141113084725.GA97979@cskk.homeip.net> Message-ID: In article , Chris Angelico wrote: > On Thu, Nov 13, 2014 at 7:47 PM, Cameron Simpson wrote: > > My view is that if there's a main (i.e. the module implements a small app > > all on its own, however tiny), then the main program logic should come > > first. The details follow later. > > Ah, I see. Makes sense. It's kinda like an executable docstring. Still > not my preferred style, but makes its own sense. > > ChrisA I generally define a main() routine up near the top, then put if __name__ == '__main__': main() at the bottom. That gives you the best of both worlds; you get to see the main() code up front in the file, but you also get to not worry about what order things are defined. It also means you can import your module and call its main() directly. That's useful for testing, but occasionally for other purposes too. You can't do that with the (detestable) style of putting a whole bunch of code in the body of the "if" statement. From fabiofz at gmail.com Thu Nov 13 08:38:57 2014 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Thu, 13 Nov 2014 11:38:57 -0200 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> <87a943qyvn.fsf@handshake.de> <545CC204.2010301@stoneleaf.us> <8761eq424e.fsf@handshake.de> Message-ID: On Thu, Nov 13, 2014 at 2:20 AM, Gregory Ewing wrote: > Fabio Zadrozny wrote: > >> can someone from python-dev give some background of why that's the way it >> is? >> > > It's because, with new-style classes, a class is also an > instance (of class "type" or a subclass thereof). So > without that rule, it would be ambiguous whether a dunder > method applied to instances of a class or to the class > itself. > > > and if maybe it's something which python-dev would consider worth > >> changing in the future -- not sure how much could break because of that >> though >> > > Something fairly fundamental that would break is classs > instantiation! You instantiate a class by calling it, so if > a(x) were implemented as a.__call__(x), and class C had > a __call__ method, then C() would invoke that method > instead of instantiating C. > > Hi Gregory, Thanks for the explanation -- it still does seem a bit surprising from an end-user point of view, but it does make more sense now :) Best Regards, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Thu Nov 13 08:40:14 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Nov 2014 00:40:14 +1100 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: <20141113084725.GA97979@cskk.homeip.net> Message-ID: On Fri, Nov 14, 2014 at 12:33 AM, Roy Smith wrote: > ... you also get to not worry > about what order things are defined. That's only as regards the interpreter, though. My point has nothing to do with the order the interpreter sees things, it's all about how they're laid out for humans to read. For that, I prefer to have definitions before use. ChrisA From lie.1296 at gmail.com Thu Nov 13 09:09:08 2014 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 14 Nov 2014 01:09:08 +1100 Subject: I love assert In-Reply-To: References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <87lhngox30.fsf@elektro.pacujo.net> Message-ID: On 13/11/14 10:05, Ian Kelly wrote: > On Wed, Nov 12, 2014 at 3:47 PM, Marko Rauhamaa wrote: >> Ian Kelly : >> >> Apart from idiomatic style, there is no difference between >> >> # never reached >> >> assert False >> >> raise RuntimeError('Unreachable code reached') > > If the purpose is communication, then the comment is most effective, > as it can easily convey anything you want. If the purpose is to detect > programming errors, then the RuntimeError is most effective, as it > will always raise an error in the event it is reached. > > assert False is a strange hybrid of the two that is less effective at > both purposes. > You can do; assert False, "Some comments about why this assert is here" From yimr00 at gmail.com Thu Nov 13 09:34:52 2014 From: yimr00 at gmail.com (Yimr Zero) Date: Thu, 13 Nov 2014 22:34:52 +0800 Subject: Synchronizing a sound with a widget change References: <54648d03$0$1981$426a74cc@news.free.fr> Message-ID: <201411132234480664272@gmail.com> Hi, You may try to add the sleep(5) after the color change statement. You could adjust the sleep time to let the color change and beep synchroize. Thanks. Yimr Zero From: ast Date: 2014-11-13 18:50 To: python-list Subject: Synchronizing a sound with a widget change Hello, here is a small test code: ---------------- from tkinter import Tk, Frame from winsound import Beep root = Tk() f = Frame(root, width=300, height=300) f.pack() f.config(bg='Yellow') Beep(2000, 1000) -------------- I intended to change the frame color to yellow (f.config(bg='Yellow')) and at the same time to emit a sound (Beep(2000, 1000)) But I first have the sound and when the sound is over the window appears. Is there a way to fix that ? I have the idea to run an other thread to emit the sound, but I didn't try yet. Is it the solution ? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Thu Nov 13 09:54:38 2014 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 14 Nov 2014 01:54:38 +1100 Subject: Communicating with a PHP script (and pretending I'm a browser) In-Reply-To: References: Message-ID: On 13/11/14 03:57, Larry Martell wrote: > We were all making this much harder than it is. I ended up doing this: > > wp = urllib.request.urlopen('http://php_page/?' + request.POST.urlencode()) > pw = wp.read() I was about that suggest that actually, just be careful to escape things properly. Although I would recommend to pass the parameters as request body rather than as query parameters. Going through the web server via HTTP is most definitely going to be even more expensive than with pipes, but if performance is the least of your concern, then this is probably the easiest way to include things between languages. Yet another methods of mixing languages is to use iframes and to built your frontend as HTML with that queries Web APIs with AJAX but this relies on the client side to do the inclusion. As your goal is to eventually port an existing site to Python, I would highly recommend against using Django. Django, as a full-featured framework, is quite opinionated on how to do things, especially in regards to database design. While this is great for a new projects as it enforces certain well-tested patterns, this can be a pain when you need to use existing tables from the PHP application. Also, if your old application database access is written in SQL (i.e. with PHP mysql or mysqli driver), it might be less friction to port to SQLAlchemy Core rather than jumping straight to a full-fledged ORM, eventually you can slowly take the next step to port SQLA Core to SQLA ORM. Or you can mix and match Core and ORM with SQLAlchemy (with some care); Django is much less flexible about mixing plain SQL with ORM. From poalman at gmail.com Thu Nov 13 10:18:08 2014 From: poalman at gmail.com (Paul Wiseman) Date: Thu, 13 Nov 2014 15:18:08 +0000 Subject: ssl error with the python mac binary In-Reply-To: References: Message-ID: On 12 November 2014 19:52, Ned Deily wrote: > In article > , > Paul Wiseman wrote: >> I'm currently using the installer with py2app to make a distributable >> app that targets 10.5+ (including ppc). To save having more than one >> build I use this for all downloads. Although I'm starting to consider >> making a second 32/64 distributable. Are there many major drawbacks >> for distributing this i386/ppc binary for all versions of OSX up 10.9 >> and 10.10? > > For a standalone app, not really. The main difference is that, by using > the older 10.5 ABI, a few functions in the os module are not available > (if they were implemented first in OS X 10.6 or later) and/or they may > work a little differently. AFAIK, the most impactful difference, by > far, is the OpenSSL version difference you have run into. Up to now, I > don't recall any compatibility problems with 10.5 ABI programs running > on later versions of OS X or, for the most part, mixing extension > modules compiled to later ABIs with a 10.5 Python, although there might > be issues with mixing versions of C++ modules (Python and its standard > library do not use C++ themselves). But, of course, there's no > guarantee that something won't break in a future release of OS X. So > far, so good. > Yea, I'm a bit worried that apple will break it on a future release- I think I will start looking into making a second build. I wonder what are the chances they'll make a 64bit only OSX one day? >> That's great news! Thanks for this! I've always found building things >> on mac a huge pain and wasn't much looking forward to the prospect of >> trying to build a 32/ppc python build on a 64 bit 10.10 machine (would >> that even be possible?). > > It's possible: I do it. But I cheat a bit: I have 10.5 running in a > virtual machine on a 10.10 host. In theory, it's possible to build > natively on 10.10. The trick is getting a version of Xcode 3 installed > on 10.10 since support for building ppc archs was removed in Xcode 4. I > also cheat a bit there: I happen to still have copies of Xcode 3.1.4 and > 3.2.6 installed on 10.10 because I made sure to preserve them through > upgrades from 10.6 days. IIRC, directly installing the necessary > components from 3.2.6 on newer systems would require some hacking. Then > you have to be really vigilant that the build never strays from the old > SDK and tools, which is not something we claim to support at the moment. > The VM approach is quite safe and reliable. > I never thought about a VM for this for some reason- I have a few as well for basic testing on older OSX versions. I remember having to re-enable ppc in later versions of Xcode (http://stackoverflow.com/q/5333490/659346) when I was building some extensions for the app. That was a bit of a pain. Thanks for your help though! look forward to the 2.7.9 release :) > -- > Ned Deily, > nad at acm.org > > -- > https://mail.python.org/mailman/listinfo/python-list From lie.1296 at gmail.com Thu Nov 13 10:28:53 2014 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 14 Nov 2014 02:28:53 +1100 Subject: [Python-Dev] Dinamically set __call__ method In-Reply-To: References: <545919B6.7040007@stoneleaf.us> Message-ID: On 05/11/14 06:15, Roberto Mart?nez wrote: > > The thing with this is tricky. I need the change in the instance, > not in the class, because I have multiple instances and all of > them must have different implementations of __call__. Why not just use functions with closure if that's what you need? def a(one): two = 'three' def mycall(self): nonlocal two print 'NEW' return mycall Python functions are objects. > The workaround of calling a different method inside __call__ > is not valid for my case because I want to change the *signature* > of the function also -for introspection reasons. This seems like they should be two totally separate classes. If the signature is different, then it violates the substitution principle. If it violates substitution, then there is no reason why they should be of the same class. > This was my first approach, but it is not very informative to the user > and I prefer to have arguments with descriptive names. We have to change > __doc__ too, so this is not an ideal solution for me. > > I tried to implement __getattribute__, but is not called either. :( Or you can use an factory function: def A(p): def xcall(self): return 'X' def ycall(self): return 'Y' class _A(object): __call__ = xcall if p == 'x' else ycall return _A >>> A('x')()(), A('y')()() ('X', 'Y') or plain and simply just use inheritance if you want to pass an isinstance check: class A(object): def __call__(self): print 'OLD' class A1(A): def __call__(self): print 'NEW' What exactly, are you trying to do? From davea at davea.name Thu Nov 13 11:15:18 2014 From: davea at davea.name (Dave Angel) Date: Thu, 13 Nov 2014 11:15:18 -0500 (EST) Subject: Synchronizing a sound with a widget change References: <54648d03$0$1981$426a74cc@news.free.fr> <201411132234480664272@gmail.com> Message-ID: "Yimr Zero" Wrote in message: > body { line-height: 1.5; }blockquote { margin-top: 0px; margin-bottom: 0px; margin-left: 0.5em; }body { font-size: 10.5pt; font-family: 'Segoe UI'; color: rgb(0, 0, 0); line-height: 1.5; } > Hi, > You may try to add the sleep(5) after the color change statement. You could adjust the sleep time to let the color change and beep synchroize. > Thanks. > But sleep () doesn't have a non blocking version. You'd have to put it in another thread to get it out of the way. -- DaveA From noah-list at enabled.com Thu Nov 13 11:30:16 2014 From: noah-list at enabled.com (Noah) Date: Thu, 13 Nov 2014 16:30:16 +0000 Subject: netaddr value back to IP Message-ID: <5464DC98.5040304@enabled.com> Hi there List, I am trying to get a value back to IP using the netaddr python module. How do I get the value 'ip' back to IP format? how is it done? ---- snip ---- print IPNetwork(v4_peer_ip).value ip = IPNetwork(v4_peer_ip).value + 1 print ip --- snip --- Cheers, Noah From anuragpatibandla7 at gmail.com Thu Nov 13 13:07:42 2014 From: anuragpatibandla7 at gmail.com (Anurag) Date: Thu, 13 Nov 2014 10:07:42 -0800 (PST) Subject: Help with Python Multiprocessing Message-ID: <91fd5810-6a2a-46d8-8d1e-b68afced3987@googlegroups.com> I am having trouble understanding the Multiprocessing module. I need to run three different files 'Worker1' , 'Worker2', 'Worker3' all at once. Currently I am doing this : from multiprocessing import Process import Worker1.py import Worker2.py import Worker3.py p1 = Process(target=Worker1.py) p1.start() p2 = Process(target=Worker2.py) p2.start() p3 = Process(target=Worker3.py) p3.start() But this will only start the 'Worker1'. How do I execute all the three files at once? Thanks From anuragpatibandla7 at gmail.com Thu Nov 13 13:10:27 2014 From: anuragpatibandla7 at gmail.com (Anurag) Date: Thu, 13 Nov 2014 10:10:27 -0800 (PST) Subject: Help with Python Multiprocessing In-Reply-To: <91fd5810-6a2a-46d8-8d1e-b68afced3987@googlegroups.com> References: <91fd5810-6a2a-46d8-8d1e-b68afced3987@googlegroups.com> Message-ID: On Thursday, November 13, 2014 1:07:56 PM UTC-5, Anurag wrote: > I am having trouble understanding the Multiprocessing module. > I need to run three different files 'Worker1' , 'Worker2', 'Worker3' all at once. Currently I am doing this : > > from multiprocessing import Process > > import Worker1.py > import Worker2.py > import Worker3.py > > > > p1 = Process(target=Worker1.py) > p1.start() > p2 = Process(target=Worker2.py) > p2.start() > p3 = Process(target=Worker3.py) > p3.start() > > But this will only start the 'Worker1'. How do I execute all the three files at once? > > Thanks I am using Python 2.7 and each of my 'Worker' has a never ending loop that runs continuously. From ethan at stoneleaf.us Thu Nov 13 13:32:56 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 13 Nov 2014 10:32:56 -0800 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> Message-ID: <5464F958.4070404@stoneleaf.us> On 11/12/2014 01:51 PM, Ian Kelly wrote: > On Wed, Nov 12, 2014 at 2:33 PM, Chris Kaynor wrote: >> >> A decorator is an interesting idea, and should be easy to implement (only >> lightly tested): >> >> def main(func): >> if func.__module__ == "__main__": >> func() >> return func # The return could be omitted to block the function from >> being manually called after import. > > This calls it at the wrong time, though. [...] One decorator that won't call too early is atexit.register(). -- ~Ethan~ From python at mrabarnett.plus.com Thu Nov 13 13:45:35 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 13 Nov 2014 18:45:35 +0000 Subject: Help with Python Multiprocessing In-Reply-To: References: <91fd5810-6a2a-46d8-8d1e-b68afced3987@googlegroups.com> Message-ID: <5464FC4F.1030405@mrabarnett.plus.com> On 2014-11-13 18:10, Anurag wrote: > On Thursday, November 13, 2014 1:07:56 PM UTC-5, Anurag wrote: >> I am having trouble understanding the Multiprocessing module. >> I need to run three different files 'Worker1' , 'Worker2', 'Worker3' all at once. Currently I am doing this : >> >> from multiprocessing import Process >> >> import Worker1.py >> import Worker2.py >> import Worker3.py >> >> >> >> p1 = Process(target=Worker1.py) >> p1.start() >> p2 = Process(target=Worker2.py) >> p2.start() >> p3 = Process(target=Worker3.py) >> p3.start() >> >> But this will only start the 'Worker1'. How do I execute all the three files at once? >> >> Thanks > > I am using Python 2.7 and each of my 'Worker' has a never ending loop that runs continuously. > The documentation has this example: from multiprocessing import Process def f(name): print 'hello', name if __name__ == '__main__': p = Process(target=f, args=('bob',)) p.start() p.join() Suppose this is in a module called 'example.py'. When 'example.py' is run as the main module, it executes: p = Process(target=f, args=('bob',)) p.start() The multiprocessing module will _import_ 'example.py' in a new process, and because it's only imported (and not run as a main module), that code won't be executed. The multiprocessing module will then call the 'f' function. The way you've written your module, it'll spawn a new process even when it's only imported, causing the spawned process to spawn another process, which will, in turn, spawn another... From sohcahtoa82 at gmail.com Thu Nov 13 14:18:24 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Thu, 13 Nov 2014 11:18:24 -0800 (PST) Subject: Help with Python Multiprocessing In-Reply-To: <91fd5810-6a2a-46d8-8d1e-b68afced3987@googlegroups.com> References: <91fd5810-6a2a-46d8-8d1e-b68afced3987@googlegroups.com> Message-ID: On Thursday, November 13, 2014 10:07:56 AM UTC-8, Anurag wrote: > I am having trouble understanding the Multiprocessing module. > I need to run three different files 'Worker1' , 'Worker2', 'Worker3' all at once. Currently I am doing this : > > from multiprocessing import Process > > import Worker1.py > import Worker2.py > import Worker3.py > > > > p1 = Process(target=Worker1.py) > p1.start() > p2 = Process(target=Worker2.py) > p2.start() > p3 = Process(target=Worker3.py) > p3.start() > > But this will only start the 'Worker1'. How do I execute all the three files at once? > > Thanks Do your WorkerX.py files have a main() function or anything like that? If not, they should. Then, you'd set the targets to WorkerX.main. From gary.herron at islandtraining.com Thu Nov 13 14:12:22 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Thu, 13 Nov 2014 11:12:22 -0800 Subject: Help with Python Multiprocessing In-Reply-To: <91fd5810-6a2a-46d8-8d1e-b68afced3987@googlegroups.com> References: <91fd5810-6a2a-46d8-8d1e-b68afced3987@googlegroups.com> Message-ID: <54650296.2020202@islandtraining.com> On 11/13/2014 10:07 AM, Anurag wrote: > I am having trouble understanding the Multiprocessing module. > I need to run three different files 'Worker1' , 'Worker2', 'Worker3' all at once. Currently I am doing this : > > from multiprocessing import Process > > import Worker1.py > import Worker2.py > import Worker3.py > > > > p1 = Process(target=Worker1.py) > p1.start() > p2 = Process(target=Worker2.py) > p2.start() > p3 = Process(target=Worker3.py) > p3.start() > > But this will only start the 'Worker1'. How do I execute all the three files at once? > > Thanks I doubt that is your actual code. Python imports do not include .py extension. Please show us your actual code. (Use cut and paste please.) And then take the time to tell us how you determine only the first is started. Then we can probably help. As an aside: To be sure, one could make the above imports work by having files named py.py and __init__.py in a directory named Worker1 (and the same for directories Worker2 and Worker3). I think it's more likely that you miss-typed the above code. Gary Herron From roy at panix.com Thu Nov 13 14:41:46 2014 From: roy at panix.com (Roy Smith) Date: Thu, 13 Nov 2014 14:41:46 -0500 Subject: Communicating with a PHP script (and pretending I'm a browser) References: Message-ID: In article , Lie Ryan wrote: > On 13/11/14 03:57, Larry Martell wrote: > > We were all making this much harder than it is. I ended up doing this: > > > > wp = urllib.request.urlopen('http://php_page/?' + request.POST.urlencode()) > > pw = wp.read() You can do this if you want, but it's much easier to use requests library (http://docs.python-requests.org/). Compared to using the raw urllib stuff, requests makes it trivial to deal with argument encoding, cookie management, and a zillion other little details which will drive you crazy if you try to roll your own with urllib. From ian.g.kelly at gmail.com Thu Nov 13 15:33:40 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 13 Nov 2014 13:33:40 -0700 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: <5464F958.4070404@stoneleaf.us> References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> <5464F958.4070404@stoneleaf.us> Message-ID: On Thu, Nov 13, 2014 at 11:32 AM, Ethan Furman wrote: > On 11/12/2014 01:51 PM, Ian Kelly wrote: >> >> On Wed, Nov 12, 2014 at 2:33 PM, Chris Kaynor wrote: >>> >>> A decorator is an interesting idea, and should be easy to implement (only >>> lightly tested): >>> >>> def main(func): >>> if func.__module__ == "__main__": >>> func() >>> return func # The return could be omitted to block the function from >>> being manually called after import. >> >> This calls it at the wrong time, though. [...] > > One decorator that won't call too early is atexit.register(). Nice. That feels like an abuse, though. The actual program won't be able to register its own atexit handlers, because the program will already be exiting, and other things decorated with atexit.register might actually be called before the main function. From ethan at stoneleaf.us Thu Nov 13 15:43:15 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 13 Nov 2014 12:43:15 -0800 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> <5464F958.4070404@stoneleaf.us> Message-ID: <546517E3.6060404@stoneleaf.us> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 11/13/2014 12:33 PM, Ian Kelly wrote: > On Thu, Nov 13, 2014 at 11:32 AM, Ethan Furman wrote: >> On 11/12/2014 01:51 PM, Ian Kelly wrote: >>> >>> On Wed, Nov 12, 2014 at 2:33 PM, Chris Kaynor wrote: >>>> >>>> A decorator is an interesting idea, and should be easy to implement (only lightly tested): >>>> >>>> def main(func): if func.__module__ == "__main__": func() return func # The return could be omitted to block >>>> the function from being manually called after import. >>> >>> This calls it at the wrong time, though. [...] >> >> One decorator that won't call too early is atexit.register(). > > Nice. That feels like an abuse, though. The actual program won't be able to register its own atexit handlers, > because the program will already be exiting, and other things decorated with atexit.register might actually be > called before the main function. It's definitely a niche use-case -- such as a cli-helper lib: import said lib, and when it's decorators are used set the atexit handler to call the lib's __main__ function, which checks that the module name of the decorated function is '__main__', and if it is, run stuff! Hmmm... hopefully that wasn't difficult to explain. ;) - -- ~Ethan~ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.11 (GNU/Linux) iQIcBAEBAgAGBQJUZRfjAAoJENZ7D1rrH75Nx4IP/3tuR4JhVK6Acv04+DiHm32H BHGmBRZGtXQrHGEBcv8BlvUiztmrHqjV+Lkm78zKF3n9R8Ta9qTeSjqIsjRWUMtR JVraCSH6usUwmcGITXIYKQHdXynl+ylu9p8Hr3NT2aNoICqowVGSvK3Ie1NmJuf3 lJcl8tXiXgUrGCwBwEgdrBKTdaATe4QT9XFQJx1QbXpF3qT1Za5hPYthY3fH/Pd9 Nl9NHyA6F5x4sSO7itD23UtUpnRBHWl7blwsKkBi7ClfacxJMrYjFAMUaxUaiTFF /bygveskmMAZw87ISLtjkmOcKtsi0i2BQSQEjpBDZTiveCD/wyDDhJ+5pmZKzll0 Q+pISt4jG9hkArd+JCCxPuTCCo2xm+cMIB4/oSeONd760u6vURLPUNZ5tmNsRkiZ o0/EwyRhWPZotiLoyi7kDNyfpj/BSKV0A6Ph+M40UXOkTZFUf0E84OFEpB359MTO rIvHDpd6Tzch2Dliuj6UKZ1OOygIZauv2ebmEBHHNDMdsVbhdtTElS1Rh2JtDVyZ tUd67KTmE9CwOPcFIbYKHXGIf4FWDAgeaz9x8RY4UUPaDRlyG1eqSxx8Vob2AG9c MEawmA48JCj52ZeICQf6nnIFdIowFkV7QssUgte3cVfbcMBYnPx/nuJWWMjULo77 WrIUpisDf/juvXn4VtuO =oczI -----END PGP SIGNATURE----- From skip.montanaro at gmail.com Thu Nov 13 15:44:30 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Thu, 13 Nov 2014 14:44:30 -0600 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> <5464F958.4070404@stoneleaf.us> Message-ID: On Thu, Nov 13, 2014 at 2:33 PM, Ian Kelly wrote: > ... other things decorated with atexit.register > might actually be called before the main function I don't think that will happen. The atexit module is documented to execute its exit functions in reverse order. What's not documented is the behavior of calling atexit.register() while atexit._run_exitfuncs is running. That's an implementation detail, and though unlikely to change, it might be worthwhile getting that behavior documented. Skip From wealthychef at gmail.com Thu Nov 13 15:45:25 2014 From: wealthychef at gmail.com (Rich Cook) Date: Thu, 13 Nov 2014 12:45:25 -0800 (PST) Subject: help please: tkinter grid layout is very slow Message-ID: <91e0adb0-e4ef-4847-881a-7325e9a781d3@googlegroups.com> Hi, I'm trying to toss together an image browser in tkinter, and it is so slow it is unworkable. Here is my code. Can someone point out why it's so sloooow? :-) Thanks root = Tkinter.Tk() root.geometry("1000x280+300+300") label = Tkinter.Button(root, compound=Tkinter.TOP) label.pack() numimages = len(image_list) numcols = 6 numrows = numimages/numcols if numrows * numcols != numimages: numrows += 1 frame = Tkinter.Frame(root) for col in range(numcols): frame.columnconfigure(col, pad=2) for row in range(numrows): frame.rowconfigure(row, pad=2) print "There are", numimages, "images" # 256 in fact... for imagenum, (row, col) in enumerate([(row,col) for row in range(numrows) for col in range(numcols)]): b = Tkinter.Label(frame, compound = Tkinter.TOP) b['text'] = os.path.basename(image_list[imagenum]) b['image'] = ImageTk.PhotoImage(Image.open(image_list[imagenum]) ) b.grid(row=row, column = col) frame.pack() root.mainloop() From skip.montanaro at gmail.com Thu Nov 13 15:53:59 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Thu, 13 Nov 2014 14:53:59 -0600 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> <5464F958.4070404@stoneleaf.us> Message-ID: On Thu, Nov 13, 2014 at 2:44 PM, Skip Montanaro wrote: > What's not documented is > the behavior of calling atexit.register() while atexit._run_exitfuncs > is running. That's an implementation detail, and though unlikely to > change, it might be worthwhile getting that behavior documented. http://bugs.python.org/issue22867 Skip From tjreedy at udel.edu Thu Nov 13 17:14:26 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Nov 2014 17:14:26 -0500 Subject: help please: tkinter grid layout is very slow In-Reply-To: <91e0adb0-e4ef-4847-881a-7325e9a781d3@googlegroups.com> References: <91e0adb0-e4ef-4847-881a-7325e9a781d3@googlegroups.com> Message-ID: On 11/13/2014 3:45 PM, Rich Cook wrote: > Hi, I'm trying to toss together an image browser in tkinter, and it is so slow it is unworkable. Here is my code. Can someone point out why it's so sloooow? :-) Thanks > > root = Tkinter.Tk() > root.geometry("1000x280+300+300") > label = Tkinter.Button(root, compound=Tkinter.TOP) > label.pack() > > numimages = len(image_list) > numcols = 6 > numrows = numimages/numcols That should be numimages // numcols > if numrows * numcols != numimages: > numrows += 1 > > frame = Tkinter.Frame(root) > for col in range(numcols): > frame.columnconfigure(col, pad=2) > > for row in range(numrows): > frame.rowconfigure(row, pad=2) > > print "There are", numimages, "images" # 256 in fact... > for imagenum, (row, col) in enumerate([(row,col) for row in range(numrows) for col in range(numcols)]): > b = Tkinter.Label(frame, compound = Tkinter.TOP) > b['text'] = os.path.basename(image_list[imagenum]) > b['image'] = ImageTk.PhotoImage(Image.open(image_list[imagenum]) ) ImageTk? or Tkinter? > b.grid(row=row, column = col) > > frame.pack() > > root.mainloop() > -- Terry Jan Reedy From pecore at pascolo.net Thu Nov 13 17:10:56 2014 From: pecore at pascolo.net (giacomo boffi) Date: Thu, 13 Nov 2014 23:10:56 +0100 Subject: What does zip mean? References: Message-ID: <87a93uiwen.fsf@pascolo.net> Grant Edwards writes: > No, you don't. That's not how a zipper works. Each tooth from side A, > isn't bound with one from side B. It's bound with _two_ of them from > side B. And each of those is in turn bound with an additional tooth > from side A, and so on... > >> In your program you have two lists, whose elements `zip` returns >> bound together in pairs > > What the zipper on a coat does is convert two separate sequences into > a single sequence where the members alternate between the two input > sequences. IOW if we want to do something analogous to a zipper > fastener it should do this: > > zip([a,b,c,d,e,f],[1,2,3,4,5,6]) => [a,1,b,2,c,3,d,4,e,5,f,6] > > Item '1' is bound equally to item 'a' and 'b'. Item 'b' is bound > equally to item '1' and '2'. I love you folks of CLP From pecore at pascolo.net Thu Nov 13 17:22:06 2014 From: pecore at pascolo.net (giacomo boffi) Date: Thu, 13 Nov 2014 23:22:06 +0100 Subject: I don't read docs and don't know how to use Google. What does the print function do? References: Message-ID: <8761eiivw1.fsf@pascolo.net> "Clayton Kirkwood" writes: > Although I suspect for a price you could bring all of your > professional programming jobs to somebody here, but I think you > would pay out more than you would make. s/ here/ else/ and your assumption can be falsified From satishmlmlml at gmail.com Thu Nov 13 17:32:34 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Thu, 13 Nov 2014 14:32:34 -0800 (PST) Subject: How to recover bytes function? Message-ID: <44f58abf-35a8-4741-8b7c-7eabe99a326d@googlegroups.com> file = open('data.bin', 'rb') bytes = file.read() bytes b'\x00\x00\x00\x02spam\x00\x03?\x9d\xf3\xb6' records = [bytes([char] * 8) for char in b'spam'] TypeError: 'bytes' object is not callable How to recover bytes function? From ian.g.kelly at gmail.com Thu Nov 13 17:48:52 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 13 Nov 2014 15:48:52 -0700 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> <5464F958.4070404@stoneleaf.us> Message-ID: On Thu, Nov 13, 2014 at 1:44 PM, Skip Montanaro wrote: > On Thu, Nov 13, 2014 at 2:33 PM, Ian Kelly wrote: >> ... other things decorated with atexit.register >> might actually be called before the main function > > I don't think that will happen. The atexit module is documented to > execute its exit functions in reverse order. Right, so if something else gets registered after the main function, it will be called before the main function. > What's not documented is > the behavior of calling atexit.register() while atexit._run_exitfuncs > is running. That's an implementation detail, and though unlikely to > change, it might be worthwhile getting that behavior documented. Since the exit functions are executed in reverse order, anything registered at this time would have to be called before something else that has already been called, so I would expect this to be an error condition. From ian.g.kelly at gmail.com Thu Nov 13 17:56:33 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 13 Nov 2014 15:56:33 -0700 Subject: How about some syntactic sugar for " __name__ == '__main__' "? In-Reply-To: References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> <5464F958.4070404@stoneleaf.us> Message-ID: On Thu, Nov 13, 2014 at 1:53 PM, Skip Montanaro wrote: > On Thu, Nov 13, 2014 at 2:44 PM, Skip Montanaro > wrote: >> What's not documented is >> the behavior of calling atexit.register() while atexit._run_exitfuncs >> is running. That's an implementation detail, and though unlikely to >> change, it might be worthwhile getting that behavior documented. > > http://bugs.python.org/issue22867 In fact it seems the behavior does differ between Python 2.7 and Python 3.4: $ cat testatexit.py import atexit @atexit.register def main(): atexit.register(goodbye) @atexit.register def goodbye(): print("Goodbye") $ python2 testatexit.py Goodbye Goodbye $ python3 testatexit.py Goodbye From python at mrabarnett.plus.com Thu Nov 13 18:12:01 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 13 Nov 2014 23:12:01 +0000 Subject: How to recover bytes function? In-Reply-To: <44f58abf-35a8-4741-8b7c-7eabe99a326d@googlegroups.com> References: <44f58abf-35a8-4741-8b7c-7eabe99a326d@googlegroups.com> Message-ID: <54653AC1.8050101@mrabarnett.plus.com> On 2014-11-13 22:32, satishmlmlml at gmail.com wrote: > file = open('data.bin', 'rb') > bytes = file.read() > bytes > b'\x00\x00\x00\x02spam\x00\x03?\x9d\xf3\xb6' > records = [bytes([char] * 8) for char in b'spam'] > TypeError: 'bytes' object is not callable > > How to recover bytes function? > The simple answer: bytes = __builtins__.bytes The smart answer: Don't bind to 'bytes' in the first place! From rosuav at gmail.com Thu Nov 13 18:14:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Nov 2014 10:14:36 +1100 Subject: How to recover bytes function? In-Reply-To: <44f58abf-35a8-4741-8b7c-7eabe99a326d@googlegroups.com> References: <44f58abf-35a8-4741-8b7c-7eabe99a326d@googlegroups.com> Message-ID: On Fri, Nov 14, 2014 at 9:32 AM, wrote: > file = open('data.bin', 'rb') > bytes = file.read() > bytes > b'\x00\x00\x00\x02spam\x00\x03?\x9d\xf3\xb6' > records = [bytes([char] * 8) for char in b'spam'] > TypeError: 'bytes' object is not callable > > How to recover bytes function? del bytes ChrisA From rantingrickjohnson at gmail.com Thu Nov 13 18:11:53 2014 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Thu, 13 Nov 2014 15:11:53 -0800 (PST) Subject: A Freudian slip of *EPIC PROPORTIONS*! Message-ID: Some of the folks on this list have attempted to shame me for not accepting "with open arms", this vile encoding we call Unicode, but i wonder, are they aware of the deepest held beliefs of our very own leader? The other day whilst perusing the idlelib i came across a small but *very* significant line of code. They say a picture is worth a thousand words, well folks, this one short line of code might cause *ANY* picture blush with envy! The line is as follows: uniphooey = str However, without some context, even the more "astute" readers might miss the connection, so allow me to offer the comment that precedes this line: # The parse functions have no idea what to do with # Unicode, so replace all Unicode characters with "x". # This is "safe" so long as the only characters germane # to parsing the structure of Python are 7-bit ASCII. # It's *necessary* because Unicode strings don't have a # .translate() method that supports deletechars. We can obviously intuit that "uni" is short for "unicode", and by attaching "phooey" to unicode the author is making a public statement that he believes "unicode is phooey". But what does "phooey" actually mean? The Merriam Webster online dictionary defines "phooey" as: PHOOEY: used to express disbelief, disappointment, or a strong dislike for something. So now it is blatantly obvious that the author of PyParse does not care for unicode, and from my recollection, it was the great GvR himself that wrote most, if not all, of the code for IDLE and Tkinter. Now that this revelation has seen the light of day, i wonder just how "far apart" myself and the great one might actually be on this unicode business? On the other hand, if the author is not GvR, then he is most likely someone of great importance within the community. In any event, i believe it is high time that the author explain his intentions when using the word "uniphooey", because using any word should not be a crime, but hiding in the shadows whilst a fellow member is being lynched, and not having the balls to stand up and speak of your deeply held beliefs *IS* the highest of all crimes! It is a betrayal of not only your peers, but also of yourself. From sohcahtoa82 at gmail.com Thu Nov 13 18:16:20 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Thu, 13 Nov 2014 15:16:20 -0800 (PST) Subject: How to recover bytes function? In-Reply-To: <44f58abf-35a8-4741-8b7c-7eabe99a326d@googlegroups.com> References: <44f58abf-35a8-4741-8b7c-7eabe99a326d@googlegroups.com> Message-ID: <5caf79f5-85e3-49fc-88cf-410a580b9e5e@googlegroups.com> On Thursday, November 13, 2014 2:32:47 PM UTC-8, satish... at gmail.com wrote: > file = open('data.bin', 'rb') > bytes = file.read() > bytes > b'\x00\x00\x00\x02spam\x00\x03?\x9d\xf3\xb6' > records = [bytes([char] * 8) for char in b'spam'] > TypeError: 'bytes' object is not callable > > How to recover bytes function? So how many times do we have to ask you to tell us your EXPECTED output before you start actually doing that? 'bytes' is a built-in function, but built-in function definitions can be overwritten by redeclaring them. In this case, you're deleting the bytes function by assigning some read data to `bytes`. Don't do that. Either use a variable name other than 'bytes', or recover your bytes function. -DJ From anuragpatibandla7 at gmail.com Thu Nov 13 18:21:02 2014 From: anuragpatibandla7 at gmail.com (Anurag) Date: Thu, 13 Nov 2014 15:21:02 -0800 (PST) Subject: Help with Python Multiprocessing In-Reply-To: References: <91fd5810-6a2a-46d8-8d1e-b68afced3987@googlegroups.com> Message-ID: <23bdb9b9-1d9b-4edf-9c38-9165f17ca62f@googlegroups.com> On Thursday, November 13, 2014 2:22:29 PM UTC-5, Gary Herron wrote: > On 11/13/2014 10:07 AM, Anurag wrote: > > I am having trouble understanding the Multiprocessing module. > > I need to run three different files 'Worker1' , 'Worker2', 'Worker3' all at once. Currently I am doing this : > > > > from multiprocessing import Process > > > > import Worker1.py > > import Worker2.py > > import Worker3.py > > > > > > > > p1 = Process(target=Worker1.py) > > p1.start() > > p2 = Process(target=Worker2.py) > > p2.start() > > p3 = Process(target=Worker3.py) > > p3.start() > > > > But this will only start the 'Worker1'. How do I execute all the three files at once? > > > > Thanks > > I doubt that is your actual code. Python imports do not include .py > extension. Please show us your actual code. (Use cut and paste > please.) And then take the time to tell us how you determine only the > first is started. Then we can probably help. > > As an aside: To be sure, one could make the above imports work by having > files named py.py and __init__.py in a directory named Worker1 (and the > same for directories Worker2 and Worker3). I think it's more likely > that you miss-typed the above code. > > Gary Herron That is the actual code I am using in a file named 'ex.py'. My Worker files are also named with a '.py' extension. When I run my 'ex.py' through a command prompt, the 'Worker1.py' is executed in the same command prompt and starts an infinite loop. It never gets to the 'Worker2.py' part. But I want my Workers to be executed in different command prompts. From anuragpatibandla7 at gmail.com Thu Nov 13 18:22:37 2014 From: anuragpatibandla7 at gmail.com (Anurag) Date: Thu, 13 Nov 2014 15:22:37 -0800 (PST) Subject: Help with Python Multiprocessing In-Reply-To: References: <91fd5810-6a2a-46d8-8d1e-b68afced3987@googlegroups.com> Message-ID: <2d8bf6c1-328e-486a-9d3b-3191cb7e702b@googlegroups.com> On Thursday, November 13, 2014 2:18:50 PM UTC-5, sohca... at gmail.com wrote: > On Thursday, November 13, 2014 10:07:56 AM UTC-8, Anurag wrote: > > I am having trouble understanding the Multiprocessing module. > > I need to run three different files 'Worker1' , 'Worker2', 'Worker3' all at once. Currently I am doing this : > > > > from multiprocessing import Process > > > > import Worker1.py > > import Worker2.py > > import Worker3.py > > > > > > > > p1 = Process(target=Worker1.py) > > p1.start() > > p2 = Process(target=Worker2.py) > > p2.start() > > p3 = Process(target=Worker3.py) > > p3.start() > > > > But this will only start the 'Worker1'. How do I execute all the three files at once? > > > > Thanks > > Do your WorkerX.py files have a main() function or anything like that? If not, they should. Then, you'd set the targets to WorkerX.main. My Worker files have three different functions From satishmlmlml at gmail.com Thu Nov 13 18:23:12 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Thu, 13 Nov 2014 15:23:12 -0800 (PST) Subject: io.UnsupportedOperation: fileno Message-ID: import sys for stream in (sys.stdin, sys.stdout, sys.stderr): print(stream.fileno()) io.UnsupportedOperation: fileno From sohcahtoa82 at gmail.com Thu Nov 13 18:30:49 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Thu, 13 Nov 2014 15:30:49 -0800 (PST) Subject: io.UnsupportedOperation: fileno In-Reply-To: References: Message-ID: <5afd4b4e-e0cd-4436-b15a-936637b4fe2b@googlegroups.com> On Thursday, November 13, 2014 3:23:24 PM UTC-8, satish... at gmail.com wrote: > import sys > for stream in (sys.stdin, sys.stdout, sys.stderr): > print(stream.fileno()) > > > io.UnsupportedOperation: fileno Yup. That's what I'd expect to see. From satishmlmlml at gmail.com Thu Nov 13 18:34:42 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Thu, 13 Nov 2014 15:34:42 -0800 (PST) Subject: io.UnsupportedOperation: fileno In-Reply-To: <5afd4b4e-e0cd-4436-b15a-936637b4fe2b@googlegroups.com> References: <5afd4b4e-e0cd-4436-b15a-936637b4fe2b@googlegroups.com> Message-ID: What is the problem and how to overcome this problem? From rosuav at gmail.com Thu Nov 13 18:35:31 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Nov 2014 10:35:31 +1100 Subject: A Freudian slip of *EPIC PROPORTIONS*! In-Reply-To: References: Message-ID: On Fri, Nov 14, 2014 at 10:11 AM, Rick Johnson wrote: > # The parse functions have no idea what to do with > # Unicode, so replace all Unicode characters with "x". > # This is "safe" so long as the only characters germane > # to parsing the structure of Python are 7-bit ASCII. > # It's *necessary* because Unicode strings don't have a > # .translate() method that supports deletechars. Sounds to me like the functions that collapse whitespace to single spaces, or turn all letters into "A" and all digits into "9", or lowercase/casefold all alphabetics, or strip diacriticals, or anything else of that nature. It's often simpler to fold equivalencies together before parsing or comparing strings. It doesn't mean you don't respect Unicode; in fact, it proves that you *do*. So if you stop calling Unicode "vile", you might actually learn something. ChrisA From ben+python at benfinney.id.au Thu Nov 13 18:37:57 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 14 Nov 2014 10:37:57 +1100 Subject: How to recover bytes function? References: <44f58abf-35a8-4741-8b7c-7eabe99a326d@googlegroups.com> Message-ID: <85vbmi4qp6.fsf@benfinney.id.au> satishmlmlml at gmail.com writes: > file = open('data.bin', 'rb') > bytes = file.read() These are both terrible names, not least because they clobber the built-in objects ?file? and ?bytes?. Don't name an object for *or not only for) its data type. Instead, choose names that convey the *purpose* for the object. -- \ ?Alternative explanations are always welcome in science, if | `\ they are better and explain more. Alternative explanations that | _o__) explain nothing are not welcome.? ?Victor J. Stenger, 2001-11-05 | Ben Finney From rosuav at gmail.com Thu Nov 13 18:39:08 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Nov 2014 10:39:08 +1100 Subject: help please: tkinter grid layout is very slow In-Reply-To: <91e0adb0-e4ef-4847-881a-7325e9a781d3@googlegroups.com> References: <91e0adb0-e4ef-4847-881a-7325e9a781d3@googlegroups.com> Message-ID: On Fri, Nov 14, 2014 at 7:45 AM, Rich Cook wrote: > print "There are", numimages, "images" # 256 in fact... > for imagenum, (row, col) in enumerate([(row,col) for row in range(numrows) for col in range(numcols)]): > b = Tkinter.Label(frame, compound = Tkinter.TOP) > b['text'] = os.path.basename(image_list[imagenum]) > b['image'] = ImageTk.PhotoImage(Image.open(image_list[imagenum]) ) You're asking someone somewhere to load 256 images into memory and display them. What's the resolution of these images? Do they need to be scaled/cropped? That can be fairly expensive. How long does it actually take to (a) load all those images, and (b) pack the frame? Try, for instance, commenting out the b.grid() call, to force them all to be loaded but not packed. ChrisA From rosuav at gmail.com Thu Nov 13 18:40:59 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Nov 2014 10:40:59 +1100 Subject: io.UnsupportedOperation: fileno In-Reply-To: References: <5afd4b4e-e0cd-4436-b15a-936637b4fe2b@googlegroups.com> Message-ID: On Fri, Nov 14, 2014 at 10:34 AM, wrote: > What is the problem and how to overcome this problem? The problem is that you're posting, with no context, a query relating to a former post which gave scanty information and no indication of what you expected. To overcome this, read this: http://www.catb.org/esr/faqs/smart-questions.html ChrisA From satishmlmlml at gmail.com Thu Nov 13 18:40:39 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Thu, 13 Nov 2014 15:40:39 -0800 (PST) Subject: Bad file descriptor Message-ID: <442861d9-4280-4222-9084-f626a7782161@googlegroups.com> import os os.write(1, b'Hello descriptor world\n') OSError: Bad file descriptor How to give a file descriptor number to this function? How to get a file descriptor number? From satishmlmlml at gmail.com Thu Nov 13 18:42:17 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Thu, 13 Nov 2014 15:42:17 -0800 (PST) Subject: io.UnsupportedOperation: fileno In-Reply-To: <5afd4b4e-e0cd-4436-b15a-936637b4fe2b@googlegroups.com> References: <5afd4b4e-e0cd-4436-b15a-936637b4fe2b@googlegroups.com> Message-ID: fileno() in not supported. Is it only in 3.1? What is the workaround? From sohcahtoa82 at gmail.com Thu Nov 13 18:43:55 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Thu, 13 Nov 2014 15:43:55 -0800 (PST) Subject: Bad file descriptor In-Reply-To: <442861d9-4280-4222-9084-f626a7782161@googlegroups.com> References: <442861d9-4280-4222-9084-f626a7782161@googlegroups.com> Message-ID: On Thursday, November 13, 2014 3:40:50 PM UTC-8, satish... at gmail.com wrote: > import os > os.write(1, b'Hello descriptor world\n') > OSError: Bad file descriptor > > How to give a file descriptor number to this function? How to get a file descriptor number? http://bit.ly/1zRWHyq From ben+python at benfinney.id.au Thu Nov 13 18:42:12 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 14 Nov 2014 10:42:12 +1100 Subject: io.UnsupportedOperation: fileno References: <5afd4b4e-e0cd-4436-b15a-936637b4fe2b@googlegroups.com> Message-ID: <85r3x64qi3.fsf@benfinney.id.au> satishmlmlml at gmail.com writes: > What is the problem and how to overcome this problem? First, please provide context (just as the previous respondent did), so your message may be understood in the absence of those prior. As to your question: Please describe what you expected, and how the behaviour was different. Unless we know what you think is wrong, we don't know what ?the problem? is. -- \ ?Sittin' on the fence, that's a dangerous course / You can even | `\ catch a bullet from the peace-keeping force? ?Dire Straits, | _o__) _Once Upon A Time In The West_ | Ben Finney From satishmlmlml at gmail.com Thu Nov 13 18:48:32 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Thu, 13 Nov 2014 15:48:32 -0800 (PST) Subject: fileno() not supported in Python 3.1 Message-ID: import sys for stream in (sys.stdin, sys.stdout, sys.stderr): print(stream.fileno()) io.UnsupportedOperation: fileno Is there a workaround? From ben+python at benfinney.id.au Thu Nov 13 18:52:11 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 14 Nov 2014 10:52:11 +1100 Subject: io.UnsupportedOperation: fileno References: <5afd4b4e-e0cd-4436-b15a-936637b4fe2b@googlegroups.com> Message-ID: <85mw7u4q1g.fsf@benfinney.id.au> satishmlmlml at gmail.com writes: > fileno() in not supported. It is supported, but it is behaving as the documentation describes . > Is it only in 3.1? What is the workaround? Expect an exception when you ask for the file descriptor on a stream that does not use a file descriptor. -- \ ?Pinky, are you pondering what I'm pondering?? ?Well, I think | `\ so, Brain, but ?apply North Pole? to what?? ?_Pinky and The | _o__) Brain_ | Ben Finney From ben+python at benfinney.id.au Thu Nov 13 18:57:47 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 14 Nov 2014 10:57:47 +1100 Subject: fileno() not supported in Python 3.1 References: Message-ID: <85egt64ps4.fsf@benfinney.id.au> satishmlmlml at gmail.com writes: > Is there a workaround? Please take the time to gather your thoughts, do not fire off a rapid series of terse scattered questions. What is it you're trying to do? What approach are you intending to take? -- \ ?I was in Las Vegas, at the roulette table, having a furious | `\ argument over what I considered to be an odd number.? ?Steven | _o__) Wright | Ben Finney From ben+python at benfinney.id.au Thu Nov 13 18:56:02 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 14 Nov 2014 10:56:02 +1100 Subject: Bad file descriptor References: <442861d9-4280-4222-9084-f626a7782161@googlegroups.com> Message-ID: <85ioii4pv1.fsf@benfinney.id.au> satishmlmlml at gmail.com writes: > import os > os.write(1, b'Hello descriptor world\n') > OSError: Bad file descriptor It works fine for me:: >>> import os >>> os.write(1, b'Hello descriptor world\n') Hello descriptor world 23 You don't say which Python, or which version, you're using. In the absence of different information, most of us will assume the latest stable release of CPython. Currently, that is CPython 3.4. -- \ ?I am too firm in my consciousness of the marvelous to be ever | `\ fascinated by the mere supernatural ?? ?Joseph Conrad, _The | _o__) Shadow-Line_ | Ben Finney From satishmlmlml at gmail.com Thu Nov 13 19:08:56 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Thu, 13 Nov 2014 16:08:56 -0800 (PST) Subject: fileno() not supported in Python 3.1 In-Reply-To: References: Message-ID: How to get file descriptor number for the following: sys.stdin sys.stdout sys.stderr It is displaying io.UnsupportedOperation: fileno error Kindly help. From tjreedy at udel.edu Thu Nov 13 19:34:36 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Nov 2014 19:34:36 -0500 Subject: A Freudian slip of *EPIC PROPORTIONS*! In-Reply-To: References: Message-ID: On 11/13/2014 6:11 PM, Rick Johnson wrote: > # The parse functions have no idea what to do with > # Unicode, so replace all Unicode characters with "x". > # This is "safe" so long as the only characters germane > # to parsing the structure of Python are 7-bit ASCII. > # It's *necessary* because Unicode strings don't have a > # .translate() method that supports deletechars. > uniphooey = str It is customary to attribute quotes to their source. This is from 2.x Lib/idlelib/PyParse.py. The file was committed (and probably written) by David Scherer 2000-08-15. Edits for unicode, including the above, were committed (and perhaps written) by Kurt B. Kaiser on 2001-07-13. I doubt GvR ever saw this code. I expect KBK has changed opinions with respect to unicode in 13 years, as has most everyone else. -- Terry Jan Reedy From roy at panix.com Thu Nov 13 19:41:22 2014 From: roy at panix.com (Roy Smith) Date: Thu, 13 Nov 2014 19:41:22 -0500 Subject: Bad file descriptor References: <442861d9-4280-4222-9084-f626a7782161@googlegroups.com> Message-ID: In article , Ben Finney wrote: > satishmlmlml at gmail.com writes: > > > import os > > os.write(1, b'Hello descriptor world\n') > > OSError: Bad file descriptor > > It works fine for me:: > > >>> import os > >>> os.write(1, b'Hello descriptor world\n') > Hello descriptor world > 23 > > You don't say which Python, or which version, you're using. In the > absence of different information, most of us will assume the latest > stable release of CPython. Currently, that is CPython 3.4. I don't think this has anything to do with which version of Python he's using. I think all that's happening is (for some unknown reason), fd 1 is closed before his program runs. You can demonstrate this, for example, in bash: $ cat hello.py import os os.write(1, b'Hello descriptor world\n') $ python hello.py Hello descriptor world $ 1<&- python hello.py Traceback (most recent call last): File "hello.py", line 2, in os.write(1, b'Hello descriptor world\n') OSError: [Errno 9] Bad file descriptor You owe the Oracle 5 minutes of his life back and a cookie for making him read enough of the bash manual to figure out the syntax to tell it to close a descriptor. From satishmlmlml at gmail.com Thu Nov 13 19:51:33 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Thu, 13 Nov 2014 16:51:33 -0800 (PST) Subject: How to get file descriptors of sys.stdin, sys.stdout and sys.stderr? Message-ID: <9ee719ac-21cb-43db-a9ae-e13fd41f4a65@googlegroups.com> How to get file descriptors of sys.stdin, sys.stdout and sys.stderr? From satishmlmlml at gmail.com Thu Nov 13 19:54:49 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Thu, 13 Nov 2014 16:54:49 -0800 (PST) Subject: How to get file descriptors of sys.stdin, sys.stdout and sys.stderr? Message-ID: <98db8c15-73fc-47cb-b32f-be7b30c8eddb@googlegroups.com> How to get file descriptors of sys.stdin, sys.stdout and sys.stderr? From ned at nedbatchelder.com Thu Nov 13 20:52:21 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Thu, 13 Nov 2014 20:52:21 -0500 Subject: How to get file descriptors of sys.stdin, sys.stdout and sys.stderr? In-Reply-To: <98db8c15-73fc-47cb-b32f-be7b30c8eddb@googlegroups.com> References: <98db8c15-73fc-47cb-b32f-be7b30c8eddb@googlegroups.com> Message-ID: On 11/13/14 7:54 PM, satishmlmlml at gmail.com wrote: > How to get file descriptors of sys.stdin, sys.stdout and sys.stderr? > You don't seem to be reading any of the responses you are getting. At the very least, you don't seem to be understanding them, or engaging with the authors. You are misbehaving on this list. Everyone else: I recommend that people stop responding. Satish seems unlikely to improve. -- Ned Batchelder, http://nedbatchelder.com From ben+python at benfinney.id.au Thu Nov 13 21:52:11 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 14 Nov 2014 13:52:11 +1100 Subject: fileno() not supported in Python 3.1 References: Message-ID: <85a93u4hpg.fsf@benfinney.id.au> satishmlmlml at gmail.com writes: > How to get file descriptor number for the following: > sys.stdin > sys.stdout > sys.stderr Why do you need this? What are you intending to do? -- \ ?Crime is contagious? if the government becomes a lawbreaker, | `\ it breeds contempt for the law.? ?Justice Louis Brandeis | _o__) | Ben Finney From breamoreboy at yahoo.co.uk Fri Nov 14 00:10:46 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 14 Nov 2014 05:10:46 +0000 Subject: io.UnsupportedOperation: fileno In-Reply-To: References: <5afd4b4e-e0cd-4436-b15a-936637b4fe2b@googlegroups.com> Message-ID: On 13/11/2014 23:34, satishmlmlml at gmail.com wrote: > What is the problem and how to overcome this problem? > RTFM. -- 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 Fri Nov 14 00:17:04 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 14 Nov 2014 05:17:04 +0000 Subject: Bad file descriptor In-Reply-To: <442861d9-4280-4222-9084-f626a7782161@googlegroups.com> References: <442861d9-4280-4222-9084-f626a7782161@googlegroups.com> Message-ID: On 13/11/2014 23:40, satishmlmlml at gmail.com wrote: > import os > os.write(1, b'Hello descriptor world\n') > OSError: Bad file descriptor > > How to give a file descriptor number to this function? How to get a file descriptor number? > I suggest getting your cheque book out and paying for the advice you so desperately need. Or follow the advice already given about asking smart questions. Or RTFM. Or simply go away. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From tjreedy at udel.edu Fri Nov 14 00:20:59 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Nov 2014 00:20:59 -0500 Subject: A new Help Vampire? (was Re: (too many threads) In-Reply-To: <9ee719ac-21cb-43db-a9ae-e13fd41f4a65@googlegroups.com> References: <9ee719ac-21cb-43db-a9ae-e13fd41f4a65@googlegroups.com> Message-ID: On 11/13/2014 7:51 PM, satishmlmlml at gmail.com wrote: in 4 different threads > How to get file descriptors of sys.stdin, sys.stdout and sys.stderr? > fileno() in not supported. Is it only in 3.1? What is the workaround? > io.UnsupportedOperation: fileno > How to give a file descriptor number to this function? How to get a file descriptor number? Satish, you are acting like the variety of troll called a Help Vampire. One of the symptoms is hogging the newsgroup by starting multiple threads a day, often on the same topic. Another is ignoring the advice to read and study the manuals. Another is ignoring advice to read, study, and follow advice on how to ask good questions. Please desist. -- Terry Jan Reedy From cs at zip.com.au Fri Nov 14 01:31:32 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 14 Nov 2014 17:31:32 +1100 Subject: fileno() not supported in Python 3.1 In-Reply-To: <85a93u4hpg.fsf@benfinney.id.au> References: <85a93u4hpg.fsf@benfinney.id.au> Message-ID: <20141114063132.GA21856@cskk.homeip.net> On 14Nov2014 13:52, Ben Finney wrote: >satishmlmlml at gmail.com writes: >> How to get file descriptor number for the following: >> sys.stdin >> sys.stdout >> sys.stderr > >Why do you need this? What are you intending to do? In fairness, who cares? It is a basic and reasonable thing to do. I did it only last night: I wanted to know if stderr was a tty or pipe, versus a regular file, as I wanted to special case some error formatting (loosely speaking, default automatic people-friendliness versus log file verbosity). I know that why people want to do things is important, as they may be choosing the wrong approach. But the above question seems very simple and very basic: he seems unable to get the OS file descriptor number from the standard streams, and this is surprising. I think he even started the thead with almost a transcript of the failure, and backed off the the above abstraction when someone complained. Cheers, Cameron Simpson | Alain van der Heide | This is the way the world ends | | avdh at dazixco.ingr.com | This is the way the world ends | | "The opinions expressed above are mine- | This is the way the world ends | | mineminemine, and you can't have them." | Not with a bang, but with a whi segmentation fault core dumped From dieter at handshake.de Fri Nov 14 02:09:36 2014 From: dieter at handshake.de (dieter) Date: Fri, 14 Nov 2014 08:09:36 +0100 Subject: Python: package root, root-node, __init__.py in the package root References: Message-ID: <87oasadzrj.fsf@handshake.de> Veek M writes: > I have a package structured like so on the file system: > PKG LIBS are stored here: /usr/lib/python3.2/ > Pkg-name: foo-1.0.0 > > 1. What is the root directory, or root-node or 'root' of my package? My > understanding is that it's: /usr/lib/python3.2/foo-1.0.0/ on the file-system > and this is referred to the root of the pkg. > > 2. Can, foo-1.0.0 contain __init__.py or do i have to do: > foo-1.0.0/foo/__init__.py ? > > > Take a look at what this guy is saying on his blog: > http://blog.habnab.it/blog/2013/07/21/python-packages-and-you/ > > ------------------- > (bottom of the page) > "Your project root should contain a python package, not be a package itself. > If you do this, your setup.py will be very confusing (or not work at all) > and it will be very difficult to run your code." The blog author distinguishes between a project and a package and *recommends* that the package is in a subfolder of its project -- in order to get a simpler "setup.py". Let me clarify the terms "package" and "project" a bit. The "package" is what is used in a Python installation - what is imported into your application. In order to get the "package" installed, other resources are typically required (e.g. installation documentation, dependency specification, "setup.py", ...). The "project" contains the package sources and (most of) the required resources to get the package installed by standard means (e.g. "pip", "easy_install", ...). From vek.m1234 at gmail.com Fri Nov 14 01:18:44 2014 From: vek.m1234 at gmail.com (Veek M) Date: Fri, 14 Nov 2014 12:48:44 +0630 Subject: Python 3.x (beazley): __context__ vs __cause__ attributes in exception handling Message-ID: In 'Chained Exceptions' - Beazley pg:626 ------------ try: pass except ValueError as e: raise SyntaxError('foo bar') from e ------------- Here, if ValueError is raised and SyntaxError is then raised.. 'e' contains __cause__ which points to the ValueError Traceback. He goes on to say: --------------- A more subtle example of exception chaining involves exceptions raised within another exception handler. For example: def error(msg): print(m) # Note: typo is intentional (m undefined) try: statements except ValueError as e: error("Couldn't parse configuration") ------------------- Here, 'error' generates an inadvertent exception. What i don't understand is this bit: ------------------ For implicit chaining, the _ _context_ _ attribute of an exception instance e contains a reference to previous exception. --------------------- Why is he saying that 'e' contains a reference in __context__ to the exception generated by 'error' ?? Is that correct? Surely, the exception generated by 'error' will refer to 'e'? WTH?? For Implicit errors, there is no 'e'! Additionally, how would you go about using __context__ if the exception is generated implicitly? Book pages: imgur.com/bwpYq8T imgur.com/inZQv5J From cs at zip.com.au Fri Nov 14 02:36:46 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 14 Nov 2014 18:36:46 +1100 Subject: fileno() not supported in Python 3.1 In-Reply-To: References: Message-ID: <20141114073646.GA32086@cskk.homeip.net> On 13Nov2014 15:48, satishmlmlml at gmail.com wrote: >import sys >for stream in (sys.stdin, sys.stdout, sys.stderr): > print(stream.fileno()) > > >io.UnsupportedOperation: fileno > >Is there a workaround? The first workaround that suggests itself it to use a more modern Python. I've got 3.4.2 here, and it goes: Python 3.4.2 (default, Nov 5 2014, 21:19:51) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> for stream in (sys.stdin, sys.stdout, sys.stderr): ... print(stream.fileno()) ... 0 1 2 >>> In short, in 3.4.2 it just works. Cheers, Cameron Simpson Chris Gascoyne, while struggling to program stuff on Microsoft Windows: "I thought people said how bad it was just because they didn't like Microsoft." From cs at zip.com.au Fri Nov 14 02:39:22 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 14 Nov 2014 18:39:22 +1100 Subject: io.UnsupportedOperation: fileno In-Reply-To: <85mw7u4q1g.fsf@benfinney.id.au> References: <85mw7u4q1g.fsf@benfinney.id.au> Message-ID: <20141114073922.GA60637@cskk.homeip.net> On 14Nov2014 10:52, Ben Finney wrote: >satishmlmlml at gmail.com writes: > >> fileno() in not supported. > >It is supported, but it is behaving as the documentation describes >. > >> Is it only in 3.1? What is the workaround? > >Expect an exception when you ask for the file descriptor on a stream >that does not use a file descriptor. However, in 3.4.2 it does work (well, on MacOSX). Just as well really, as stdin, stdout and stderr do eventually connect to file descriptors... Cheers, Cameron Simpson You wouldn't... ...but you KNOW you could. - Original V65 Commercial From cs at zip.com.au Fri Nov 14 02:46:09 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 14 Nov 2014 18:46:09 +1100 Subject: How to recover bytes function? In-Reply-To: <44f58abf-35a8-4741-8b7c-7eabe99a326d@googlegroups.com> References: <44f58abf-35a8-4741-8b7c-7eabe99a326d@googlegroups.com> Message-ID: <20141114074609.GA72902@cskk.homeip.net> On 13Nov2014 14:32, satishmlmlml at gmail.com wrote: >file = open('data.bin', 'rb') >bytes = file.read() >bytes >b'\x00\x00\x00\x02spam\x00\x03?\x9d\xf3\xb6' >records = [bytes([char] * 8) for char in b'spam'] >TypeError: 'bytes' object is not callable > >How to recover bytes function? The best way is not to use "bytes" for something else when you know you will be using the builtin version as well. Using the same name for two things is generally a bad idea. The second, and worse, way is to see the documentation for the "builtins" module. Cheers, Cameron Simpson Madness takes its toll. Please have exact change. - Janice Hanes From cs at zip.com.au Fri Nov 14 02:42:40 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 14 Nov 2014 18:42:40 +1100 Subject: Bad file descriptor In-Reply-To: <442861d9-4280-4222-9084-f626a7782161@googlegroups.com> References: <442861d9-4280-4222-9084-f626a7782161@googlegroups.com> Message-ID: <20141114074240.GA64317@cskk.homeip.net> On 13Nov2014 15:40, satishmlmlml at gmail.com wrote: >import os >os.write(1, b'Hello descriptor world\n') >OSError: Bad file descriptor > >How to give a file descriptor number to this function? How to get a file descriptor number? Wow, this must be at least the 4th post of the same question. It now occurs to me that a newer Python won't help you. Are you running this at a command prompt? Or are you running this in some IDE? The reason I ask this question is that at a command prompt, the above would probably work. In short, please provide more context. What OS? What version of Python? What environment (command prompt, IDE (which one?), a standalone script, etc)? CHeers, Cameron Simpson Louis Pasteur's theory of germs is ridiculous fiction. --Pierre Pachet, Professor of Physiology at Toulouse, 1872 From KO at example.org Fri Nov 14 03:25:56 2014 From: KO at example.org (KO) Date: Fri, 14 Nov 2014 08:25:56 +0000 (UTC) Subject: A Freudian slip of *EPIC PROPORTIONS*! References: Message-ID: On 2014-11-13, Rick Johnson wrote: > On the other hand, if the author is not GvR, then he is most > likely someone of great importance within the community. As much as I love Python, I hate the amount of appeal to authority that is present in the Python community. Ok, GvR created Python, great. He is extremely smart and knowledgable, no doubt. But that doesn't make him right on everything. That doesn't mean his opinion on something makes it True or False. Gooosh. -- ko From michael at stroeder.com Fri Nov 14 04:03:40 2014 From: michael at stroeder.com (=?UTF-8?B?TWljaGFlbCBTdHLDtmRlcg==?=) Date: Fri, 14 Nov 2014 10:03:40 +0100 Subject: netaddr value back to IP In-Reply-To: References: Message-ID: Noah wrote: > I am trying to get a value back to IP using the netaddr python module. > How do I get the value 'ip' back to IP format? how is it done? > > ---- snip ---- > > print IPNetwork(v4_peer_ip).value > ip = IPNetwork(v4_peer_ip).value + 1 > print ip > > --- snip --- >>> ip=netaddr.IPAddress('192.168.71.20') >>> ip+=1 >>> str(ip) '192.168.71.21' Ciao, Michael. From wxjmfauth at gmail.com Fri Nov 14 04:57:28 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Fri, 14 Nov 2014 01:57:28 -0800 (PST) Subject: A Freudian slip of *EPIC PROPORTIONS*! In-Reply-To: References: Message-ID: <30b65bb8-1258-45c6-a16f-c97f16451109@googlegroups.com> _________ The Python devs are not understanding Unicode. (I saw it once more yesterday). jmf From steve+comp.lang.python at pearwood.info Fri Nov 14 05:58:40 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 14 Nov 2014 21:58:40 +1100 Subject: I don't read docs and don't know how to use Google. What does the print function do? References: <019e01cffd3d$18b60c50$4a2224f0$@us> Message-ID: <5465e062$0$12998$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > There are blog posts out there about how large proportions of > applicants can't even write simple code on command... and I've taken > the questions and shown them to my siblings (who protest that they're > definitely not programmers), proving that a basic smattering of > mathematical nous puts you above people who are trying to earn money > from coding. > > It's like a carpenter, looking for a skilled assistant, and getting > people who don't know which end of a saw to hold. http://blog.codinghorror.com/why-cant-programmers-program/ Not everyone agrees that this is a thing: http://www.skorks.com/2010/10/99-out-of-100-programmers-cant-program-i-call-bullshit/ I'm inclined to accept that maybe 99 out of 100 *applications* for programming jobs are from people who can't program, but I don't think that 99 out of 100 *programmers* can't program. It's probably more like 65, maybe 70 out of 100, tops. Ha ha only serious. More here: http://www.protocolostomy.com/2010/03/15/programmers-that-cant-program/ -- Steven From steve+comp.lang.python at pearwood.info Fri Nov 14 06:06:07 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 14 Nov 2014 22:06:07 +1100 Subject: What does zip mean? References: Message-ID: <5465e220$0$13004$c3e8da3$5496439d@news.astraweb.com> Grant Edwards wrote: > What the zipper on a coat does is convert two separate sequences into > a single sequence where the members alternate between the two input > sequences. ?IOW if we want to do something analogous to a zipper > fastener it should do this: > > zip([a,b,c,d,e,f],[1,2,3,4,5,6]) ?=> [a,1,b,2,c,3,d,4,e,5,f,6] While that is correct, the name "zip" for zip([a,b,c],[1,2,3]) => [(a,1), (b,2), (c,3)] is long-established. I generally call the alternate behaviour "interleaving" or "muxing", derived from multiplexer. While muxing and demuxing is extremely important in circuit design and telecommunications, I've never needed it in Python programming. -- Steven From rosuav at gmail.com Fri Nov 14 06:15:49 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Nov 2014 22:15:49 +1100 Subject: I don't read docs and don't know how to use Google. What does the print function do? In-Reply-To: <5465e062$0$12998$c3e8da3$5496439d@news.astraweb.com> References: <019e01cffd3d$18b60c50$4a2224f0$@us> <5465e062$0$12998$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Nov 14, 2014 at 9:58 PM, Steven D'Aprano wrote: > http://blog.codinghorror.com/why-cant-programmers-program/ > > Not everyone agrees that this is a thing: > > http://www.skorks.com/2010/10/99-out-of-100-programmers-cant-program-i-call-bullshit/ > > I'm inclined to accept that maybe 99 out of 100 *applications* for > programming jobs are from people who can't program, but I don't think that > 99 out of 100 *programmers* can't program. It's probably more like 65, > maybe 70 out of 100, tops. I was talking only about *applications* at that point. From the point of view of an applicant, the massive noise of incompetent people trying to get the job means it's really hard to get heard, especially since a lot of the incompetents can make their resumes look great. [1] So getting a job you apply for based on your own skill is... not easy. At least, I'm fairly sure it's not easy. All I know is that it's never happened to me. [1] They probably learned from all the other department heads. http://dilbert.com/strips/comic/2011-02-20/ ChrisA From steve+comp.lang.python at pearwood.info Fri Nov 14 06:15:37 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 14 Nov 2014 22:15:37 +1100 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: <5465e45a$0$12993$c3e8da3$5496439d@news.astraweb.com> Peter Cacioppi wrote: > I get the impression that most Pythonistas aren't as habituated with > assert statements as I am. Is that just a misimpression on my part? If > not, is there a good reason to assert less with Python than other > languages? I love assert, and use it frequently. But there are good reasons and bad reasons to use it. I've written an essay about the good reasons to use assert, e.g. defensive programming, program invariants, checked comments, design by contract, and when not to use them, e.g. testing arguments to public interfaces. http://import-that.dreamwidth.org/676.html > As far as I can tell, Python supports assert perfectly well. When run with > the optimization flagging, the asserts are truly removed. > > I think one needs to take care with some basic assert coding - it's not a > substitute for unit tests, it doesn't absolve you of normal exception > responsibilities, and, most of all, it should be used for passive > inspection and not action. But given these guidelines, I still find it > very useful as "active comments". Agreed completely! -- Steven From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Fri Nov 14 06:29:17 2014 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Fri, 14 Nov 2014 12:29:17 +0100 Subject: io.UnsupportedOperation: fileno References: <5afd4b4e-e0cd-4436-b15a-936637b4fe2b@googlegroups.com> Message-ID: Am 14.11.2014 00:42 schrieb satishmlmlml at gmail.com: > fileno() in not supported. Is it only in 3.1? What is the workaround? You have been asked many times about the details of your environment. Especially, you have been told that it is important to know if you directly use the Python CLI or some GUI like IDLE. I just tested the latter thing and found out that it indeed makes a difference, as it introduces a replacement for the std* stuff you are missing: >>> sys.stdin >>> sys.stdout >>> sys.stderr Calling .fileno() on such a Pseudo*File just raises an UnsupportedOperation exception. This is in contrast to using the CLI directly. From steve+comp.lang.python at pearwood.info Fri Nov 14 06:33:26 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 14 Nov 2014 22:33:26 +1100 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> Message-ID: <5465e887$0$12976$c3e8da3$5496439d@news.astraweb.com> Ethan Furman wrote: > On 11/12/2014 01:41 PM, Marko Rauhamaa wrote: >> >> Or I might indicate the exhaustion of possibilities: >> >> if status == OK: >> ... >> elif status == ERROR: >> ... >> else: >> assert status == WARNING >> ... > > And here's a nice example of what one should NOT do. Imagine that a new > status, CONFUSED is added, the above code is not modified to handle it, > and for whatever reason the program is being run optimized -- the assert > is not there, and CONFUSED is treated the same as WARNING. I agree with Marko in this case. Marko's example of defensive programming is very similar to the one I gave in my essay here: http://import-that.dreamwidth.org/676.html You're correct of course that under the circumstances you describe the code will fail. But that is no different from the scenario: "a new status is added, the code is not modified to handle it, no tests are written to check the code is correct (or if the tests are written, the test suite is not run), and then the code is released at which point it fails" We know that even the best programmer writes buggy code, which is why we invent processes like defensive programming, design by contract, test driven development, unit testing and so on. Even so, buggy code gets written and released. When that happens, it is a failure of process. If your process is so poor that you release code without running it with asserts enabled, then assert will not save you from bugs. No process is immune to sufficiently malicious or incompetent use. Assertions are just a tool, not a panacea. -- Steven From steve+comp.lang.python at pearwood.info Fri Nov 14 06:37:06 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 14 Nov 2014 22:37:06 +1100 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> Message-ID: <5465e963$0$13009$c3e8da3$5496439d@news.astraweb.com> Ethan Furman wrote: >> There's no way to make the CONFUSED status be handled without actually >> changing the code. The difference is that this version will not >> incorrectly treat CONFUSED as WARNING; it just won't do anything at >> all if the code is optimized. > > So, a different wrong thing, but still a wrong thing. ?;) And potentially a *worse* wrong thing. "I find it amusing when novice programmers believe their main job is preventing programs from crashing. ... More experienced programmers realize that correct code is great, code that crashes could use improvement, but incorrect code that doesn?t crash is a horrible nightmare." -- Chris Smith Assertions can help by this, by causing wrong code to fail as soon as possible (provided, of course, that you don't defeat the assertions by running the code with assertions disabled). -- Steven From satishmlmlml at gmail.com Fri Nov 14 06:57:24 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Fri, 14 Nov 2014 03:57:24 -0800 (PST) Subject: UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 308: character maps to Message-ID: <0a5917ca-70f3-4297-9e98-e8ed0556ee22@googlegroups.com> For 'mimetypes' in the code given below, python is giving the following error. Kindly help. >>> import os >>> matches = [] >>> for (dirname, dirshere, fileshere) in os.walk(r'C:\Python34'): for filename in fileshere: if filename.endswith('.py'): pathname = os.path.join(dirname, filename) if 'mimetypes' in open(pathname).read(): matches.append(pathname) Traceback (most recent call last): File "", line 5, in if 'mimetypes' in open(pathname).read(): File "C:\Python34\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 308: character maps to From joel.goldstick at gmail.com Fri Nov 14 07:30:01 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 14 Nov 2014 07:30:01 -0500 Subject: UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 308: character maps to In-Reply-To: <0a5917ca-70f3-4297-9e98-e8ed0556ee22@googlegroups.com> References: <0a5917ca-70f3-4297-9e98-e8ed0556ee22@googlegroups.com> Message-ID: On Fri, Nov 14, 2014 at 6:57 AM, wrote: > For 'mimetypes' in the code given below, python is giving the following error. Kindly help. > >>>> import os >>>> matches = [] >>>> for (dirname, dirshere, fileshere) in os.walk(r'C:\Python34'): > for filename in fileshere: > if filename.endswith('.py'): > pathname = os.path.join(dirname, filename) > if 'mimetypes' in open(pathname).read(): > matches.append(pathname) > > > Traceback (most recent call last): > File "", line 5, in > if 'mimetypes' in open(pathname).read(): > File "C:\Python34\lib\encodings\cp1252.py", line 23, in decode > return codecs.charmap_decode(input,self.errors,decoding_table)[0] > UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 308: character maps to You should understand encodings. There is lots of literature on the web about unicode and python. In your case, the fact that you are reading a file called cp1252.py and your code is raising a UnicodeDecodeError should be a clue > -- > https://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick http://joelgoldstick.com From vek.m1234 at gmail.com Fri Nov 14 07:26:22 2014 From: vek.m1234 at gmail.com (Veek M) Date: Fri, 14 Nov 2014 18:56:22 +0630 Subject: Python 3.x (beazley): __context__ vs __cause__ attributes in exception handling References: Message-ID: It's been answered here: http://stackoverflow.com/questions/26924045/python-3-x-beazley-context-vs- cause-attributes-in-exception-handling?noredirect=1#comment42403467_26924045 From nobody at nowhere.invalid Fri Nov 14 08:59:30 2014 From: nobody at nowhere.invalid (Nobody) Date: Fri, 14 Nov 2014 13:59:30 +0000 Subject: fileno() not supported in Python 3.1 References: Message-ID: On Thu, 13 Nov 2014 15:48:32 -0800, satishmlmlml wrote: > import sys > for stream in (sys.stdin, sys.stdout, sys.stderr): > print(stream.fileno()) > > > io.UnsupportedOperation: fileno > > Is there a workaround? Try: sys.stdin.buffer.fileno() or maybe sys.stdin.buffer.raw.fileno() In Python 3.x, sys.stdin isn't actually a "file", it's a TextIOWrapper around a BufferedReader around a file (io.FileIO). TextIOWrapper is responsible for converting a stream of bytes to a stream of (Unicode) characters. BufferedReader is responsible for buffering (like C stdio). From joel.goldstick at gmail.com Fri Nov 14 09:09:44 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 14 Nov 2014 09:09:44 -0500 Subject: fileno() not supported in Python 3.1 In-Reply-To: References: Message-ID: On Fri, Nov 14, 2014 at 8:59 AM, Nobody wrote: > On Thu, 13 Nov 2014 15:48:32 -0800, satishmlmlml wrote: > >> import sys >> for stream in (sys.stdin, sys.stdout, sys.stderr): >> print(stream.fileno()) >> >> >> io.UnsupportedOperation: fileno >> >> Is there a workaround? > > Try: > sys.stdin.buffer.fileno() > > or maybe > > sys.stdin.buffer.raw.fileno() > > In Python 3.x, sys.stdin isn't actually a "file", it's a TextIOWrapper > around a BufferedReader around a file (io.FileIO). > > TextIOWrapper is responsible for converting a stream of bytes to a stream > of (Unicode) characters. BufferedReader is responsible for buffering (like > C stdio). > A little off topic, but why not upgrade to 3.4 if you are learning python. I run 2.7, but I've read that much has improved in the 3.x series since 3.1 > > -- > https://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick http://joelgoldstick.com From bv4bv4bv4 at gmail.com Fri Nov 14 09:08:42 2014 From: bv4bv4bv4 at gmail.com (bv4bv4bv4 at gmail.com) Date: Fri, 14 Nov 2014 06:08:42 -0800 (PST) Subject: Islam prohibited women to be Unveiled....why? Message-ID: <8affef0d-5f93-49fa-b3e2-c2d13f97135e@googlegroups.com> Islam prohibited women to be Unveiled....why? Are there any harmful effects on women if they used to display parts of their body? Let us read......... According to the latest figures, the incidence of melanoma, a potentially fatal skin cancer, is increasing dramatically. It is currently the most common type of cancer in young women between the ages of 25 and 29. Researchers believe that sun exposure plays a significant role in the development of melanoma. According to Dr. Diane Berson, an American dermatologist says "intense sun exposure prior to age 20 may be more of a significant risk factor for skin cancer than sun exposure past the age of 20. Three or more blistering sunburns early in life, or three or more years of working out of doors, (e.g. camp counselors or lifeguards), without protection, can increase the risk of skin cancer by more than three times." Another study held from 1973 to 2004 found that the rate of new melanoma cases in younger women had jumped 50 percent since 1980, but did not increase for younger men in that period. "It's worrying," said Mark Purdue, a research fellow at the National Cancer Institute, who led the analysis published in the Journal of Investigative Dermatology. "What we are seeing in young adults right now could foretell a much larger number of melanoma cases in older women." he said. "One possible explanation is increases among young women of recreational sun exposure or tanning bed use," Purdue said. "Both of these things have been identified as risk factors." Statistics say that 62,000 melanoma cases are diagnosed each year in the United States, and more than 8,400 people die from the disease, according to the American Cancer Society. Previous studies have shown that the rate of new diagnoses has been increasing among adults overall. Woman's dress in Islam According to religion of Islam woman should only display her face and palms of hands in front of foreigner men (indoor and outdoor) and more than that is prohibited. Allah Almighty tells prophet Mohamed peace be upon him to order women to do the following: (And tell the believing women to lower their gaze (from looking at forbidden things), and protect their private parts (from illegal sexual acts) and not to show off their adornment except only that which is apparent (like both eyes for necessity to see the way, or outer palms of hands or one eye or dress like veil, gloves, head-cover, apron, etc.), and to draw their veils all over Juy?bihinna (i.e. their bodies, faces, necks and bosoms) and not to reveal their adornment except to their husbands, or their fathers, or their husband's fathers, or their sons, or their husband's sons, or their brothers or their brother's sons, or their sister's sons, or their (Muslim) women (i.e. their sisters in Isl?m), or the (female) slaves whom their right hands possess, or old male servants who lack vigour, or small children who have no sense of feminine sex. And let them not stamp their feet so as to reveal what they hide of their adornment. And all of you beg All?h to forgive you all, O believers, that you may be successful.){ S?rat An-N?r - The Light -verse31}. Also prophet Mohamed peace be upon him says in the right Hadith about some indications for the imminence of day of resurrection that "there will be women who are dressed and naked at the same time, who are reeling while walking and their heads are like the top of the camel, those will not enter the heaven or even smell its smell" [narrated by Abu- horraira] Muslim women who are veiled believe that their body is valuable so it should not be as a commodity that is exposed to everyone to evaluate. Conclusion The great religion of Islam doesn't approve any practice that may cause any harm to both men and women , therefore Allah Almighty and His prophet Mohamed peace be upon him order women to be veiled because woman's veil definitely respects woman than exposing her parts in front of everyone. Also, Allah Almighty didn't order women to be veiled and ordered men to do what they want but He Almighty orders men also to respect women by not to look in their parts because that is purer for them so that Allah Almighty tells the prophet to inform men to:(Tell the believing men to lower their gaze (from looking at forbidden things), and protect their private parts (from illegal sexual acts, etc.). That is purer for them. Verily, Allah is All-Aware of what they do.){ S?rat An-N?r - The Light -verse30}. ------------------------------ By: Abduldaem Al-Kaheel www.kaheel7.com/eng http://www.kaheel7.com/eng/index.php/legislative-miracles/646-islam-prohibited-women-to-be-unveiledwhy References: * http://www.webmd.com/skin-beauty/guide/sun-exposure-skin-cancer * http://www.boston.com/news/nation/washington/articles/2008/07/11/skin_cancer_on_rise_in_young_women/ * http://www.medicalnewstoday.com/articles/44764.php Thank you From ali.hallaji1 at gmail.com Fri Nov 14 09:10:34 2014 From: ali.hallaji1 at gmail.com (ali.hallaji1 at gmail.com) Date: Fri, 14 Nov 2014 06:10:34 -0800 (PST) Subject: Twisted and txJSON-RPC In-Reply-To: References: <53e3097c-edc8-4d09-8651-ec220758016f@n31g2000vbd.googlegroups.com> Message-ID: Hi, I want to write authentication with txjson-rpc. please guide me in this method! best Regards, Ali Hallaji From ali.hallaji1 at gmail.com Fri Nov 14 09:12:45 2014 From: ali.hallaji1 at gmail.com (ali.hallaji1 at gmail.com) Date: Fri, 14 Nov 2014 06:12:45 -0800 (PST) Subject: Authentication method with txjson-rpc. Message-ID: <61dc4ae1-8474-4c3c-929c-e7747021de1d@googlegroups.com> Hi, I want to write authentication by txjson, Please help me in this way. From qualsivoglia at dovetipare.nz Fri Nov 14 09:18:00 2014 From: qualsivoglia at dovetipare.nz (maurog) Date: Fri, 14 Nov 2014 14:18:00 +0000 (UTC) Subject: python on android: where to start Message-ID: I looked at the newsgroup, but I didn't find recent infos on this topic. On the other side I went lost by looking for this topic with google. So I'm asking you my question, if I want to develop or run some code with python on android, what are the resources to start with? Thanks mauro From oquanox at gmail.com Fri Nov 14 09:24:18 2014 From: oquanox at gmail.com (Mayank Tripathi) Date: Fri, 14 Nov 2014 14:24:18 +0000 Subject: python on android: where to start References: Message-ID: You can try Kivy. http://kivy.org On Fri Nov 14 2014 at 7:51:08 PM maurog wrote: > I looked at the newsgroup, but I didn't find recent infos on this topic. > On the other side I went lost by looking for this topic with google. So > I'm asking you my question, if I want to develop or run some code with > python on android, what are the resources to start with? > > Thanks > > mauro > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Fri Nov 14 09:38:36 2014 From: davea at davea.name (Dave Angel) Date: Fri, 14 Nov 2014 09:38:36 -0500 (EST) Subject: python on android: where to start References: Message-ID: maurog Wrote in message: > I looked at the newsgroup, but I didn't find recent infos on this topic. > On the other side I went lost by looking for this topic with google. So > I'm asking you my question, if I want to develop or run some code with > python on android, what are the resources to start with? > > Thanks > > mauro > My Google shows two useful sites on the first page. Qpython.com Kivy.org -- DaveA From nomail at invalid.com Fri Nov 14 10:11:28 2014 From: nomail at invalid.com (ast) Date: Fri, 14 Nov 2014 16:11:28 +0100 Subject: Two locations for module struct ? Message-ID: <54661ba8$0$2906$426a74cc@news.free.fr> Hello In module wave there is a sub module struct. You can call function pack() with: import wave val = wave.struct.pack(...) but the same function can be called with: import struct val = struct.pack(...) Is it exactly the same module in both location ? Why putting struct in two places ? From rosuav at gmail.com Fri Nov 14 11:24:56 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Nov 2014 03:24:56 +1100 Subject: Two locations for module struct ? In-Reply-To: <54661ba8$0$2906$426a74cc@news.free.fr> References: <54661ba8$0$2906$426a74cc@news.free.fr> Message-ID: On Sat, Nov 15, 2014 at 2:11 AM, ast wrote: > In module wave there is a sub module struct. > You can call function pack() with: > > import wave > val = wave.struct.pack(...) > > but the same function can be called with: > > import struct > val = struct.pack(...) > > Is it exactly the same module in both location ? > Why putting struct in two places ? I don't think that's a submodule of wave. It's just the standard struct module, which presumably wave imported. Use it as struct, not as wave.struct. ChrisA From __peter__ at web.de Fri Nov 14 11:51:35 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 Nov 2014 17:51:35 +0100 Subject: Two locations for module struct ? References: <54661ba8$0$2906$426a74cc@news.free.fr> Message-ID: ast wrote: > In module wave there is a sub module struct. > You can call function pack() with: > > import wave > val = wave.struct.pack(...) > > but the same function can be called with: > > import struct > val = struct.pack(...) > > Is it exactly the same module in both location ? You can answer that yourself: >>> import struct, wave >>> struct is wave.struct True > Why putting struct in two places ? Assumming your code is part of a module called mymodule.py > import wave > val = wave.struct.pack(...) > import struct > val = struct.pack(...) you can now also do import mymodule val = mymodule.struct.pack(...) or even val = mymodule.wave.struct.pack(...) Do you see the pattern? You should ;) From phil at riverbankcomputing.com Fri Nov 14 11:48:41 2014 From: phil at riverbankcomputing.com (Phil Thompson) Date: Fri, 14 Nov 2014 16:48:41 +0000 Subject: python on android: where to start In-Reply-To: References: Message-ID: <4dbc3121ebedf78951a1ae60195d54f5@riverbankcomputing.com> On 14/11/2014 2:18 pm, maurog wrote: > I looked at the newsgroup, but I didn't find recent infos on this > topic. > On the other side I went lost by looking for this topic with google. So > I'm asking you my question, if I want to develop or run some code with > python on android, what are the resources to start with? PyQt4 or PyQt5 with pyqtdeploy... http://pyqt.sourceforge.net/Docs/pyqtdeploy/ Phil From ian.g.kelly at gmail.com Fri Nov 14 11:51:11 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Nov 2014 09:51:11 -0700 Subject: fileno() not supported in Python 3.1 In-Reply-To: <20141114073646.GA32086@cskk.homeip.net> References: <20141114073646.GA32086@cskk.homeip.net> Message-ID: On Fri, Nov 14, 2014 at 12:36 AM, Cameron Simpson wrote: > On 13Nov2014 15:48, satishmlmlml at gmail.com wrote: >> >> import sys >> for stream in (sys.stdin, sys.stdout, sys.stderr): >> print(stream.fileno()) >> >> >> io.UnsupportedOperation: fileno >> >> Is there a workaround? > > > The first workaround that suggests itself it to use a more modern Python. > I've got 3.4.2 here, and it goes: > > Python 3.4.2 (default, Nov 5 2014, 21:19:51) > [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import sys > >>> for stream in (sys.stdin, sys.stdout, sys.stderr): > ... print(stream.fileno()) > ... > 0 > 1 > 2 > >>> > > In short, in 3.4.2 it just works. Why do you think the Python version has anything to do with it? Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> for stream in (sys.stdin, sys.stdout, sys.stderr): ... print(stream.fileno()) ... 0 1 2 Clearly, in 2.7.6 it also "just works". From ian.g.kelly at gmail.com Fri Nov 14 11:40:16 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Nov 2014 09:40:16 -0700 Subject: I love assert In-Reply-To: <5465e963$0$13009$c3e8da3$5496439d@news.astraweb.com> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> <5465e963$0$13009$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Nov 14, 2014 at 4:37 AM, Steven D'Aprano wrote: > Ethan Furman wrote: > >>> There's no way to make the CONFUSED status be handled without actually >>> changing the code. The difference is that this version will not >>> incorrectly treat CONFUSED as WARNING; it just won't do anything at >>> all if the code is optimized. >> >> So, a different wrong thing, but still a wrong thing. ;) > > And potentially a *worse* wrong thing. Potentially it's worse, but more likely doing the wrong thing will be worse than doing nothing. > "I find it amusing when novice programmers believe their main > job is preventing programs from crashing. ... More experienced > programmers realize that correct code is great, code that > crashes could use improvement, but incorrect code that doesn?t > crash is a horrible nightmare." > -- Chris Smith > > Assertions can help by this, by causing wrong code to fail as soon as > possible (provided, of course, that you don't defeat the assertions by > running the code with assertions disabled). I fail to see the relevance of this quote. The code I posted that you're responding to does use an assertion. The case where it does "a different wrong thing" is precisely the case where assertions are disabled. From nomail at invalid.com Fri Nov 14 13:12:48 2014 From: nomail at invalid.com (ast) Date: Fri, 14 Nov 2014 19:12:48 +0100 Subject: Two locations for module struct ? In-Reply-To: References: <54661ba8$0$2906$426a74cc@news.free.fr> Message-ID: <54664621$0$2391$426a74cc@news.free.fr> "Peter Otten" <__peter__ at web.de> a ?crit dans le message de news:mailman.15823.1415983912.18130.python-list at python.org... > > Do you see the pattern? You should ;) > Understood thx From ethan at stoneleaf.us Fri Nov 14 13:18:27 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Nov 2014 10:18:27 -0800 Subject: I love assert In-Reply-To: <5465e887$0$12976$c3e8da3$5496439d@news.astraweb.com> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <5465e887$0$12976$c3e8da3$5496439d@news.astraweb.com> Message-ID: <54664773.7050403@stoneleaf.us> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 11/14/2014 03:33 AM, Steven D'Aprano wrote: > > I agree with Marko in this case. Marko's example of defensive programming is very similar to the one I gave in my > essay here: > > http://import-that.dreamwidth.org/676.html > > You're correct of course that under the circumstances you describe the code will fail. But that is no different > from the scenario: > > "a new status is added, the code is not modified to handle it, no tests are written to check the code is correct > (or if the tests are written, the test suite is not run), and then the code is released at which point it fails" I am reminded of a Star Treck episode (Deep Space 9?) in which a Klingon is mocking the Federation tech for having three backups, instead of only two, to which the Federation tech replies, "When the second one fails, I wouldn't want to be without my tertiary backup!" My point being: a safety net that is so easily disabled does not count (IMHO) as a backup. > If your process is so poor that you release code without running it with asserts enabled, then assert will not save > you from bugs. This is one my very few complaints about Python: running it normally is the same as running with DEBUG turned on, so the unusual case is remembering to run with asserts turned /off/. > Assertions are just a tool, not a panacea. Right -- and using it is like using a rock when what you need is a ball-peen hammer. ;) - -- ~Ethan~ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.11 (GNU/Linux) iQIcBAEBAgAGBQJUZkdzAAoJENZ7D1rrH75Nl9YQALx9UIAxYzlzH04EoMlILErb 0wz5xNhTM2JmF3csJPi3pQSpEr1XpHhWjFZYsFoPB24I8bN7tGALb91+ME7ElHgw WP6Z+AVPuHCRxTG/oteK72+f5S+SN6zV1ECwrUuWxqIt5CHzYFtQjRKvEinNDtaT xKtEfYZdrZFeqo7ssV2gHprDd1QFIAygLMbIlwke6nT/TdMGmw/wG9LQtpfSnrQc 4BeFoeYM3OL+hxHUNfYJI9cGL7skykU3EHnuFqNbhA6QhGawvBqUhVDGoFFDkJ/e AX6AGk5Fu9cvjEFTzRQJzW4S5s6nD4dYM7Z93GfD9G9KBmfzQNM1pBA3yqxf0S8Q CWTWBs8pPkYe/G1Y/WOn7lzYQdMneIGUNnHR8fnABKPPf5IeTXabkWgtVnq1g5Ty DVcg/47G8gBMOTz5DD08iigu4f2bsNGowFoAkCDsbNmzjmxODGSUoj1ph/4xg6HP HbuEQZXwNZXmlP9ZcLoxjCKdBdRJo3JZ4hAf6kVj4VT4y438GL2dI0/KIUSDWgYE B0mCsQ7WYm80AvfpYR7fJoZsd/5jXe7RCLHanNLIZff3LupdFZri5E246KloUBj+ 3Jw3HgwME6wyDshiHtsS5tuDcANvow+PICA+wn2KmU9Mn2JNwsG3D98ZFJfXp0JR eG/Pg7cgQhrjhFqe6cgO =EoEX -----END PGP SIGNATURE----- From marko at pacujo.net Fri Nov 14 14:12:41 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 14 Nov 2014 21:12:41 +0200 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <5465e887$0$12976$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87ppcpmw9i.fsf@elektro.pacujo.net> Ethan Furman : > My point being: a safety net that is so easily disabled does not count > (IMHO) as a backup. Correct. You never lean on assertions. They are primarily formal comments. However, assertion failures do help in troubleshooting occasionally. Most importantly, they immediately, unquestionably point the finger at the developer. > This is one my very few complaints about Python: running it normally > is the same as running with DEBUG turned on, so the unusual case is > remembering to run with asserts turned /off/. I don't remember ever having optimized them out in any programming language. Has that really improved the performance of your code? Marko From emptya45 at gmail.com Fri Nov 14 13:42:38 2014 From: emptya45 at gmail.com (Empty Account) Date: Fri, 14 Nov 2014 18:42:38 +0000 Subject: Efficient Threading Message-ID: Hi, I am thinking about writing a load test tool in Python, so I am interested in how I can create the most concurrent threads/processes with the fewest OS resources. I would imagine that I/O would need to be non-blocking. There are a number of options including standard library threading, gevent, stackless python, cython parallelism etc. Because I am new to Python, I am unsure on which libraries to choose. I am not really bothered on the tool chain, just as long as it is Python related (so I'd use PyPy for example). Many Thanks Aidy -------------- next part -------------- An HTML attachment was scrubbed... URL: From sohcahtoa82 at gmail.com Fri Nov 14 14:41:10 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Fri, 14 Nov 2014 11:41:10 -0800 (PST) Subject: Help with Python Multiprocessing In-Reply-To: <2d8bf6c1-328e-486a-9d3b-3191cb7e702b@googlegroups.com> References: <91fd5810-6a2a-46d8-8d1e-b68afced3987@googlegroups.com> <2d8bf6c1-328e-486a-9d3b-3191cb7e702b@googlegroups.com> Message-ID: On Thursday, November 13, 2014 3:22:49 PM UTC-8, Anurag wrote: > On Thursday, November 13, 2014 2:18:50 PM UTC-5, sohca... at gmail.com wrote: > > On Thursday, November 13, 2014 10:07:56 AM UTC-8, Anurag wrote: > > > I am having trouble understanding the Multiprocessing module. > > > I need to run three different files 'Worker1' , 'Worker2', 'Worker3' all at once. Currently I am doing this : > > > > > > from multiprocessing import Process > > > > > > import Worker1.py > > > import Worker2.py > > > import Worker3.py > > > > > > > > > > > > p1 = Process(target=Worker1.py) > > > p1.start() > > > p2 = Process(target=Worker2.py) > > > p2.start() > > > p3 = Process(target=Worker3.py) > > > p3.start() > > > > > > But this will only start the 'Worker1'. How do I execute all the three files at once? > > > > > > Thanks > > > > Do your WorkerX.py files have a main() function or anything like that? If not, they should. Then, you'd set the targets to WorkerX.main. > > My Worker files have three different functions What I mean is that your code should probably look more like this: # Contents of main.py from multiprocessing import Process import Worker1 import Worker2 import Worker3 p1 = Process(target=Worker1.main) p1.start() p2 = Process(target=Worker2.main) p2.start() p3 = Process(target=Worker3.main) p3.start # Contents of Worker1.py def main(): # Do worker1 stuff... # Contents of Worker2.py def main(): # Do worker2 stuff... # Contents of Worker3.py def main(): # Do worker3 stuff... Alternatively, you could have a single worker.py, import that, but have 3 main() functions, main1(), main2(), main3(), and set the targets for each process to those functions. Maybe its because I'm less experienced as most people on this group, but setting a Process's target to a module and not a specific function in that module seems slightly strange and ambiguous to me. From ethan at stoneleaf.us Fri Nov 14 15:41:09 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Nov 2014 12:41:09 -0800 Subject: I love assert In-Reply-To: <87ppcpmw9i.fsf@elektro.pacujo.net> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <5465e887$0$12976$c3e8da3$5496439d@news.astraweb.com> <87ppcpmw9i.fsf@elektro.pacujo.net> Message-ID: <546668E5.6080004@stoneleaf.us> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 11/14/2014 11:12 AM, Marko Rauhamaa wrote: > Ethan Furman wrote: > >> My point being: a safety net that is so easily disabled does not count (IMHO) as a backup. > > Correct. You never lean on assertions. They are primarily formal comments. On this point we can agree. :) >> This is one my very few complaints about Python: running it normally is the same as running with DEBUG turned >> on, so the unusual case is remembering to run with asserts turned /off/. > > I don't remember ever having optimized them out in any programming language. Has that really improved the > performance of your code? In the handful of languages I have worked with so far, it's the other way 'round: you un-optimize debug mode in. CPython itself is a good example: when configuring, you must add --with-pydebug in order to get all the extra checks added (which is great when adding new features), but that option isn't used when making production CPythons; yet Python the language is just the opposite: debug mode is on /by default/, and to turn it off you have to specify -O: $ ./python -c "print(__debug__)" True $ ./python -O -c "print(__debug__)" False - -- ~Ethan~ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.11 (GNU/Linux) iQIcBAEBAgAGBQJUZmjlAAoJENZ7D1rrH75N3wMP/j9AowuuEvW9khTFX512QUHn VGwEqkIu4FDFRA8T+qzwqhL7st5GGsnXaPvaWCLmPGbtt1qrVxJ1M6LLkuSWI8Fj /hGe5rcEPP88/tMA5zy/pmg6jDgl96hojCnDmmS6meIQijVRpxMUGQ/4+N1oKI5d JYKOlhFStk0N5O6gyZ3Yc6UDY+I9kLVPZsIgH0bXx5IkvwQUi1aNboADehDgSbM5 XDCuZvfNsauKyJZL52NkKu6qLSY/CHDx4kaWdP/i75gZPeVJirjEUkcLYSK6iE19 DpkyeR5wetH1yppH27yyfZPCKHnaYD8O/rykRrQLaIYefKb7XhxGWXa4C17w+AQP 3+hjONiPBsXe2FZZNTskKufI88oXbFwTyI3GseeWTIbS+V9TIwGTjZA+V9jc6EvL T6T9PRGwOzfPolcLZ43x3ea8uCzLhxe0BILEfdmv6XPoPl9sJ5wHhbxg0oblo8GL GNkfOFw0ncxplyobU0RXhvsKCUg6EpAukWgIcX5IhHfnesoS1BpSMtZubAbY4GVI AHzL34KpYhOIDo3Ws26dCtHz5ocJSnDlHv2lxv+iEEZV+4lShFEreqfCLK0hcJTP QMFoI401Dy3bLd3wJX9mYQA+nMGhNtRK+4uYwGSbAinOGDKVuqrmNM7wCaF9lr/I aC+wno9PzNxkDNy2nUpY =gJhZ -----END PGP SIGNATURE----- From marko at pacujo.net Fri Nov 14 15:50:25 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 14 Nov 2014 22:50:25 +0200 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <5465e887$0$12976$c3e8da3$5496439d@news.astraweb.com> <87ppcpmw9i.fsf@elektro.pacujo.net> Message-ID: <87fvdlmrqm.fsf@elektro.pacujo.net> Ethan Furman : > Python the language is just the opposite: debug mode is on /by > default/, and to turn it off you have to specify -O: C's the same way. When I did Java, we enabled assertions in production code. Marko From tjreedy at udel.edu Fri Nov 14 16:47:13 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Nov 2014 16:47:13 -0500 Subject: Two locations for module struct ? In-Reply-To: <54661ba8$0$2906$426a74cc@news.free.fr> References: <54661ba8$0$2906$426a74cc@news.free.fr> Message-ID: On 11/14/2014 10:11 AM, ast wrote: > Hello > > In module wave there is a sub module struct. struct is not a documented part of the wave module. > You can call function pack() with: > > import wave > val = wave.struct.pack(...) wave imports several other stdlib modules. All are accessible the same way. None are documented or included in wave.__all__. Some modules, typically more recently written or edited, do things like import struct as _struct to avoid such leakage of import. But this is a nuisance to write and read. Best to stick with the documented api. -- Terry Jan Reedy From rriehle at itu.edu Fri Nov 14 17:09:04 2014 From: rriehle at itu.edu (Richard Riehle) Date: Fri, 14 Nov 2014 14:09:04 -0800 (PST) Subject: I love assert In-Reply-To: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: On Tuesday, November 11, 2014 11:41:06 AM UTC-8, Peter Cacioppi wrote: > I get the impression that most Pythonistas aren't as habituated with assert statements as I am. Is that just a misimpression on my part? If not, is there a good reason to assert less with Python than other languages? > > As far as I can tell, Python supports assert perfectly well. When run with the optimization flagging, the asserts are truly removed. > > I think one needs to take care with some basic assert coding - it's not a substitute for unit tests, it doesn't absolve you of normal exception responsibilities, and, most of all, it should be used for passive inspection and not action. But given these guidelines, I still find it very useful as "active comments". -------------------------------------------------------------------------- Reply & Comment: I am new to this group, but really like Python. One of the things I find helpful is to combine the assert with the decorator capability to produce code that is close to, although not identical to, the Design by Contract features built-in to Eiffel and Ada (2012). I find that not a lot of Python user really appreciate the power of decorators. Richard Riehle, PhD, International Technological University, San Jose, CA. From rriehle at itu.edu Fri Nov 14 17:17:23 2014 From: rriehle at itu.edu (Richard Riehle) Date: Fri, 14 Nov 2014 14:17:23 -0800 (PST) Subject: Array of Functions Message-ID: <42b534f0-aeef-411f-80c5-db5d20c80b55@googlegroups.com> In C, C++, Ada, and functional languages, I can create an array of functions, albeit with the nastiness of pointers in the C family. For example, an array of functions where each function is an active button, or an array of functions that behave like formulae in a spreadsheet. I am finding this a bit challenging in Python. Example: r1c1 r1c2 r1c3 r2c1 r2c2 r2c3 r3c1 r3c2 r3c3 where r1 is row 1 and c1 is column 1. Suppose I want an array where the colum three is a set of functions that operates on the other two columns, depending on the values I set for those rows and columns? As noted, I can do this pretty easily in most languages (well, except for Java which does not support any kind of functional programming capability), even if I have to use pointers. I think my difficulty is related to the REPL nature of Python. However, I am sure some clever Pythonista has found a way to do this. Thanks in advance for any suggestions, Richard Riehle, PhD, International Technological University, San Jose, CA From marko at pacujo.net Fri Nov 14 17:18:30 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Nov 2014 00:18:30 +0200 Subject: Decorators (was: Re: I love assert) References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> Message-ID: <8761ehmnnt.fsf_-_@elektro.pacujo.net> Richard Riehle : > I find that not a lot of Python user really appreciate the power of > decorators. Well, I don't. All it means is that I've never seen a use of decorators that has enhanced the code. Once I "see the light," I'll have no problem changing my view. Marko From marko at pacujo.net Fri Nov 14 17:21:13 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Nov 2014 00:21:13 +0200 Subject: Array of Functions References: <42b534f0-aeef-411f-80c5-db5d20c80b55@googlegroups.com> Message-ID: <871tp5mnja.fsf@elektro.pacujo.net> Richard Riehle : > Example: > > r1c1 r1c2 r1c3 > r2c1 r2c2 r2c3 > r3c1 r3c2 r3c3 > > where r1 is row 1 and c1 is column 1. Suppose I want an array where the > colum three is a set of functions that operates on the other two > columns, depending on the values I set for those rows and columns? As > noted, I can do this pretty easily in most languages (well, except for > Java which does not support any kind of functional programming > capability), even if I have to use pointers. Show some code in, say, Scheme (which is among the most functional programming languages in existence), and we'll see how we could translate that into Python. Marko From breamoreboy at yahoo.co.uk Fri Nov 14 17:37:30 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 14 Nov 2014 22:37:30 +0000 Subject: Decorators In-Reply-To: <8761ehmnnt.fsf_-_@elektro.pacujo.net> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <8761ehmnnt.fsf_-_@elektro.pacujo.net> Message-ID: On 14/11/2014 22:18, Marko Rauhamaa wrote: > Richard Riehle : > >> I find that not a lot of Python user really appreciate the power of >> decorators. > > Well, I don't. > > All it means is that I've never seen a use of decorators that has > enhanced the code. Once I "see the light," I'll have no problem changing > my view. > Perhaps this helps http://blog.dscpl.com.au/2014/01/how-you-implemented-your-python.html ? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From sam.raker at gmail.com Fri Nov 14 17:44:09 2014 From: sam.raker at gmail.com (Sam Raker) Date: Fri, 14 Nov 2014 14:44:09 -0800 (PST) Subject: Array of Functions In-Reply-To: <42b534f0-aeef-411f-80c5-db5d20c80b55@googlegroups.com> References: <42b534f0-aeef-411f-80c5-db5d20c80b55@googlegroups.com> Message-ID: I second the call for a more concrete implementation, but if you want the results of the functions in c3 to be responsive to the values of c1 and c2 (i.e., if you change r1c1, r1c3 returns a different value), it might be worth encapsulating the whole thing in an object and making the c3 functions properties, which is Python for 'preprocessed attributes.' On Friday, November 14, 2014 5:17:38 PM UTC-5, Richard Riehle wrote: > In C, C++, Ada, and functional languages, I can create an array of functions, albeit with the nastiness of pointers in the C family. For example, an array of functions where each function is an active button, or an array of functions that behave like formulae in a spreadsheet. I am finding this a bit challenging in Python. > > Example: > > r1c1 r1c2 r1c3 > r2c1 r2c2 r2c3 > r3c1 r3c2 r3c3 > > where r1 is row 1 and c1 is column 1. Suppose I want an array where the colum three is a set of functions that operates on the other two columns, depending on the values I set for those rows and columns? As noted, I can do this pretty easily in most languages (well, except for Java which does not support any kind of functional programming capability), even if I have to use pointers. > > I think my difficulty is related to the REPL nature of Python. However, I am sure some clever Pythonista has found a way to do this. > > Thanks in advance for any suggestions, > > Richard Riehle, PhD, International Technological University, San Jose, CA From marko at pacujo.net Fri Nov 14 17:47:45 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Nov 2014 00:47:45 +0200 Subject: Decorators References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <8761ehmnnt.fsf_-_@elektro.pacujo.net> Message-ID: <87sihll7qm.fsf@elektro.pacujo.net> Mark Lawrence : > Perhaps this helps > http://blog.dscpl.com.au/2014/01/how-you-implemented-your-python.html ? Thanks, but sorry, it didn't. I couldn't even relate to the supposed WSGI craze. I'm yet to face the situation where a colleague would point out, "See how elegantly you could have done that using a decorator." Marko From ian.g.kelly at gmail.com Fri Nov 14 17:50:42 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Nov 2014 15:50:42 -0700 Subject: Array of Functions In-Reply-To: <42b534f0-aeef-411f-80c5-db5d20c80b55@googlegroups.com> References: <42b534f0-aeef-411f-80c5-db5d20c80b55@googlegroups.com> Message-ID: On Fri, Nov 14, 2014 at 3:17 PM, Richard Riehle wrote: > In C, C++, Ada, and functional languages, I can create an array of functions, albeit with the nastiness of pointers in the C family. For example, an array of functions where each function is an active button, or an array of functions that behave like formulae in a spreadsheet. I am finding this a bit challenging in Python. > > Example: > > r1c1 r1c2 r1c3 > r2c1 r2c2 r2c3 > r3c1 r3c2 r3c3 > > where r1 is row 1 and c1 is column 1. Suppose I want an array where the colum three is a set of functions that operates on the other two columns, depending on the values I set for those rows and columns? As noted, I can do this pretty easily in most languages (well, except for Java which does not support any kind of functional programming capability), even if I have to use pointers. > > I think my difficulty is related to the REPL nature of Python. However, I am sure some clever Pythonista has found a way to do this. >>> list_of_functions = [lambda x=x: x + 4 for x in range(3)] >>> list_of_functions[0]() 4 >>> list_of_functions[1]() 5 >>> list_of_functions[2]() 6 If you want more help, you'll have to be more specific about the problem you're encountering. Since you didn't go into any detail, I'm just going to assume that it's the common pitfall of variable scoping in functions defined in a loop and point you to this FAQ answer: https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result From python at mrabarnett.plus.com Fri Nov 14 18:02:04 2014 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Nov 2014 23:02:04 +0000 Subject: Array of Functions In-Reply-To: <42b534f0-aeef-411f-80c5-db5d20c80b55@googlegroups.com> References: <42b534f0-aeef-411f-80c5-db5d20c80b55@googlegroups.com> Message-ID: <546689EC.9080908@mrabarnett.plus.com> On 2014-11-14 22:17, Richard Riehle wrote: > In C, C++, Ada, and functional languages, I can create an array of > functions, albeit with the nastiness of pointers in the C family. > For example, an array of functions where each function is an active > button, or an array of functions that behave like formulae in a > spreadsheet. I am finding this a bit challenging in Python. > > Example: > > r1c1 r1c2 r1c3 > r2c1 r2c2 r2c3 > r3c1 r3c2 r3c3 > > where r1 is row 1 and c1 is column 1. Suppose I want an array where > the colum three is a set of functions that operates on the other two > columns, depending on the values I set for those rows and columns? > As noted, I can do this pretty easily in most languages (well, except > for Java which does not support any kind of functional programming > capability), even if I have to use pointers. > > I think my difficulty is related to the REPL nature of Python. > However, I am sure some clever Pythonista has found a way to do > this. > > Thanks in advance for any suggestions, > In C, you're not creating an array of functions, but an array of _pointers_ to functions. In Python, we don't have pointers, but we do have references. For example, you can define a function: >>> def my_func(): ... print('my_func called') ... The name of the function is just a reference to that function: >>> print(my_func) You call it using (...): >>> my_func() my_func called You can store the reference in a list or bind another name to it: >>> func_by_another_name = my_func And call it by that other name: >>> func_by_another_name() my_func called Does that help? From steve+comp.lang.python at pearwood.info Fri Nov 14 18:40:55 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 15 Nov 2014 10:40:55 +1100 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> <28e159ff-3d64-4793-9082-05cf1553c7c2@googlegroups.com> <87h9y4owgc.fsf@elektro.pacujo.net> Message-ID: <54669308$0$13002$c3e8da3$5496439d@news.astraweb.com> Marko Rauhamaa wrote: > Asserts are not about notification, checking or optimization. They are > about communicating what's going on in the programmer's mind. They are > comments. Assertions can be used for *all of these things*. Assertions can be used for: - checking internal program logic; - testing pre- and post-conditions; - testing program invariants; - comments which are verified at runtime; > So why use asserts instead of comments? Not all comments can be replaced with an assertion, but some can: # once we reach here, mylist has at least two items is better turned into an assert: assert len(mylist) >= 2 To someone who is fluent in Python, the assertion is as easy to read and understandable as the English comment. And it has the added benefit that the interpreter will verify that the comment is correct at runtime. Verifying comments is important, since programmers are notorious for ignoring comments and failing to update them: http://import-that.dreamwidth.org/956.html Why would you choose a comment rather than an assertion? If the code is performance critical, and the extra cost of the assertion is significant, and you cannot reasonably run the code using -O to disable it, then a comment might be better. > Asserts *could* help in fixing bugs: > > 1. An assertion failure immediately, unambiguously, declares even to > customer service representatives that this is a terrible bug and > should be brought to R&D's attention instead of hazing the poor > customer with standard questions ("have you updated?", "have you > rebooted?"). If only that were the case :-( > 2. An assertion failure probably gives the developer an very good clue > as to what has gone wrong. There is a good chance of quickly > finding an accurate analysis and fix to the bug. In general, it is desirable to have any eventual exception occur as soon as possible to the ultimate cause of the exception. Assertions can aid in that. Languages such as Eiffel provide a rich and powerful set of different assertions, including: require ensure check debug invariant The Eiffel manual is explicit about the correct use of assertions: It should be clear from the preceding discussion that contracts are not a mechanism to test for special conditions, for example erroneous user input. For that purpose, the usual control structures ( if deposit_sum > 0 then ...) are available, complemented in applicable cases by the exception handling mechanism reviewed next. An assertion is instead a correctness condition governing the relationship between two software modules (not a software module and a human, or a software module and an external device). If sum is negative on entry to deposit, violating the precondition, the culprit is some other software element, whose author was not careful enough to observe the terms of the deal. Bluntly: Rule -- Assertion Violation: A run-time assertion violation is the manifestation of a bug. [...] That violations indicate bugs explains why it is legitimate to enable or disable assertion monitoring through mere compilation options: for a correct system -- one without bugs -- assertions will always hold, so the compilation option makes no difference to the semantics of the system. https://docs.eiffel.com/book/method/et-design-contract-tm-assertions-and-exceptions -- Steven From tjreedy at udel.edu Fri Nov 14 19:11:34 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Nov 2014 19:11:34 -0500 Subject: Array of Functions In-Reply-To: <42b534f0-aeef-411f-80c5-db5d20c80b55@googlegroups.com> References: <42b534f0-aeef-411f-80c5-db5d20c80b55@googlegroups.com> Message-ID: On 11/14/2014 5:17 PM, Richard Riehle wrote: > In C, C++, Ada, and functional languages, I can create an array of > functions, albeit with the nastiness of pointers in the C family. > For example, an array of functions where each function is an active > button, or an array of functions that behave like formulae in a > spreadsheet. Googling 'python spreadsheet', the first hit is https://manns.github.io/pyspread/ "Pyspread expects Python expressions in its grid cells," and expressions can reference other cells. There may be other relevant programs. > I am finding this a bit challenging in Python. Since python functions are objects, they easy fit into any array of objects. They can also be the values in dicts. Since strings can be passed to built-in runtime compile, eval, and exec functions, (not part of standard C), functions can also be represented by a return expression, as in Pyspread, or even quoted def statements. A program that executes user-entered code is much easier in Python than in C or any other language where one would have to write or find lexer, parser, compiler, and execution functions. > I think my difficulty is related to the REPL nature of Python. I do not understand this. The interpreter runs a REPL in interactive mode but can also run in batch mode. -- Terry Jan Reedy From marko at pacujo.net Fri Nov 14 19:12:14 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Nov 2014 02:12:14 +0200 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> <28e159ff-3d64-4793-9082-05cf1553c7c2@googlegroups.com> <87h9y4owgc.fsf@elektro.pacujo.net> <54669308$0$13002$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87h9y1l3tt.fsf@elektro.pacujo.net> Steven D'Aprano : > Marko Rauhamaa wrote: > >> Asserts are not about notification, checking or optimization. They are >> about communicating what's going on in the programmer's mind. They are >> comments. > > Assertions can be used for *all of these things*. > > Assertions can be used for: > > - checking internal program logic; > - testing pre- and post-conditions; > - testing program invariants; > - comments which are verified at runtime; Most importantly, assertion failures are not supposed to be recovered from (within the program). Assertion failures can result in the loss of life and limb. They can result in database corruption. They can result in monetary losses. They can result in smoke coming out of the monitor. That's because the programmer is in no way prepared for the assertion to fail and cannot rely on the assertions to really be checked. IOW, assertions are not a mechanism for fault-tolerant programming. Marko From rosuav at gmail.com Fri Nov 14 20:04:50 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Nov 2014 12:04:50 +1100 Subject: I love assert In-Reply-To: <87h9y1l3tt.fsf@elektro.pacujo.net> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> <28e159ff-3d64-4793-9082-05cf1553c7c2@googlegroups.com> <87h9y4owgc.fsf@elektro.pacujo.net> <54669308$0$13002$c3e8da3$5496439d@news.astraweb.com> <87h9y1l3tt.fsf@elektro.pacujo.net> Message-ID: On Sat, Nov 15, 2014 at 11:12 AM, Marko Rauhamaa wrote: > Most importantly, assertion failures are not supposed to be recovered > from (within the program). Assertion failures can result in the loss of > life and limb. They can result in database corruption. They can result > in monetary losses. They can result in smoke coming out of the monitor. Or, in theory, AssertionError just prevented any of the above from happening. ChrisA From marko at pacujo.net Fri Nov 14 20:30:13 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Nov 2014 03:30:13 +0200 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> <28e159ff-3d64-4793-9082-05cf1553c7c2@googlegroups.com> <87h9y4owgc.fsf@elektro.pacujo.net> <54669308$0$13002$c3e8da3$5496439d@news.astraweb.com> <87h9y1l3tt.fsf@elektro.pacujo.net> Message-ID: <87a93tl07u.fsf@elektro.pacujo.net> Chris Angelico : > On Sat, Nov 15, 2014 at 11:12 AM, Marko Rauhamaa wrote: >> Most importantly, assertion failures are not supposed to be recovered >> from (within the program). Assertion failures can result in the loss >> of life and limb. They can result in database corruption. They can >> result in monetary losses. They can result in smoke coming out of the >> monitor. > > Or, in theory, AssertionError just prevented any of the above from > happening. I'd advice against catching AssertionError and trying to recover from it within the program. You could catch it, log it and reraise it, but since the failure modes could be completely unexpected (really, by definition), I would move fault-tolerance outside the failing process and try to restore a coherent reality from there. Assertion errors are in the same class with CPython bugs, external signals (say, SIGKILL), security breaches, hardware failures and the like. For expected failure modes, other exceptions are a suitable facility. Marko From rosuav at gmail.com Fri Nov 14 20:48:44 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Nov 2014 12:48:44 +1100 Subject: I love assert In-Reply-To: <87a93tl07u.fsf@elektro.pacujo.net> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> <28e159ff-3d64-4793-9082-05cf1553c7c2@googlegroups.com> <87h9y4owgc.fsf@elektro.pacujo.net> <54669308$0$13002$c3e8da3$5496439d@news.astraweb.com> <87h9y1l3tt.fsf@elektro.pacujo.net> <87a93tl07u.fsf@elektro.pacujo.net> Message-ID: On Sat, Nov 15, 2014 at 12:30 PM, Marko Rauhamaa wrote: > Chris Angelico : > >> On Sat, Nov 15, 2014 at 11:12 AM, Marko Rauhamaa wrote: >>> Most importantly, assertion failures are not supposed to be recovered >>> from (within the program). Assertion failures can result in the loss >>> of life and limb. They can result in database corruption. They can >>> result in monetary losses. They can result in smoke coming out of the >>> monitor. >> >> Or, in theory, AssertionError just prevented any of the above from >> happening. > > I'd advice against catching AssertionError and trying to recover from it > within the program. You could catch it, log it and reraise it, but since > the failure modes could be completely unexpected (really, by > definition), I would move fault-tolerance outside the failing process > and try to restore a coherent reality from there. I agree - never catch it. But you should be able to prevent database corruption: conn = establish_database_connection() try: do_stuff() finally: conn.rollback() The raising of AssertionError anywhere inside do_stuff() will prevent craziness from getting to the database, because it aborts the execution. (You know, the way a royal pardon does.) ChrisA From python.list at tim.thechases.com Fri Nov 14 21:14:53 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 14 Nov 2014 20:14:53 -0600 Subject: I love assert In-Reply-To: References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> <28e159ff-3d64-4793-9082-05cf1553c7c2@googlegroups.com> <87h9y4owgc.fsf@elektro.pacujo.net> <54669308$0$13002$c3e8da3$5496439d@news.astraweb.com> <87h9y1l3tt.fsf@elektro.pacujo.net> <87a93tl07u.fsf@elektro.pacujo.net> Message-ID: <20141114201453.16a034df@bigbox.christie.dr> On 2014-11-15 12:48, Chris Angelico wrote: > conn = establish_database_connection() > try: > do_stuff() > finally: > conn.rollback() this sounds suspiciously like you'd never actually commit. Do you mean something like conn = establisth_database_connection() try: do_stuff(conn) except: conn.rollback() raise instead? I don't generally like bare excepts, but in this case, the exception just gets re-raised, so I feel Less Bad? about it (there's still the case where the rollback call raises some alternate exception, obfuscating the underlying root issue). -tkc From rosuav at gmail.com Fri Nov 14 21:16:50 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Nov 2014 13:16:50 +1100 Subject: I love assert In-Reply-To: <20141114201453.16a034df@bigbox.christie.dr> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <87y4rgozgd.fsf@elektro.pacujo.net> <0cdc67f4-d9d5-4a73-91fe-7558161246af@googlegroups.com> <28e159ff-3d64-4793-9082-05cf1553c7c2@googlegroups.com> <87h9y4owgc.fsf@elektro.pacujo.net> <54669308$0$13002$c3e8da3$5496439d@news.astraweb.com> <87h9y1l3tt.fsf@elektro.pacujo.net> <87a93tl07u.fsf@elektro.pacujo.net> <20141114201453.16a034df@bigbox.christie.dr> Message-ID: On Sat, Nov 15, 2014 at 1:14 PM, Tim Chase wrote: > On 2014-11-15 12:48, Chris Angelico wrote: >> conn = establish_database_connection() >> try: >> do_stuff() >> finally: >> conn.rollback() > > this sounds suspiciously like you'd never actually commit. Do you > mean something like > > conn = establisth_database_connection() > try: > do_stuff(conn) > except: > conn.rollback() > raise No; I prefer to have the commit be as close as possible to the code that needs it done. So in this toy example, the commit would be inside - maybe deep inside - do_stuff(). After committing, rolling back wouldn't hurt. ChrisA From rriehle at itu.edu Fri Nov 14 21:19:25 2014 From: rriehle at itu.edu (Richard Riehle) Date: Fri, 14 Nov 2014 18:19:25 -0800 (PST) Subject: Decorators (was: Re: I love assert) In-Reply-To: <8761ehmnnt.fsf_-_@elektro.pacujo.net> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <8761ehmnnt.fsf_-_@elektro.pacujo.net> Message-ID: <26dba8fd-e403-4129-ad57-11376eb807bd@googlegroups.com> On Friday, November 14, 2014 2:18:48 PM UTC-8, Marko Rauhamaa wrote: > Richard Riehle : > > > I find that not a lot of Python user really appreciate the power of > > decorators. > > Well, I don't. > > All it means is that I've never seen a use of decorators that has > enhanced the code. Once I "see the light," I'll have no problem changing > my view. > > > Marko Decorators are new in Python, so there are not a lot of people using them. From my experience with other languages, especially Ada and Eiffel, I enjoy the benefit of assertions (as pre-conditions and post-conditions and invariants) at the specification level (not embedded in the code), so decorators are closer to my other experience. They bring me closer to the Design by Contract model of Ada and Eiffel. That is why I was so pleased to see them added to Python. It is true, however, that they are not immediately intutive in Python, but once understood, they are handy IMHO for improving code reliability. Perhaps I was spoiled by having this capability in some other languages. From oquanox at gmail.com Fri Nov 14 21:36:41 2014 From: oquanox at gmail.com (Mayank Tripathi) Date: Sat, 15 Nov 2014 02:36:41 +0000 Subject: Decorators (was: Re: I love assert) References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <8761ehmnnt.fsf_-_@elektro.pacujo.net> <26dba8fd-e403-4129-ad57-11376eb807bd@googlegroups.com> Message-ID: Decorators were there in Python 2.4, released in 2005. Not exactly new. On Sat Nov 15 2014 at 7:51:11 AM Richard Riehle wrote: > On Friday, November 14, 2014 2:18:48 PM UTC-8, Marko Rauhamaa wrote: > > Richard Riehle : > > > > > I find that not a lot of Python user really appreciate the power of > > > decorators. > > > > Well, I don't. > > > > All it means is that I've never seen a use of decorators that has > > enhanced the code. Once I "see the light," I'll have no problem changing > > my view. > > > > > > Marko > > Decorators are new in Python, so there are not a lot of people using > them. From my experience with other languages, especially Ada and Eiffel, > I enjoy the benefit of assertions (as pre-conditions and post-conditions > and invariants) at the specification level (not embedded in the code), so > decorators are closer to my other experience. They bring me closer to the > Design by Contract model of Ada and Eiffel. That is why I was so pleased > to see them added to Python. > > It is true, however, that they are not immediately intutive in Python, but > once understood, they are handy IMHO for improving code reliability. > Perhaps I was spoiled by having this capability in some other languages. > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Fri Nov 14 21:58:04 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 15 Nov 2014 13:58:04 +1100 Subject: I love assert References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <5465e887$0$12976$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5466c13d$0$13009$c3e8da3$5496439d@news.astraweb.com> Ethan Furman wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On 11/14/2014 03:33 AM, Steven D'Aprano wrote: >> >> I agree with Marko in this case. Marko's example of defensive programming >> is very similar to the one I gave in my essay here: >> >> http://import-that.dreamwidth.org/676.html >> >> You're correct of course that under the circumstances you describe the >> code will fail. But that is no different from the scenario: >> >> "a new status is added, the code is not modified to handle it, no tests >> are written to check the code is correct (or if the tests are written, >> the test suite is not run), and then the code is released at which point >> it fails" > > I am reminded of a Star Treck episode (Deep Space 9?) in which a Klingon > is mocking the Federation tech for having three backups, instead of only > two, to which the Federation tech replies, "When the second one fails, I > wouldn't want to be without my tertiary backup!" > > My point being: a safety net that is so easily disabled does not count > (IMHO) as a backup. Assertions are not a backup or a safety net. They are development tools, like functional requirements, unit tests, code review and the use of version control. Like any tool, you need to use it correctly. Writing assertions but never actually running them is not correct use of assertions, just like writing tests but never actually running them is not correct use of tests. One wouldn't say that code review by a senior developer before code is checked into the main branch is pointless because "if the developer doesn't perform the review, buggy code might be checked in". Well duh. >> If your process is so poor that you release code without running it with >> asserts enabled, then assert will not save you from bugs. > > This is one my very few complaints about Python: running it normally is > the same as running with DEBUG turned on, so the unusual case is > remembering to run with asserts turned /off/. That's curious. Your complaint is that asserts are too easy to disable, nevertheless it takes a deliberate and conscious act to disable them. By default, Python runs assertions. And yet that is your complaint, so I suppose that you would rather asserts *didn't* run by default and you needed a deliberate act to run in debug mode. That doesn't seem consistent to me. >> Assertions are just a tool, not a panacea. > > Right -- and using it is like using a rock when what you need is a > ball-peen hammer. ;) Compared to Eiffel, Python doesn't have a lot of flexibility to assertions. You either run them all, or you run none of them. But the assertions themselves can be as narrow or as broad as you like. It's just code, you can do anything you like in it. -- Steven From software.by.python at gmail.com Fri Nov 14 22:01:55 2014 From: software.by.python at gmail.com (pythonista) Date: Fri, 14 Nov 2014 19:01:55 -0800 (PST) Subject: Question about installing python and modules on Red Hat Linux 6 Message-ID: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> I am developing a python application as a contractor. I would like to know if someone can provide me with some insight into the problems that then infrastructure team has been having. The scope of the project was to install python 2.7.8 and 4 modules/site packages on a fresh linux build. The first team failed after almost 3 weeks of work. Then they put their star Linux administrator on the task and it took almost a week of considerable effort. I was able to perform the same task on my windows desktop in less than a morning. I cannot get a straight answer as to what the problems are. They just seemed to be building and rebuilding all of the components from scratch. Can anyone provide me with insight as to the scope what the problem could have been? Thanks From cs at zip.com.au Fri Nov 14 21:39:58 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 15 Nov 2014 13:39:58 +1100 Subject: fileno() not supported in Python 3.1 In-Reply-To: References: Message-ID: <20141115023958.GA83867@cskk.homeip.net> On 14Nov2014 09:51, Ian Kelly wrote: >On Fri, Nov 14, 2014 at 12:36 AM, Cameron Simpson wrote: >> On 13Nov2014 15:48, satishmlmlml at gmail.com wrote: >>> import sys >>> for stream in (sys.stdin, sys.stdout, sys.stderr): >>> print(stream.fileno()) >>> io.UnsupportedOperation: fileno >>> >>> Is there a workaround? >> >> The first workaround that suggests itself it to use a more modern Python. >> I've got 3.4.2 here, and it goes: [... works just fine ...] > >Why do you think the Python version has anything to do with it? >Python 2.7.6 (default, Mar 22 2014, 22:59:56) [... works just fine ...] >Clearly, in 2.7.6 it also "just works". Yeah, true. I think the consensus is now that the OP is using some kind of IDE where the IO streams are not connected to terminals or other real OS-level files, but to stream abstractions delivering the the IDE display widgetry. Thus no .fileno() facility, because there is no OS-level file. But we have yet to obtain that information from the OP. Cheers, Cameron Simpson That's about as good as when one of my students left me a note signed 'anon.'--written on personalized stationery. - Ayse Sercan From ethan at stoneleaf.us Fri Nov 14 23:09:37 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Nov 2014 20:09:37 -0800 Subject: I love assert In-Reply-To: <5466c13d$0$13009$c3e8da3$5496439d@news.astraweb.com> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <87a93wqeq3.fsf@elektro.pacujo.net> <5465e887$0$12976$c3e8da3$5496439d@news.astraweb.com> <5466c13d$0$13009$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5466D201.9080400@stoneleaf.us> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 11/14/2014 06:58 PM, Steven D'Aprano wrote: > Ethan Furman wrote: >> >> My point being: a safety net that is so easily disabled does not count (IMHO) as a backup. > > Assertions are not a backup or a safety net. [...] Would you be happier if I phrased that as: Defensive programming techniques that can be unknowingly disabled by the end-user aren't very helpful? >>> If your process is so poor that you release code without running it with asserts enabled, then assert will not >>> save you from bugs. >> >> This is one my very few complaints about Python: running it normally is the same as running with DEBUG turned >> on, so the unusual case is remembering to run with asserts turned /off/. > > That's curious. Your complaint is that asserts are too easy to disable, nevertheless it takes a deliberate and > conscious act to disable them. And more likely they were disabled because somebody was trying to get more performance from the app, not because that someone thought, "I know, I'll turn asserts off and see how badly I can corrupt all my data." > By default, Python runs assertions. And yet that is your complaint, so I suppose that you would rather asserts > *didn't* run by default and you needed a deliberate act to run in debug mode. That is correct. > That doesn't seem consistent to me. Because debug mode runs by default, many folks (myself included) simply run everything in debug mode. I have never even considered, until this very moment, to run my unittests with -O. And yet the very purpose of -O is to (hopefully) get more performance. So you end up with folks using asserts inappropriately, yet their tests pass. They distribute their code. Somebody has a slower machine, or gobs of data, so they decide to use -O. Asserts are disabled, something somewhere isn't checked, an error passes silently, the wrong thing happens... I'll you use your imagination for what happens next. Having debug mode be the default makes it too easy to screw up. And yes, I am aware of at least one very large, complex, and modular system that uses Python, Javascript, CSS, HTML, and some templating language I don't remember the name of. It allows for third-party module integration. It checks third-party code with asserts. It checks user-input with asserts. I strongly suspect that if debug mode was not the default, this particular abuse wouldn't happen nearly as frequently as it does. - -- ~Ethan~ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.11 (GNU/Linux) iQIcBAEBAgAGBQJUZtIBAAoJENZ7D1rrH75NmJAP/jmW9GhlR2TeThlUoiIaslVU qKgiUeNplab9rbbIfQigmZaSTh/n+CeSK9pCu5dIOz7m6oBGoqtWJGFIl+E7pAsz +MWLCDCIzCi4AGslDZ3ZZSW+e1zG2EK2BgNtLuh3EV4fBJq9GSNDfzlsUbXO7qnQ yO0h41QuFOMuPiXDGkZ979u5OOBoH1JRUjmXhfUOSua0YcJ1dyRxNJKyhsMyUYPn relMcTyT04rXj/sl3LUFgaO898mV7ieKgB5tBybAg5EKpArzpnAeIgMjcTP8B6YH f+2n0jyL56oCCA0CO4BWP31unD8v89hBBeVJo0weprS9owq8OAdfyjXdfYMM77sM oeQjCM8rs7uej17l4joGfvkrAnsa1BQLyhWzk0aeH4xpfMkgLHVnbwRt6v2PvPWK IxNraSQQm3UjL1o1trLVznxT2+TOnNUucAl0XSLWSnIo9H1NJmYBZdHpmXvfo7R5 qIo1MyrQYLful+iaNI1I+5A3KLrKOduHm6Uqf4mDKXX6hMMbOdT1lHHpuD/fJYWW jNqOiMpZl3NtxuEJjdLc5mvXvkoTZ9Z188WfFvFNnsL27aGxFfuulAWKc6EpbWgW +8VoXVVhgs1mcB4UHM5dFrRSG7CgZi+btfHEGympWv74zun9FHHu2hNg+XPDibtS D5P2/nCwQYFuCgapy+Ko =QH9H -----END PGP SIGNATURE----- From python.list at tim.thechases.com Fri Nov 14 21:30:38 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 14 Nov 2014 20:30:38 -0600 Subject: Decorators (was: Re: I love assert) In-Reply-To: <26dba8fd-e403-4129-ad57-11376eb807bd@googlegroups.com> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <8761ehmnnt.fsf_-_@elektro.pacujo.net> <26dba8fd-e403-4129-ad57-11376eb807bd@googlegroups.com> Message-ID: <20141114203038.038fc698@bigbox.christie.dr> On 2014-11-14 18:19, Richard Riehle wrote: > Decorators are new in Python, so there are not a lot of people > using them. Um...they were introduced in 2.4 which was released in late 2004. So they've only been around for about (almost exactly) a decade. Not sure that qualifies as "new in Python". And decorators are used pretty regularly in just about every code-base that I've touched (I've been programming in Python since early 2004, so I've maintained pre-2.4 code without decorators and then brought it forward to 2.4 where decorators were usable). -tkc From rosuav at gmail.com Sat Nov 15 00:09:51 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Nov 2014 16:09:51 +1100 Subject: Question about installing python and modules on Red Hat Linux 6 In-Reply-To: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> References: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> Message-ID: On Sat, Nov 15, 2014 at 2:01 PM, pythonista wrote: > The scope of the project was to install python 2.7.8 and 4 modules/site packages on a fresh linux build. > > The first team failed after almost 3 weeks of work. > > Then they put their star Linux administrator on the task and it took almost a week of considerable effort. > > I was able to perform the same task on my windows desktop in less than a morning. > > I cannot get a straight answer as to what the problems are. Well, you're asking the wrong people. The crystal ball manufacturer around here is horribly shoddy, shipping us faulty optics and devices with frequent outages. But if you ask the people who did the work, they should be able to tell you what was happening. My suspicion here is that the admins were trying to use multiple different installation methods, and they ran into issues. This currently can't happen on Windows, as there simply isn't a system-provided package manager (though that may be changing - soon Windows people will have all the same advantages AND disadvantages that everyone else has!), hence you perhaps found it easier. On my Debian systems, I can use "apt-get install python python-bs4 python-django" and grab a consistent set of packages from the OS-provided repositories; or alternatively, I can use pip to get things from the Python-provided repository (PyPI). Trying to use both can cause issues. Want an easy solution? Get a recent Python (preferably 3.x, but otherwise the latest builds of 2.7 should do I think), get pip, get virtualenv, and then do everything inside a venv with "pip install" (maybe using requirements.txt to save you the hassle of keying everything in). You'll find that that "just works", pretty much all the time. It's perhaps more work than you truly need (I personally don't usually bother with a venv), but that way you can be sure you're not trampling all over anything else. ChrisA From cs at zip.com.au Sat Nov 15 00:11:44 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 15 Nov 2014 16:11:44 +1100 Subject: Question about installing python and modules on Red Hat Linux 6 In-Reply-To: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> References: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> Message-ID: <20141115051144.GA89182@cskk.homeip.net> On 14Nov2014 19:01, pythonista wrote: >I am developing a python application as a contractor. >I would like to know if someone can provide me with some insight into the problems that then infrastructure team has been having. >The scope of the project was to install python 2.7.8 and 4 modules/site packages on a fresh linux build. >The first team failed after almost 3 weeks of work. >Then they put their star Linux administrator on the task and it took almost a week of considerable effort. >I was able to perform the same task on my windows desktop in less than a morning. >I cannot get a straight answer as to what the problems are. >They just seemed to be building and rebuilding all of the components from scratch. >Can anyone provide me with insight as to the scope what the problem could have been? It depends. If they were trying to interoperate with the vendor supplied Python, they could be fighting with the RPM system. When I do this these days I do two things: - fetch and build Python 2.7.8 from source, to install in /usr/local/python-2.7.8 (i.e. use that as the --prefix option for configure). At this point you could just proceed and use that python, installing inside its site-packages as usual. Or you could go a little further and make a virtualenv for your project: - fetch virtualenv and (blasphemy!) install it in the vendor space using: "python setup.py install" - create a virtualenv for your project: "/usr/local/python-2.7.8/bin/python2.7 virtualenv.py /usr/local/venv-2.7.8-your-project-name" At that point you will have a "bin" directory inside /usr/local/venv-2.7.8-your-project-name with "python" and so forth. Executing that "python" runs the python-2.7.8 you built earlier but with all the system paths set to install and use the lib tree inside the virtualenv directory. The nice thing about that is that it is easy to make multiple virtualenvs, using distinct collections of additional packages, nicely isolated and easy to invoke (just run the "python" from within the appropriate virtualenv tree). Cheers, Cameron Simpson I just kept it wide-open thinking it would correct itself. Then I ran out of talent. - C. Fittipaldi From cs at zip.com.au Sat Nov 15 01:29:48 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 15 Nov 2014 17:29:48 +1100 Subject: Efficient Threading In-Reply-To: References: Message-ID: <20141115062948.GA5154@cskk.homeip.net> On 14Nov2014 18:42, Empty Account wrote: >I am thinking about writing a load test tool in Python, so I am interested >in how I can create the most concurrent threads/processes with the fewest >OS resources. I would imagine that I/O would need to be non-blocking. > >There are a number of options including standard library threading, gevent, >stackless python, cython parallelism etc. Because I am new to Python, I am >unsure on which libraries to choose. I am not really bothered on the tool >chain, just as long as it is Python related (so I'd use PyPy for example). The locust.io load test tool uses gevent and seems to like it. I do not know enough to make a recommendation myself, but I believe they use it for the same reasons you have. Cheers, Cameron Simpson Whatever is not nailed down is mine. What I can pry loose is not nailed down. - Collis P. Huntingdon From marko at pacujo.net Sat Nov 15 02:00:09 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Nov 2014 09:00:09 +0200 Subject: Decorators References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <8761ehmnnt.fsf_-_@elektro.pacujo.net> <26dba8fd-e403-4129-ad57-11376eb807bd@googlegroups.com> Message-ID: <87zjbtj6di.fsf@elektro.pacujo.net> Tim Chase : > And decorators are used pretty regularly in just about every code-base > that I've touched (I've been programming in Python since early 2004, > so I've maintained pre-2.4 code without decorators and then brought it > forward to 2.4 where decorators were usable). Funny. My experience with Python is about as old, and I have yet to encounter them in code. I have seen (maybe even used) @staticmethod once or twice over a decade and then as a magic keyword rather than a "decorator pattern." Marko From rriehle at itu.edu Sat Nov 15 02:42:00 2014 From: rriehle at itu.edu (Richard Riehle) Date: Fri, 14 Nov 2014 23:42:00 -0800 Subject: Decorators (was: Re: I love assert) In-Reply-To: References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <8761ehmnnt.fsf_-_@elektro.pacujo.net> <26dba8fd-e403-4129-ad57-11376eb807bd@googlegroups.com> Message-ID: Mayank, Thanks. I have only been using Python for about four years, so there are features I have only recently discovered. Decorators are one of them. So far, I encounter other Python users who are also unfamiliar with them. When I discovered them, I instantly saw how they could be valuable. Richard Riehle, PhD Core Faculty, ITU On Fri, Nov 14, 2014 at 6:36 PM, Mayank Tripathi wrote: > Decorators were there in Python 2.4, released in 2005. Not exactly new. > > On Sat Nov 15 2014 at 7:51:11 AM Richard Riehle wrote: > >> On Friday, November 14, 2014 2:18:48 PM UTC-8, Marko Rauhamaa wrote: >> > Richard Riehle : >> > >> > > I find that not a lot of Python user really appreciate the power of >> > > decorators. >> > >> > Well, I don't. >> > >> > All it means is that I've never seen a use of decorators that has >> > enhanced the code. Once I "see the light," I'll have no problem changing >> > my view. >> > >> > >> > Marko >> >> Decorators are new in Python, so there are not a lot of people using >> them. From my experience with other languages, especially Ada and Eiffel, >> I enjoy the benefit of assertions (as pre-conditions and post-conditions >> and invariants) at the specification level (not embedded in the code), so >> decorators are closer to my other experience. They bring me closer to the >> Design by Contract model of Ada and Eiffel. That is why I was so pleased >> to see them added to Python. >> >> It is true, however, that they are not immediately intutive in Python, >> but once understood, they are handy IMHO for improving code reliability. >> Perhaps I was spoiled by having this capability in some other languages. >> -- >> https://mail.python.org/mailman/listinfo/python-list >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Sat Nov 15 05:39:30 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 15 Nov 2014 21:39:30 +1100 Subject: Curious function argument References: <54635bce$0$2384$426a74cc@news.free.fr> Message-ID: <54672d63$0$12983$c3e8da3$5496439d@news.astraweb.com> ast wrote: > Hello > > I saw in a code from a previous message in this forum > a curious function argument. > > def test(x=[0]): > print(x[0]) ## Poor man's object > x[0] += 1 > >>>> test() > 0 >>>> test() > 1 >>>> test() > 2 >>>> > > I understand that the author wants to implement a global > variable x . It would be better to write 'global x' inside the > function. No, it's not a global. A better description is that it is a way of faking static storage for a function: the function test has a "static variable" x which is independent of any other function's x, but it can remember its value from one function call to another. > At first test() function call, it prints 0, that's OK. > But at the second call, since we dont pass any argument to test(), > x should be equal to its default value [0] (a single item list). But > it seems that Python keeps the original object whose content has > been changed to 1. > > Is it a usual way to implement a global variable ? No, it's unusual. If you actually want a global, use the global keyword. Otherwise, there are often better ways to get a similar effect, such as using a generator: def gen(): x = 0 while True: yield x x += 1 it = gen() next(it) # returns 0 next(it) # returns 1 next(it) # returns 2 You can turn that into functional form like this: import functools func = functools.partial(next, gen()) func() # returns 0 func() # returns 1 func() # returns 2 -- Steven From p.f.moore at gmail.com Sat Nov 15 05:45:05 2014 From: p.f.moore at gmail.com (Paul Moore) Date: Sat, 15 Nov 2014 10:45:05 +0000 Subject: Call for information - What assumptions can I make about Unix users' access to Windows? In-Reply-To: References: Message-ID: On 7 November 2014 15:46, Paul Moore wrote: > To that end, I'd like to get an idea of what sort of access to Windows > a typical Unix developer would have. Thanks to all who contributed to this thread. Based on the feedback, I think it's going to be useful to provide two options. First of all, an EC2 AMI that can be used by people without access to a local Windows system. While other cloud providers are a possibility, EC2 provides a free tier (for the first year) and is well-known, so it's probably the easiest to get started with (at least it was for me!) Also, I will provide a script that can be used to automatically build the environment on a newly-installed machine. The idea is that you can use this on a Windows VM (something that a number of people have said they have access to). The script may be usable on an existing machine, but it's hard to make it robust, as there are too many failure modes to consider (software already installed, configuration and/or permission differences, etc). So while such use may be possible, I probably won't consider it as supported. Thanks again, Paul From steve+comp.lang.python at pearwood.info Sat Nov 15 05:52:38 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 15 Nov 2014 21:52:38 +1100 Subject: How about some syntactic sugar for " __name__ == '__main__' "? References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> Message-ID: <54673077$0$12976$c3e8da3$5496439d@news.astraweb.com> John Ladasky wrote: > I have taught Python to several students over the past few years. As I > have worked with my students, I find myself bothered by the programming > idiom that we use to determine whether a module is being executed or > merely imported: > > "if __name__ == '__main__':" > > The use of two dunder tokens -- one as a name in a namespace, and the > other as a string, is intimidating. It exposes too much of Python's guts. The dunders are a tad ugly, but it's actually quite simple and elegant: * every module has a global variable `__name__` which normally holds the name of the module: py> import functools py> functools.__name__ 'functools' py> import math as foobarbaz py> foobarbaz.__name__ 'math' * When Python imports a module, it sets the global __name__ to that module's actual name (as taken from the file name). * But when Python runs a file, as in `python2.7 path/to/script.py`, it sets the global __name__ to the magic value '__main__' instead of "script". The consequence is that every module can tell whether it is being run as a script or not by inspecting the __name__ global. That's all there is to it. -- Steven From steve+comp.lang.python at pearwood.info Sat Nov 15 06:09:11 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 15 Nov 2014 22:09:11 +1100 Subject: How about some syntactic sugar for " __name__ == '__main__' "? References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> Message-ID: <54673458$0$12999$c3e8da3$5496439d@news.astraweb.com> Chris Kaynor wrote: > I was thinking along the lines of replacing: > > if __name__ == "__main__": > <<>> > > with > > @main > def myFunction() > <<<> > > Both blocks of code will be called at the same time. You can't guarantee that, because you cannot tell ahead of time when the "if __name__" statement will be run. It is *usually* at the end of the file, but that's just the normal useful convention, it is not a hard requirement. The current idiom uses normal, unmagical execution of Python code. When the interpreter reaches the "if __name__ ..." statement, it executes that statement, just like every other statement. There's no magic involved here, and in fact I have written code with *multiple* such "if __name__" blocks. Here's a sketch of the sort of thing I mean: import a import b if __name__ == '__main__': import c as d else: import d def this(): ... def that(): ... flag = __name__ == '__main__' process(flag) if __name__ == '__main__' or condition(): print "still executing" main() print "done loading" (I haven't ever done *all* of these things in a *single* file, but I have done all these things at one time or another.) There's no way that any automatic system can match that for flexibility or simplicity. -- Steven From steve+comp.lang.python at pearwood.info Sat Nov 15 06:23:46 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 15 Nov 2014 22:23:46 +1100 Subject: fileno() not supported in Python 3.1 References: <20141114073646.GA32086@cskk.homeip.net> Message-ID: <546737c3$0$12977$c3e8da3$5496439d@news.astraweb.com> Ian Kelly wrote: > On Fri, Nov 14, 2014 at 12:36 AM, Cameron Simpson wrote: >> On 13Nov2014 15:48, satishmlmlml at gmail.com >> wrote: >>> >>> import sys >>> for stream in (sys.stdin, sys.stdout, sys.stderr): >>> print(stream.fileno()) >>> >>> >>> io.UnsupportedOperation: fileno >>> >>> Is there a workaround? >> >> >> The first workaround that suggests itself it to use a more modern Python. >> I've got 3.4.2 here, and it goes: >> >> Python 3.4.2 (default, Nov 5 2014, 21:19:51) >> [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)] on darwin >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import sys >> >>> for stream in (sys.stdin, sys.stdout, sys.stderr): >> ... print(stream.fileno()) >> ... >> 0 >> 1 >> 2 >> >>> >> >> In short, in 3.4.2 it just works. > > Why do you think the Python version has anything to do with it? Because the OP states that he is using Python 3.1 (look at the subject line) and it doesn't work in 3.1. For what it is worth, I cannot confirm that alleged behaviour: steve at orac:~$ python3.1 -c "import sys; print(sys.stdout.fileno())" 1 I suspect that the OP may be using an IDE which does something funny to sys.stdout etc., or perhaps he has accidentally shadowed them. The OP failed to copy and paste the actual traceback, so who knows what is actually happening? -- Steven From marko at pacujo.net Sat Nov 15 06:54:21 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Nov 2014 13:54:21 +0200 Subject: How about some syntactic sugar for " __name__ == '__main__' "? References: <71b9a111-283f-4006-bc9d-e35782d9888c@googlegroups.com> <54673458$0$12999$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87ppcok7bm.fsf@elektro.pacujo.net> Steven D'Aprano : > if __name__ == '__main__' or condition(): > print "still executing" > main() > > print "done loading" > > (I haven't ever done *all* of these things in a *single* file, but I > have done all these things at one time or another.) > > There's no way that any automatic system can match that for > flexibility or simplicity. Our test system has this boilerplate at the end of each test case: if __name__ == '__main__': run(test) Nobody claims it's beautiful but nobody has been overly bothered by it, either. Marko From steve+comp.lang.python at pearwood.info Sat Nov 15 07:28:47 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 15 Nov 2014 23:28:47 +1100 Subject: A Freudian slip of *EPIC PROPORTIONS*! References: Message-ID: <54674700$0$13003$c3e8da3$5496439d@news.astraweb.com> Terry Reedy wrote: > On 11/13/2014 6:11 PM, Rick Johnson wrote: > >> # The parse functions have no idea what to do with >> # Unicode, so replace all Unicode characters with "x". >> # This is "safe" so long as the only characters germane >> # to parsing the structure of Python are 7-bit ASCII. >> # It's *necessary* because Unicode strings don't have a >> # .translate() method that supports deletechars. >> uniphooey = str > > It is customary to attribute quotes to their source. This is from 2.x > Lib/idlelib/PyParse.py. The file was committed (and probably written) > by David Scherer 2000-08-15. Edits for unicode, including the above, > were committed (and perhaps written) by Kurt B. Kaiser on 2001-07-13. Correct. The line in question was written by Kurt. We can find this out by using the hg annotate command. Change into the Lib/idlelib directory of the source repository, then use hg annotate command as follows: [steve at ando idlelib]$ hg annotate PyParse.py | grep phoo 42050: uniphooey = s 18555: for raw in map(ord, uniphooey): The numbers shown on the left are the revision IDs, so look at the older of the two: [steve at ando idlelib]$ hg annotate -r 18555 PyParse.py | grep phoo 18555: uniphooey = str 18555: for raw in map(ord, uniphooey): We can confirm that prior to that revision, the uniphooey lines didn't exist: [steve at ando idlelib]$ hg annotate -r 18554 PyParse.py | grep phoo And then find out who is responsible: [steve at ando idlelib]$ hg annotate -uvd -r 18555 PyParse.py | grep phoo Kurt B. Kaiser Fri Jul 13 20:33:46 2001 +0000: uniphooey = str Kurt B. Kaiser Fri Jul 13 20:33:46 2001 +0000: for raw in map(ord, uniphooey): > I doubt GvR ever saw this code. I expect KBK has changed opinions with > respect to unicode in 13 years, as has most everyone else. We don't know Kurt's intention with regard to the name, the "phooey" could refer to: - the parse functions failing to understand Unicode; - it being a nasty hack that assumes that Python will never use Unicode characters for keywords or operators; - it being necessary because u''.translate fails to support a deletechars parameter. It's unlikely to refer to the Unicode character set itself. -- Steven From breamoreboy at yahoo.co.uk Sat Nov 15 08:12:12 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Nov 2014 13:12:12 +0000 Subject: Decorators In-Reply-To: References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <8761ehmnnt.fsf_-_@elektro.pacujo.net> <26dba8fd-e403-4129-ad57-11376eb807bd@googlegroups.com> Message-ID: On 15/11/2014 07:42, Richard Riehle wrote: > Mayank, > > Thanks. I have only been using Python for about four years, so there > are features I have only recently discovered. Decorators are one of > them. So far, I encounter other Python users who are also unfamiliar > with them. When I discovered them, I instantly saw how they could be > valuable. > > Richard Riehle, PhD > Core Faculty, ITU > Would you please be kind enough to get a PhD in interspersing your replies or bottom posting rather than top posting, thank you. -- 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 Sat Nov 15 08:24:38 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Nov 2014 15:24:38 +0200 Subject: Decorators References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <8761ehmnnt.fsf_-_@elektro.pacujo.net> <26dba8fd-e403-4129-ad57-11376eb807bd@googlegroups.com> Message-ID: <87k32wk355.fsf@elektro.pacujo.net> Mark Lawrence : > On 15/11/2014 07:42, Richard Riehle wrote: >> When I discovered them, I instantly saw how they could be valuable. > > Would you please be kind enough to get a PhD in interspersing your > replies or bottom posting rather than top posting, thank you. I'd take top-posting if I were enlightened about how decorators could be valuable. Sadly, I didn't see it instantly, or even afterwards. Marko From ngangsia at gmail.com Sat Nov 15 09:10:02 2014 From: ngangsia at gmail.com (ngangsia akumbo) Date: Sat, 15 Nov 2014 06:10:02 -0800 (PST) Subject: webhooks Message-ID: <4ca2dd5f-e158-4f86-8e5f-fde4557c5a62@googlegroups.com> What are the basics of implement web hooks with python? I need some detail tutorial in this topic. Thanks From steve+comp.lang.python at pearwood.info Sat Nov 15 10:15:46 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 16 Nov 2014 02:15:46 +1100 Subject: Question about installing python and modules on Red Hat Linux 6 References: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> Message-ID: <54676e23$0$13010$c3e8da3$5496439d@news.astraweb.com> pythonista wrote: > I am developing a python application as a contractor. > > I would like to know if someone can provide me with some insight into the > problems that then infrastructure team has been having. > > The scope of the project was to install python 2.7.8 and 4 modules/site > packages on a fresh linux build. A "fresh linux build" of Red Hat Linux 6? RHL 6 was discontinued in 2000. That's *at least* 14 years old. Why on earth are you using something so old instead of a recent version of RHEL, Centos or Fedora? The supported version of Python for RHL 6 was Python 1.5. (That's *one* point five.) I'm not surprised that they had trouble installing Python 2.7 on something that old, especially if you needed support for optional but important features like tkinter, ssh, readline, curses, etc. I haven't tried it, so it is possible that installing 2.7 from source on such an old Linux system will actually be trivially easy and need only half an hour's work. But I wouldn't bet on it. I would expect all sorts of difficulties, due to the age difference between RHL 6 and the Python 2.7. As for the four modules, that depends. If they are extension modules written in C, who knows how hard it will be to get them working under RHL 6. And even if they are pure Python modules, depending on how old they are, they may be difficult to get working with something as new as Python 2.7. Without more details of what the modules are and what errors the infrastructure team experienced, there is no way to tell whether four weeks to get this working was a heroic effort or a sign of utter incompetence. -- Steven From invalid at invalid.invalid Sat Nov 15 10:32:01 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Sat, 15 Nov 2014 15:32:01 +0000 (UTC) Subject: Decorators References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <8761ehmnnt.fsf_-_@elektro.pacujo.net> <26dba8fd-e403-4129-ad57-11376eb807bd@googlegroups.com> <87zjbtj6di.fsf@elektro.pacujo.net> Message-ID: On 2014-11-15, Marko Rauhamaa wrote: > Tim Chase : > >> And decorators are used pretty regularly in just about every code-base >> that I've touched (I've been programming in Python since early 2004, >> so I've maintained pre-2.4 code without decorators and then brought it >> forward to 2.4 where decorators were usable). > > Funny. My experience with Python is about as old, and I have yet to > encounter them in code. I have seen (maybe even used) @staticmethod once > or twice over a decade and then as a magic keyword rather than a > "decorator pattern." I've been using Python since 1999 and version 1.5.2 and have yet to use decorators. I do occasionally find myself in a spot where I'm pretty sure that there's a more elegent way to do something using a decorator, and promise myself that I'll read up on decorators one of these days when I have some spare time... -- Grant From steve+comp.lang.python at pearwood.info Sat Nov 15 10:39:40 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 16 Nov 2014 02:39:40 +1100 Subject: Decorators (was: Re: I love assert) References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <8761ehmnnt.fsf_-_@elektro.pacujo.net> <26dba8fd-e403-4129-ad57-11376eb807bd@googlegroups.com> Message-ID: <546773bd$0$13011$c3e8da3$5496439d@news.astraweb.com> Richard Riehle wrote: > Decorators are new in Python, so there are not a lot of people using them. The principle of decorators themselves is as old as Python itself. You could implement them as far back as Python 1.5, if not older: [steve at ando ~]$ python1.5 Python 1.5.2 (#1, Aug 27 2012, 09:09:18) [GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> def decorator(func): ... def inner(arg, func=func): ... return func(arg*2) ... return inner ... >>> def f(x): ... return x + 1 ... >>> f = decorator(f) >>> f(1) 3 >>> f(5) 11 The first built-in decorators (classmethod, staticmethod and property) were added in Python 2.2. Decorator syntax using @ was added in 2.4. https://docs.python.org/2/whatsnew/2.4.html#pep-318-decorators-for-functions-and-methods So decorators have been available for a very long time. > From my experience with other languages, especially Ada and Eiffel, I > enjoy the benefit of assertions (as pre-conditions and post-conditions and > invariants) at the specification level (not embedded in the code), so > decorators are closer to my other experience. They bring me closer to > the Design by Contract model of Ada and Eiffel. That is why I was so > pleased to see them added to Python. Way back in Python 1.5, Guido van Rossum wrote an essay describing a way to get Eiffel-like checks for pre-conditions and post-conditions: https://www.python.org/doc/essays/metaclasses/ (Alas, the link to Eiffel.py is currently broken. But you can read the rest of the essay.) > It is true, however, that they are not immediately intutive in Python, but > once understood, they are handy IMHO for improving code reliability. > Perhaps I was spoiled by having this capability in some other languages. -- Steven From invalid at invalid.invalid Sat Nov 15 10:45:01 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Sat, 15 Nov 2014 15:45:01 +0000 (UTC) Subject: Question about installing python and modules on Red Hat Linux 6 References: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> <54676e23$0$13010$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2014-11-15, Steven D'Aprano wrote: > pythonista wrote: > >> I am developing a python application as a contractor. >> >> I would like to know if someone can provide me with some insight into the >> problems that then infrastructure team has been having. >> >> The scope of the project was to install python 2.7.8 and 4 modules/site >> packages on a fresh linux build. > > A "fresh linux build" of Red Hat Linux 6? RHL 6 was discontinued in 2000. > That's *at least* 14 years old. Why on earth are you using something so old > instead of a recent version of RHEL, Centos or Fedora? I'm sure the OP meant RHEL 6, and not RH 6 [yes, I realize you know that two and are just making a point about how it pays to include accurate info when asking for help.] The OP probably doesn't even _know_ that there was prior product line called RedHat Linux with a version 6. [Kids these days!] IIRC, I started with one of the "holiday" RedHat Linux releases before they were numbered. I think it was "Mothers Day" or "Holloween". The first numbered release I remember was RedHat Linux 3.something. RHL was pretty good up through the 6.x series, but 7.00 was utterly and famously shoddy [at that point I switched to Mandrake]. RH 7.00 was so notoriously bad, I'm surprised that they didn't skip "7" entirely in the RHEL product line to avoid the bad memories... -- Grant From torriem at gmail.com Sat Nov 15 12:02:09 2014 From: torriem at gmail.com (Michael Torrie) Date: Sat, 15 Nov 2014 10:02:09 -0700 Subject: Question about installing python and modules on Red Hat Linux 6 In-Reply-To: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> References: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> Message-ID: <54678711.4070900@gmail.com> On 11/14/2014 08:01 PM, pythonista wrote: > Can anyone provide me with insight as to the scope what the problem could have been? Well the fact is that RHEL 6 uses Python 2.6 as a core system package. Many system utilities depend on it, so it cannot be replaced with a newer version. You must install the newer version alongside the old version. This can be easily accomplished with Redhat's Software Collections system. I have Python 2.7 and 3.4 installed on my RHEL6 box with this machanism. From torriem at gmail.com Sat Nov 15 12:05:01 2014 From: torriem at gmail.com (Michael Torrie) Date: Sat, 15 Nov 2014 10:05:01 -0700 Subject: Question about installing python and modules on Red Hat Linux 6 In-Reply-To: <54676e23$0$13010$c3e8da3$5496439d@news.astraweb.com> References: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> <54676e23$0$13010$c3e8da3$5496439d@news.astraweb.com> Message-ID: <546787BD.8050908@gmail.com> On 11/15/2014 08:15 AM, Steven D'Aprano wrote: > A "fresh linux build" of Red Hat Linux 6? RHL 6 was discontinued in 2000. Yes I know you're making a point about not assuming anything, but the odds are very good that the OP meant RHEL6. And meaning RHEL6, there are some good reasons why the infrastructure team struggled, since Python 2.6 is a core system dependency and cannot easily be overridden without breaking the entire system. The answer is either use Redhat Software Collections[1], or compile from scratch to /opt. [1] https://www.softwarecollections.org/en/scls/rhscl/python27/ From nomail at invalid.com Sat Nov 15 12:07:30 2014 From: nomail at invalid.com (ast) Date: Sat, 15 Nov 2014 18:07:30 +0100 Subject: Strange result with timeit execution time measurment Message-ID: <54678857$0$2325$426a74cc@news.free.fr> Hi I needed a function f(x) which looks like sinus(2pi.x) but faster. I wrote this one: -------------------------- from math import floor def sinusLite(x): x = x - floor(x) return -16*(x-0.25)**2 + 1 if x < 0.5 else 16*(x-0.75)**2 - 1 -------------------------- then i used module timeit to compare its execution time with math.sin() I put the sinusLite() function in a module named test. then: >>> import timeit >>> t1 = timeit.Timer("y=test.sinusLite(0.7)", "import test") >>> t2 = timeit.Timer("y=math.sin(4.39)", "import math") ## 4.39 = 2*pi*0.7 >>> t1.repeat(3, 1000000) [1.9994622221539373, 1.9020670224846867, 1.9191573230675942] >>> t2.repeat(3, 1000000) [0.2913627989031511, 0.2755561810230347, 0.2755186762562971] so the genuine sinus is much faster than my so simple sinLite() ! Amazing isnt it ? Do you have an explanation ? Thx From torriem at gmail.com Sat Nov 15 12:13:57 2014 From: torriem at gmail.com (Michael Torrie) Date: Sat, 15 Nov 2014 10:13:57 -0700 Subject: Question about installing python and modules on Red Hat Linux 6 In-Reply-To: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> References: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> Message-ID: <546789D5.5070502@gmail.com> On 11/14/2014 08:01 PM, pythonista wrote: > The scope of the project was to install python 2.7.8 and 4 modules/site packages on a fresh linux build. I neglected to put the URL for software collections in my reply to you. Here it is. https://www.softwarecollections.org/en/scls/rhscl/python27/ Note that the infrastructure team will have to learn how to interface with it, since, as a software collection, it's not going to be in the path by default (because it would conflict). Any startup scripts or other invocations of your app will have to be modified to acquire the python 2.7 special environment, by sourcing the python 2.7 collection's enable file. I'm not entirely sure how to integrate it with Apache, but I know it can be done. If it's a package that won't conflict, such as Python 2.4, you can permanently integrate it into the environment this way: http://developerblog.redhat.com/2014/03/19/permanently-enable-a-software-collection/ -- but I can't recommend this for python 2.7 as it would break a lot of RHEL 6's commands. From torriem at gmail.com Sat Nov 15 12:23:04 2014 From: torriem at gmail.com (Michael Torrie) Date: Sat, 15 Nov 2014 10:23:04 -0700 Subject: Question about installing python and modules on Red Hat Linux 6 In-Reply-To: <546789D5.5070502@gmail.com> References: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> <546789D5.5070502@gmail.com> Message-ID: <54678BF8.9030808@gmail.com> On 11/15/2014 10:13 AM, Michael Torrie wrote: > If it's a package that won't conflict, such as Python 2.4, you can Ahem, that should have been 3.4 From __peter__ at web.de Sat Nov 15 12:59:22 2014 From: __peter__ at web.de (Peter Otten) Date: Sat, 15 Nov 2014 18:59:22 +0100 Subject: Strange result with timeit execution time measurment References: <54678857$0$2325$426a74cc@news.free.fr> Message-ID: ast wrote: > Hi > > I needed a function f(x) which looks like sinus(2pi.x) but faster. > I wrote this one: > > -------------------------- > from math import floor > > def sinusLite(x): > x = x - floor(x) > return -16*(x-0.25)**2 + 1 if x < 0.5 else 16*(x-0.75)**2 - 1 > -------------------------- > > then i used module timeit to compare its execution time with math.sin() > I put the sinusLite() function in a module named test. > > then: > >>>> import timeit >>>> t1 = timeit.Timer("y=test.sinusLite(0.7)", "import test") >>>> t2 = timeit.Timer("y=math.sin(4.39)", "import math") ## 4.39 = >>>> 2*pi*0.7 > >>>> t1.repeat(3, 1000000) > [1.9994622221539373, 1.9020670224846867, 1.9191573230675942] > >>>> t2.repeat(3, 1000000) > [0.2913627989031511, 0.2755561810230347, 0.2755186762562971] > > so the genuine sinus is much faster than my so simple sinLite() ! > Amazing isnt it ? Do you have an explanation ? You are applying your optimisation in an implementation where the function call overhead of a Python-implemented function is greater than the time to invoke the C-coded function, calculate the sin, and create the python float. $ python -m timeit -s 'from math import sin' 'sin(.7)' 1000000 loops, best of 3: 0.188 usec per loop $ python -m timeit -s 'from test import sinusLite as sin' 'sin(.7)' 1000000 loops, best of 3: 0.972 usec per loop $ python -m timeit -s 'sin = lambda x: None' 'sin(.7)' 1000000 loops, best of 3: 0.242 usec per loop For CPython to write fast lowlevel code you have to switch to C (or Cython). In PyPy the results get interesting: $ pypy -m timeit -s 'from test import sinusLite as sin' 'sin(.7)' 100000000 loops, best of 3: 0.00459 usec per loop $ pypy -m timeit -s 'from math import sin' 'sin(.7)' 10000000 loops, best of 3: 0.0476 usec per loop So yes, your approximation may speed up code in some parts of the Python universe (I don't know if pypy takes advantage of the constant argument). From davea at davea.name Sat Nov 15 13:08:28 2014 From: davea at davea.name (Dave Angel) Date: Sat, 15 Nov 2014 13:08:28 -0500 (EST) Subject: Strange result with timeit execution time measurment References: <54678857$0$2325$426a74cc@news.free.fr> Message-ID: "ast" Wrote in message: > Hi > > I needed a function f(x) which looks like sinus(2pi.x) but faster. > I wrote this one: > > -------------------------- > from math import floor > > def sinusLite(x): > x = x - floor(x) > return -16*(x-0.25)**2 + 1 if x < 0.5 else 16*(x-0.75)**2 - 1 > -------------------------- > > then i used module timeit to compare its execution time with math.sin() > I put the sinusLite() function in a module named test. > > then: > >>>> import timeit >>>> t1 = timeit.Timer("y=test.sinusLite(0.7)", "import test") >>>> t2 = timeit.Timer("y=math.sin(4.39)", "import math") ## 4.39 = 2*pi*0.7 > >>>> t1.repeat(3, 1000000) > [1.9994622221539373, 1.9020670224846867, 1.9191573230675942] > >>>> t2.repeat(3, 1000000) > [0.2913627989031511, 0.2755561810230347, 0.2755186762562971] > > so the genuine sinus is much faster than my so simple sinLite() ! > Amazing isnt it ? Do you have an explanation ? > > Thx > Sure, the library function probably used the trig logic in the processor. Perhaps if you timed things on a processor without a "math coprocessor" things could be different. But even there, you'd probably be comparing C to python. Library code is optimized where it's deemed helpful. -- DaveA From pkpearson at nowhere.invalid Sat Nov 15 13:12:52 2014 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 15 Nov 2014 18:12:52 GMT Subject: Strange result with timeit execution time measurment References: <54678857$0$2325$426a74cc@news.free.fr> Message-ID: On Sat, 15 Nov 2014 18:07:30 +0100, ast wrote: > > I needed a function f(x) which looks like sinus(2pi.x) but faster. > I wrote this one: > > -------------------------- > from math import floor > > def sinusLite(x): > x = x - floor(x) > return -16*(x-0.25)**2 + 1 if x < 0.5 else 16*(x-0.75)**2 - 1 > -------------------------- > > then i used module timeit to compare its execution time with math.sin() > I put the sinusLite() function in a module named test. > > then: > >>>> import timeit >>>> t1 = timeit.Timer("y=test.sinusLite(0.7)", "import test") >>>> t2 = timeit.Timer("y=math.sin(4.39)", "import math") ## 4.39 = 2*pi*0.7 > >>>> t1.repeat(3, 1000000) > [1.9994622221539373, 1.9020670224846867, 1.9191573230675942] > >>>> t2.repeat(3, 1000000) > [0.2913627989031511, 0.2755561810230347, 0.2755186762562971] > > so the genuine sinus is much faster than my so simple sinLite() ! > Amazing isnt it ? Do you have an explanation ? I suppose math.sin is implemented in C. Compiled languages (like C) are much faster than interpreted languages like Python. -- To email me, substitute nowhere->runbox, invalid->com. From ian.g.kelly at gmail.com Sat Nov 15 13:18:01 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 15 Nov 2014 11:18:01 -0700 Subject: Strange result with timeit execution time measurment In-Reply-To: <54678857$0$2325$426a74cc@news.free.fr> References: <54678857$0$2325$426a74cc@news.free.fr> Message-ID: On Sat, Nov 15, 2014 at 10:07 AM, ast wrote: > Hi > > I needed a function f(x) which looks like sinus(2pi.x) but faster. > I wrote this one: > > -------------------------- > from math import floor > > def sinusLite(x): > x = x - floor(x) > return -16*(x-0.25)**2 + 1 if x < 0.5 else 16*(x-0.75)**2 - 1 > -------------------------- > > then i used module timeit to compare its execution time with math.sin() > I put the sinusLite() function in a module named test. > > then: > >>>> import timeit >>>> t1 = timeit.Timer("y=test.sinusLite(0.7)", "import test") >>>> t2 = timeit.Timer("y=math.sin(4.39)", "import math") ## 4.39 = >>>> 2*pi*0.7 > > >>>> t1.repeat(3, 1000000) > > [1.9994622221539373, 1.9020670224846867, 1.9191573230675942] > >>>> t2.repeat(3, 1000000) > > [0.2913627989031511, 0.2755561810230347, 0.2755186762562971] > > so the genuine sinus is much faster than my so simple sinLite() ! > Amazing isnt it ? Do you have an explanation ? The built-in sin is written in C, and the C implementation on most modern systems boils down to a single assembly instruction implemented in microcode. That's generally going to be faster than a whole series of operations written in Python. Even just doing the 2*pi multiplication in Python will add a lot to the timing: C:\>python -m timeit -s "import math" "math.sin(2*math.pi*0.7)" 1000000 loops, best of 3: 0.587 usec per loop C:\>python -m timeit -s "import math" "math.sin(4.39)" 1000000 loops, best of 3: 0.222 usec per loop From tjreedy at udel.edu Sat Nov 15 15:12:22 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 15 Nov 2014 15:12:22 -0500 Subject: A Freudian slip of *EPIC PROPORTIONS*! In-Reply-To: <54674700$0$13003$c3e8da3$5496439d@news.astraweb.com> References: <54674700$0$13003$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 11/15/2014 7:28 AM, Steven D'Aprano wrote: > Terry Reedy wrote: > >> On 11/13/2014 6:11 PM, Rick Johnson wrote: >> >>> # The parse functions have no idea what to do with >>> # Unicode, so replace all Unicode characters with "x". >>> # This is "safe" so long as the only characters germane >>> # to parsing the structure of Python are 7-bit ASCII. >>> # It's *necessary* because Unicode strings don't have a >>> # .translate() method that supports deletechars. >>> uniphooey = str >> >> It is customary to attribute quotes to their source. This is from 2.x >> Lib/idlelib/PyParse.py. The file was committed (and probably written) >> by David Scherer 2000-08-15. Edits for unicode, including the above, >> were committed (and perhaps written) by Kurt B. Kaiser on 2001-07-13. > > Correct. > > The line in question was written by Kurt. We can find this out by using > the hg annotate command. Change into the Lib/idlelib directory of the > source repository, then use hg annotate command as follows: > > > [steve at ando idlelib]$ hg annotate PyParse.py | grep phoo > 42050: uniphooey = s > 18555: for raw in map(ord, uniphooey): > > The numbers shown on the left are the revision IDs, so look at the > older of the two: > > [steve at ando idlelib]$ hg annotate -r 18555 PyParse.py | grep phoo > 18555: uniphooey = str > 18555: for raw in map(ord, uniphooey): > > We can confirm that prior to that revision, the uniphooey lines > didn't exist: > > [steve at ando idlelib]$ hg annotate -r 18554 PyParse.py | grep phoo > > > > And then find out who is responsible: > > [steve at ando idlelib]$ hg annotate -uvd -r 18555 PyParse.py | grep phoo > Kurt B. Kaiser Fri Jul 13 20:33:46 2001 +0000: uniphooey = str > Kurt B. Kaiser Fri Jul 13 20:33:46 2001 +0000: for raw in map(ord, uniphooey): On windows, with TortoiseHg installed, I right-clicked PyParse in Explorer and selected TortoiseHg on the context menu and Annotate on the submenu. This pops up a Window with two linked panels -- a list of revisions and an annotated file listing with lines added or changed by the current revision marked a different background color. I found the comment block easily enough, looked at the annotation, and looked back at the revision list. Clicking on a revision changes the file listing. On can easily march through the history of the file. >> I doubt GvR ever saw this code. I expect KBK has changed opinions with >> respect to unicode in 13 years, as has most everyone else. Including mine. > We don't know Kurt's intention with regard to the name, the "phooey" > could refer to: > > - the parse functions failing to understand Unicode; > - it being a nasty hack that assumes that Python will never use > Unicode characters for keywords or operators; > - it being necessary because u''.translate fails to support > a deletechars parameter. I expect I would have been annoyed when a new-fangled feature, elsewhere in Python, broke one of the files I was working on. Now, of course, I would know to not use a variable name that could be misinterpreted by someone years in the future. > It's unlikely to refer to the Unicode character set itself. -- Terry Jan Reedy From tjreedy at udel.edu Sat Nov 15 15:28:41 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 15 Nov 2014 15:28:41 -0500 Subject: Decorators In-Reply-To: <87k32wk355.fsf@elektro.pacujo.net> References: <96c138e4-ab95-4e5f-a0c8-e696b5a926bb@googlegroups.com> <8761ehmnnt.fsf_-_@elektro.pacujo.net> <26dba8fd-e403-4129-ad57-11376eb807bd@googlegroups.com> <87k32wk355.fsf@elektro.pacujo.net> Message-ID: On 11/15/2014 8:24 AM, Marko Rauhamaa wrote: > I'd take top-posting if I were enlightened about how decorators could be > valuable. Here is part of the original rationale. @deco(arg) def f: suite is (for this discussion) equivalent to def f: suite f = deco(arg)(f) The latter requires writing 'f' 3 times instead of 1. Now suppose to meet external requirements, such as interfacing to Objective C, you had to wrap dozens of functions, each with long names, up to 30 chars, with multiple components. You would then become enlightened. Once the idea of making function wrapping easier emerged, many other applications emerged. Various stdlib modules define decorators. If you do not need to wrap functions, easy wrapping might seem useless to you. That's fine. You know they are there should you ever have need. -- Terry Jan Reedy From cts.private.yahoo at gmail.com Sat Nov 15 17:52:33 2014 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Sat, 15 Nov 2014 22:52:33 +0000 (UTC) Subject: caught in the import web again Message-ID: Now, I'm getting these errors: ImportError: cannot import name ... and AttributeError: 'module' object has no attribute ... (what is 'module'?) Is there a way to resolve this without having to restructure my code every couple of days? I thought using imports of the form: from module import symbol was the "right way" to avoid these hassles... TIA cts www.creative-telcom-solutions.de From ben+python at benfinney.id.au Sat Nov 15 18:43:02 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 16 Nov 2014 10:43:02 +1100 Subject: caught in the import web again References: Message-ID: <85tx202fp5.fsf@benfinney.id.au> "Charles T. Smith" writes: > Now, I'm getting these errors: Please reduce the problem to a minimal, complete example demonstrating the behaviour so that you can show us exactly what's happening. > AttributeError: 'module' object has no attribute ... > > (what is 'module'?) The type of the object which doesn't have the attribute. It's saying you're tring to access an attribute on a particular object, and that object (which is of type ?module?, hence it is a ?'module' object?) doesn't have that attribute. > Is there a way to resolve this without having to restructure my code > every couple of days? Not knowing what the actual problem is, it's difficult to say. Please come up with a (contrived, if you like) minimal clear example of what's happening ? i.e. make it from scratch, without irrelevant parts from the rest of your program, but ensure it still does what you're confused by ? and present it here. -- \ ?It's a terrible paradox that most charities are driven by | `\ religious belief.? if you think altruism without Jesus is not | _o__) altruism, then you're a dick.? ?Tim Minchin, 2010-11-28 | Ben Finney From steve+comp.lang.python at pearwood.info Sat Nov 15 20:08:52 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 16 Nov 2014 12:08:52 +1100 Subject: Question about installing python and modules on Red Hat Linux 6 References: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> <54676e23$0$13010$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5467f926$0$13014$c3e8da3$5496439d@news.astraweb.com> Grant Edwards wrote: > On 2014-11-15, Steven D'Aprano > wrote: >> pythonista wrote: >> >>> I am developing a python application as a contractor. >>> >>> I would like to know if someone can provide me with some insight into >>> the problems that then infrastructure team has been having. >>> >>> The scope of the project was to install python 2.7.8 and 4 modules/site >>> packages on a fresh linux build. >> >> A "fresh linux build" of Red Hat Linux 6? RHL 6 was discontinued in 2000. >> That's *at least* 14 years old. Why on earth are you using something so >> old instead of a recent version of RHEL, Centos or Fedora? > > I'm sure the OP meant RHEL 6, and not RH 6 [yes, I realize you know > that two and are just making a point about how it pays to include > accurate info when asking for help.] Actually, no, the thought didn't even cross my mind. I just assumed that if somebody is going to cast aspersions on the professionalism of others, they'd get their facts right. If they said RHL 6, they meant RHL 6 and not Centos 5 or Fedora 20 or Debian Squeeze. But I suppose that you're probably right. In hindsight, given that the OP is a Windows guy and not a Linux user, writing Red Hat Linux for Red Hat Enterprise Linux is an easy mistake to make. Assuming it was RHEL 6, then installing Python 2.7 from source as a separate application from the system Python should be trivially easy, half an hour's work. Download the source, untar, run ./configure, make, make altinstall and you should be done. There may be a few bumps in the road to get optional components supported, in which case a skilled Linux admin (which I am not) might need perhaps a couple of hours. Depending on just how bad the bumps were, an unskilled admin like me might take a day or so, not three weeks, before giving up. The most obvious trap is to run `make install` instead of `make altinstall`, in which case congratulations, you've just broken the RHEL install, and why didn't you read the README first? You can recover from it, probably, by fixing a few sym links, or by re-installing the system Python using the package manager. Worst case you just reinstall the whole OS. Two or three days, tops, not four weeks. If some foolish person insisted on upgrading the system python to 2.7 instead of installing a parallel installation, then the sky is the limit. I cannot imagine how much effort that would take, or how fragile it would be. Weeks? Probably. And then the first time the admin runs the package manager to install updates, things could start breaking. One thing which the OP hasn't told us, how much of the four weeks was effort, as opposed to elapsed time. For all we know, it took them four weeks to install this because for three weeks, four days and seven hours they were doing something else. In any case, if the OP has been billed for this time, I would insist on justification for why it took so long before paying. -- Steven From denismfmcmahon at gmail.com Sat Nov 15 20:11:05 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Sun, 16 Nov 2014 01:11:05 +0000 (UTC) Subject: caught in the import web again References: Message-ID: On Sat, 15 Nov 2014 22:52:33 +0000, Charles T. Smith wrote: > Now, I'm getting these errors: > > ImportError: cannot import name ... > > and > > AttributeError: 'module' object has no attribute ... It would be useful to know what you're actually trying to import and what the complete error messages are. For example, are these imports of code that you've written yourself, or part of the standard library modules, or third party modules. -- Denis McMahon, denismfmcmahon at gmail.com From rosuav at gmail.com Sat Nov 15 20:32:01 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Nov 2014 12:32:01 +1100 Subject: Question about installing python and modules on Red Hat Linux 6 In-Reply-To: <5467f926$0$13014$c3e8da3$5496439d@news.astraweb.com> References: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> <54676e23$0$13010$c3e8da3$5496439d@news.astraweb.com> <5467f926$0$13014$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Nov 16, 2014 at 12:08 PM, Steven D'Aprano wrote: > Assuming it was RHEL 6, then installing Python 2.7 from source as a separate > application from the system Python should be trivially easy, half an hour's > work. Download the source, untar, run ./configure, make, make altinstall > and you should be done. There may be a few bumps in the road to get > optional components supported, in which case a skilled Linux admin (which I > am not) might need perhaps a couple of hours. Depending on just how bad the > bumps were, an unskilled admin like me might take a day or so, not three > weeks, before giving up. For a competent Linux system admin, this should be second nature. Installing from source should be as normal an operation as writing a shell script or scheduling a job with cron. But if the people concerned aren't so much "POSIX system admins" as "RHEL admins", then it's possible they depend entirely on the upstream repositories, and aren't familiar with the dance of "can't find -lfoo so go install libfoo-dev" (with occasionally a more exotic step, when the package name isn't obvious, but Google helps there); in that case, it could well take a long time, but that's like a Python programmer who's having trouble debugging an asyncio program because s/he isn't used to walking through the control flow of "yield from". I know I'm not competent at that, and it doesn't stop me from being a programmer - but I'm not going to come to python-list saying "This language sucks, I can't find this bug", because the problem is a limitation in my own skills. Other RHEL people: Is there a yum equivalent to "apt-get build-dep", which goes out and fetches all the compilers, libraries, build tools, etc, needed to build a package from source? If so - and I wouldn't be at all surprised if there is - that would be my recommended first step: grab the build deps for Python 2.6 and use those to build 2.7. Chances are that's all you need - that, plus the one little trick of "make altinstall" rather than "make install". ChrisA From torriem at gmail.com Sat Nov 15 20:57:47 2014 From: torriem at gmail.com (Michael Torrie) Date: Sat, 15 Nov 2014 18:57:47 -0700 Subject: Question about installing python and modules on Red Hat Linux 6 In-Reply-To: <5467f926$0$13014$c3e8da3$5496439d@news.astraweb.com> References: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> <54676e23$0$13010$c3e8da3$5496439d@news.astraweb.com> <5467f926$0$13014$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5468049B.6050806@gmail.com> On 11/15/2014 06:08 PM, Steven D'Aprano wrote: > Assuming it was RHEL 6, then installing Python 2.7 from source as a separate > application from the system Python should be trivially easy, half an hour's > work. Download the source, untar, run ./configure, make, make altinstall > and you should be done. There may be a few bumps in the road to get > optional components supported, in which case a skilled Linux admin (which I > am not) might need perhaps a couple of hours. Depending on just how bad the > bumps were, an unskilled admin like me might take a day or so, not three > weeks, before giving up. In my last system administration job, we forbade installing from source, at least in the manner you are describing. It's a maintenance nightmare. Especially when it comes time to upgrade the system and get things up and running on a new OS version. To make the system maintainable and re-creatable (it's easy to dump a list of installed packages to install on anther machine), it had to be done using the package manager. Preferably with trusted packages (trusted repositories) that were actively maintained. At that time Red Hat software collections didn't exist, so I did have to spend some considerable time building and testing RPM packages. Yes it's a headache for the developer in the short term, but in the long term it always turned out better than hacking things together from source. The OP hasn't said that this is the case for his client of course. From rosuav at gmail.com Sat Nov 15 21:23:12 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Nov 2014 13:23:12 +1100 Subject: Question about installing python and modules on Red Hat Linux 6 In-Reply-To: <5468049B.6050806@gmail.com> References: <2e88d2e2-bde6-4d8f-8f2f-06d6a9676ee4@googlegroups.com> <54676e23$0$13010$c3e8da3$5496439d@news.astraweb.com> <5467f926$0$13014$c3e8da3$5496439d@news.astraweb.com> <5468049B.6050806@gmail.com> Message-ID: On Sun, Nov 16, 2014 at 12:57 PM, Michael Torrie wrote: > In my last system administration job, we forbade installing from source, > at least in the manner you are describing. It's a maintenance > nightmare. Especially when it comes time to upgrade the system and get > things up and running on a new OS version. To make the system > maintainable and re-creatable (it's easy to dump a list of installed > packages to install on anther machine), it had to be done using the > package manager. Preferably with trusted packages (trusted > repositories) that were actively maintained. At that time Red Hat > software collections didn't exist, so I did have to spend some > considerable time building and testing RPM packages. Yes it's a > headache for the developer in the short term, but in the long term it > always turned out better than hacking things together from source. > Fundamentally, this comes down to a single question: Who do you most trust? 1) Upstream repositories? Then install everything from the provided package manager. All will be easy; as long as nothing you use got removed in the version upgrade, you should be able to just grab all the same packages and expect everything to run. This is what I'd recommend for most end users. 2) Yourself? Then install stuff from source. For a competent sysadmin on his/her own computer, this is what I'd recommend. Use the repos when you can, but install anything from source if you feel like it. I do this for a number of packages where Debian provides an oldish version, or where I want to tweak something, or anything like that. When you upgrade to a new OS version, it's time to reconsider all those decisions; maybe there's a newer version in repo than the one you built from source a while ago. 3) A local repository? Then do what you describe above - build and test the RPMs and don't install anything from source. If you need something that isn't in upstream, you compile it, package it, and deploy it locally. Great if you have hundreds or thousands of similar machines to manage, eliminates the maintenance nightmare, but is unnecessary work if you have only a handful of machines and they're all unique. I'm responsible for maybe a dozen actively-used Linux boxes, so I'm a pretty small-time admin. Plus, they run a variety of different hardware, OS releases (they're mostly Debian-family distros, but I have some Ubuntu, some Debian, one AntiX, and various others around the place - and a variety of versions as well), and application software (different needs, different stuff installed). Some are headless servers that exist solely for the network. Others are people's clients that they actively use every day. They don't all need Wine, VirtualBox, DOSBox, or other compatibility/emulation layers; but some need versions newer than those provided in the upsstream repos. One box needs audio drivers compiled from source, else there's no sound. Until a few months ago, several - but not all - needed a few local patches to one program. (Then the patches got accepted upstream, but that version isn't in the Debian repos yet.) And of course, they all need their various configs - a web server is not created by "sudo apt-get install apache2" so much as by editing /etc/apache2/*. Sure, I *could* run everything through deb/rpm packages, but I'd be constantly tweaking and packaging and managing upgrades, and it's much better use of my time to just deploy from source. With so few computers to manage, the Big-Oh benefits of your recommendation just don't kick in. But I doubt these considerations apply to the OP. Of course, we can't know until our crystal balls get some more to work on. ChrisA From ikorot01 at gmail.com Sat Nov 15 23:12:36 2014 From: ikorot01 at gmail.com (Igor Korot) Date: Sat, 15 Nov 2014 23:12:36 -0500 Subject: Where is inspect() located? Message-ID: Hi, ALL, C:\Documents and Settings\Igor.FORDANWORK\Desktop\winpdb>python Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from a.b import c >>> print c.classA >>> inspect.getmembers(c.classA) Traceback (most recent call last): File "", line 1, in NameError: name 'inspect' is not defined >>> import lib Traceback (most recent call last): File "", line 1, in ImportError: No module named lib >>> In the https://docs.python.org/2/library/inspect.html, it says it is located in Lib/inspect.py. What am I missing? Or its only for 3.x? Thank you. From rosuav at gmail.com Sat Nov 15 23:29:22 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Nov 2014 15:29:22 +1100 Subject: Where is inspect() located? In-Reply-To: References: Message-ID: On Sun, Nov 16, 2014 at 3:12 PM, Igor Korot wrote: > In the https://docs.python.org/2/library/inspect.html, it says it is > located in Lib/inspect.py. > > What am I missing? Or its only for 3.x? You need to import it. If you're curious, you can find out exactly where it's imported from like this: Python 2.7.3 (default, Mar 13 2014, 11:03:55) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import inspect >>> inspect.__file__ '/usr/lib/python2.7/inspect.pyc' The path will be different on your system, as this is a Debian box, but the technique is the same. However, all that matters is that you hadn't imported it. The Lib directory is one of the places where importable modules are found. ChrisA From davea at davea.name Sat Nov 15 23:36:15 2014 From: davea at davea.name (Dave Angel) Date: Sat, 15 Nov 2014 23:36:15 -0500 (EST) Subject: Where is inspect() located? References: Message-ID: Igor Korot Wrote in message: > Hi, ALL, > > C:\Documents and Settings\Igor.FORDANWORK\Desktop\winpdb>python > Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> from a.b import c >>>> print c.classA > And what is your question here? >>>> inspect.getmembers(c.classA) > Traceback (most recent call last): > File "", line 1, in > NameError: name 'inspect' is not defined That's because you haven't imported it. >>>> import lib > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named lib The module is called inspect. import inspect > -- DaveA From rantingrickjohnson at gmail.com Sun Nov 16 00:01:14 2014 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Sat, 15 Nov 2014 21:01:14 -0800 (PST) Subject: PyWart: "Python's import statement and the history of external dependencies" Message-ID: <066c46c8-a04d-4489-b15a-b603c1b1818b@googlegroups.com> Python's attempt to solve the "external dependencies problem" has yet to produce the results that many people, including myself, would like. Actually, Python is not alone in this deficiency, no, Python is just *ANOTHER* language in a *STRING* of languages over the years who has *YET AGAIN* implemented the same old crusty design patterns, packaged them in a shiny metallic wrapping paper with a big red bow on top, and hoped that no one would notice the stench... WELL I NOTICED M.F.! Before we can formulate a solution to this mess, we must first obtain an "inside perspective" of the "world" in which a Python script lives during run-time. ============================================================ Welcome to "Python Gardens": a master planned community ============================================================ Well... urm, sort of. @_@ I like to analyze problems, when possible, in relation to real world "tangible" examples. So for me, i like to think of the main script (aka: __main__) as an apartment building, and each module that runs under the main script as a single apartment, and finally, the inhabitants of the apartments as objects. Furthermore, we can define the apartment building as being "global space", and each individual apartment as being "local space". The first law we encounter is that "global space" is reserved for all tenants/guest, but "local space" is by *invitation* only! You can think of "import" as similar to sending out an invitation, and requesting that a friend join you inside your apartment (we'll get back to "import" later). And of course, with this being the 21st century and all, every apartment has *local* access to *global* resources like water and electrical. In Python, these "global resources" are available "locally" in every module via the implicit namespace of "__builtins__". You can think of built-ins as a "house keeper" robot that lives in every apartment (I call mine "Rosie"). It was there when you moved in --a "house warming" gift of sorts-- and it helps you with chores and makes your life a little easier. Sometimes i abuse my robot but i always apologize afterwards. Now that we know how the global and local spaces are defined (in the context of modules), and what implicit/explicit "gifts" (are supplied), and "rules" (are demanded) in our little Python world, we have a good basis to start understanding why Python's import mechanism is at best a "helpful failure" that only *naively* attempts to streamline the management of such an important language feature as external dependencies! Up until this point, our apartment example has not mapped the actual *mechanics* of "import" to a real world example, but now that we have the correct "perspective", we can tread into the dark and damp underworld that is "import". Remember when i said: "import is like sending out an invitation"? Well, in actuality, import is only *superficially* similar to "sending out an invitation". You see, when you send an invitation in real life, the most important two things you'll need are a *name* and an *address* --a name so you'll know *who* to send the invitation to, and an address so you'll know *where* to send the invitation-- but Python's import mechanism does not work that way. When you import an external dependency into a Python module all you need is the name of a module -- addresses are neither required *OR* allowed! Like almost all modern languages, Python has adopted the ubiquitous practice of internalizing a mapping of known directories from which to search for modules (called a search path), so when we "import somemodule" the following happens (Note: I'm not going into too many details for the sake of topic): 1. Python checks if the external resource has already been loaded if not 1, then 2. Python looks in a few "special places" if not 2, then 3. Python searches one-by-one the directories in sys.path RESULT: Python finds the resource or barfs an exception. I have no problem with step 1, however, step 2 and step 3 can be redundant, excessive, and even unreliable. I can explain better why i levee such harsh words for "import" by going back to our apartment building example. Let's imagine that Python is the "lobby boy" of our apartment building. And in our little example, one of the duties of the "lobby boy" is to manage invitations between tenants and guests. Each time a tenant wants to invite someone into their apartment, they must pick up the phone, press the import button (which connects them to the lobby boy via a voice connection) and they say the name of the person they want to invite. But *EVEN IF* they know the address of the recipient, they are not allowed to say the address to the lobby boy, no, because *THIS* building is owned by a evil tyrant, who has declared that any mention of an address when calling import is punishable by the fatal exception! So, being a good tenant who does not want to *DIE*, they simply mention the recipients name, roll their eyes, hang up the phone, and hope that lobby boy can locate the correct recipient It is at this point that the lobby boy (aka: Python) springs into action. The lobby boy has a gargantuan task ahead of him, he must locate a tenant based solely on the name with no idea of which apartment the tenant resides. And, realizing that he has a terrible memory, and that some of the building's pranksters have sent him on "wild goose chases" for recipients that do not exist, his first action is to check his daily log and ensure he did not *already* deliver the invitation... DAMN! Not in the log! So then the lobby boy checks for a few special places... DAMN! not in my "special places" either! Sadly, the lobby knows that now he must check the ENTIRE building, of which contains thousands of tenants. So he starts on floor one (sys.path[0]), knocks on all the doors, then proceeds to floor two (sys.path[1]), knocks on all those doors..., and so on and so forth until he locates the recipient or dies of exhaustion -- whichever comes first. It is this point that i find the import machinery to be lacking. It's not only the *needless* exhaustive searching via such an unintelligent algorithm, but also the great possibility of importing the wrong resource. "Yeah Rick, but who wants to include a file-path for importing modules, the whole reason for import was to abstract away the file-system and file-paths, etc... Are you proposing we go back and re-adopt the historical conventions?" Absolutely not. In most day to day usage Python's import statement works just fine, it's a cycle burner, but who cares about a lobby boy anyway right? I have thousands of modules on my hdrive, and many many directories holding them, even if i could overlook the "cycle bonfire" of import's underlying machinery, the list of intuit-able names for modules are finite, and i'm not about to start tagging file-names because then i'm back to the file-system again -- but instead of slashes i'm using underscores. NO THANKS!. What the creators of "import" fail to understand is that a trade-off has been made, and the Python programmer has been given the short end of a very long stick, and now we're being beaten with the very long stick and he nothing to defend himself with but a tooth-pick! Creating an "implicit name resolution system" (aka: import) to abstract away an "explicit name resolution system" (file-paths) has resulted in more problems that it can solve: 1. Name clashes! 2. Smaller name pool! 3. Machinery is too implicit! 4. Circular imports are inevitable! 5. Much too difficult to use and/or explain! 6. Too many "gotchas"! Of course, if "import" is not problematic enough for you, one you use one of the many modules like importlib, imp, importil, ihooks, or __import__ function, and then become more confused!! -- Python's external dependency is not only broken, it's discombobulated and downright confusing! In closing, there is only one thing you need to know about Python's import statement: it is deceptively easy to underestimate it's ability to *EFF UP* your expectations! From rosuav at gmail.com Sun Nov 16 00:16:40 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Nov 2014 16:16:40 +1100 Subject: PyWart: "Python's import statement and the history of external dependencies" In-Reply-To: <066c46c8-a04d-4489-b15a-b603c1b1818b@googlegroups.com> References: <066c46c8-a04d-4489-b15a-b603c1b1818b@googlegroups.com> Message-ID: On Sun, Nov 16, 2014 at 4:01 PM, Rick Johnson wrote: > Creating an "implicit name resolution system" (aka: import) > to abstract away an "explicit name resolution system" > (file-paths) has resulted in more problems that it can solve: > > 1. Name clashes! > 2. Smaller name pool! > 3. Machinery is too implicit! > 4. Circular imports are inevitable! > 5. Much too difficult to use and/or explain! > 6. Too many "gotchas"! And the ability to write cross-platform code! ChrisA From drsalists at gmail.com Sun Nov 16 00:18:20 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Sat, 15 Nov 2014 21:18:20 -0800 Subject: Efficient Threading In-Reply-To: References: Message-ID: On Fri, Nov 14, 2014 at 10:42 AM, Empty Account wrote: > Hi, > > I am thinking about writing a load test tool in Python, so I am interested > in how I can create the most concurrent threads/processes with the fewest OS > resources. I would imagine that I/O would need to be non-blocking. > > There are a number of options including standard library threading, gevent, > stackless python, cython parallelism etc. Because I am new to Python, I am > unsure on which libraries to choose. I am not really bothered on the tool > chain, just as long as it is Python related (so I'd use PyPy for example). If you need a large amount of concurrency, you might look at Jython with threads. Jython threads well. If you don't intend to do more than a few hundred concurrent things, you might just go with CPython and multiprocessing. Fortunately, the interfaces are similar, so you can try one and switch to another later without huge issues. The main difference is that multiprocessing doesn't show variable changes to other processes, while multithreading (more often) does. From drsalists at gmail.com Sun Nov 16 00:25:46 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Sat, 15 Nov 2014 21:25:46 -0800 Subject: fileno() not supported in Python 3.1 In-Reply-To: References: Message-ID: On Thu, Nov 13, 2014 at 3:48 PM, wrote: > import sys > for stream in (sys.stdin, sys.stdout, sys.stderr): > print(stream.fileno()) > > > io.UnsupportedOperation: fileno > > Is there a workaround? > -- > https://mail.python.org/mailman/listinfo/python-list Works for me, although it's a little different in Jython: $ pythons --command 'import sys; print(sys.stdin.fileno())' /usr/local/cpython-2.4/bin/python good 0 /usr/local/cpython-2.5/bin/python good 0 /usr/local/cpython-2.6/bin/python good 0 /usr/local/cpython-2.7/bin/python good 0 /usr/local/cpython-3.0/bin/python good 0 /usr/local/cpython-3.1/bin/python good 0 /usr/local/cpython-3.2/bin/python good 0 /usr/local/cpython-3.3/bin/python good 0 /usr/local/cpython-3.4/bin/python good 0 /usr/local/jython-2.7b3/bin/jython good org.python.core.io.StreamIO at 170ed6ab /usr/local/pypy-2.3.1/bin/pypy good 0 /usr/local/pypy-2.4.0/bin/pypy good 0 /usr/local/pypy3-2.3.1/bin/pypy good 0 /usr/local/pypy3-2.4.0/bin/pypy good 0 From rosuav at gmail.com Sun Nov 16 00:29:45 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Nov 2014 16:29:45 +1100 Subject: fileno() not supported in Python 3.1 In-Reply-To: References: Message-ID: On Sun, Nov 16, 2014 at 4:25 PM, Dan Stromberg wrote: > Works for me, although it's a little different in Jython: > $ pythons --command 'import sys; print(sys.stdin.fileno())' > /usr/local/jython-2.7b3/bin/jython good org.python.core.io.StreamIO at 170ed6ab Huh, that is curious. According to its CPython docstring, it's supposed to return an integer (no idea if that's standardized)... but I guess if os.read() takes that StreamIO object, then it'll do as well. ChrisA From kevinarpe at gmail.com Sun Nov 16 00:25:42 2014 From: kevinarpe at gmail.com (kevinarpe at gmail.com) Date: Sat, 15 Nov 2014 21:25:42 -0800 (PST) Subject: frame.f_locals['__class__'] -- When does it (not) exist and why? Message-ID: Hello, I am CPython 3.4+ user on Linux. I am writing a little library for myself to improve the traceback module -- print_exc() and friends. I want to include the module name, class name (if possible), and function name. Some background: traceback.print_exc() iterates through traceback objects returned by sys.exc_info()[2]. traceback.tb_frame holds each stack frame. (I call this 'frame' below.) My improved library nearly works, but I noticed a strange corner case around frame.f_locals['__class__']. When super().__init__() is called, a 'magic' local appears in frame.f_locals called '__class__'. Helpfully, it has the correct class for the context, which will differ from type(self). (I discovered this magic local by poking around in the debugger. I am unable to find any official documentation on it.) Here is the quirk: In the last class in a chain of super.__init__() calls, this magic local disappears. So I have no idea the correct class for the context. I am stuck with frame.f_locals['self']. How can I recover the correct class for the context in the last __init__() method? I noticed if I chance the last class to inherit from object, the magic local '__class__' appears again. A little code to demonstrate: # do not subclass object here def class X: def __init__(self): # frame.f_locals['__class__'] does not exist pass def class Y(X): def __init__(self): # frame.f_locals['__class__'] == Y super().__init__() def class Z(Y): def __init__(self): super().__init__() # subclass object here def class X2(object): def __init__(self): # frame.f_locals['__class__'] == X2 pass def class Y2(X2): def __init__(self): # frame.f_locals['__class__'] == Y2 super().__init__() def class Z2(Y2): def __init__(self): super().__init__() Thanks, Arpe From rosuav at gmail.com Sun Nov 16 00:40:05 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Nov 2014 16:40:05 +1100 Subject: frame.f_locals['__class__'] -- When does it (not) exist and why? In-Reply-To: References: Message-ID: On Sun, Nov 16, 2014 at 4:25 PM, wrote: > When super().__init__() is called, a 'magic' local appears in frame.f_locals called '__class__'. Helpfully, it has the correct class for the context, which will differ from type(self). (I discovered this magic local by poking around in the debugger. I am unable to find any official documentation on it.) > Interesting. Are you sure you can't get the class name via the function, rather than depending on this magic local? That seems fragile. Your example code isn't currently runnable ("def class"); can you provide a self-contained program that actually attempts to display something? It'd be helpful for those of us who aren't familiar with internal and esoteric details of tracebacks and __init__ :) ChrisA From kevinarpe at gmail.com Sun Nov 16 01:28:13 2014 From: kevinarpe at gmail.com (kevinarpe at gmail.com) Date: Sat, 15 Nov 2014 22:28:13 -0800 (PST) Subject: frame.f_locals['__class__'] -- When does it (not) exist and why? In-Reply-To: References: Message-ID: Apologies for previous code example. Yes, the 'def class' should read: 'class'. Writing a sample to better demonstrate the issue made me realize that super() is doing something special. It is injecting the magic '__class__' local. I should rephrase my question: How do I get the declaring class from from a traceback object? Currently, I cannot see how to do it. Magic local '__class__' is not always available. And locals 'cls' and 'self' may come from subclasses. Code sample: import inspect import sys class X: def __init__(self): # Magic local '__class__' is missing raise ValueError() class Y(X): def __init__(self): super().__init__() class X2: def __init__(self): # Calling super() here will 'inject' magic local '__class__' super().__init__() raise ValueError() class Y2(X2): def __init__(self): super().__init__() def main(): _main(lambda: Y()) _main(lambda: Y2()) def _main(func): try: func() except: (exc_type, exc_value, traceback) = sys.exc_info() tb = traceback while tb: frame = tb.tb_frame # See: code.co_freevars. Sometimes magic '__class__' appears. code = frame.f_code lineno = frame.f_lineno func_name = code.co_name file_path = code.co_filename module = inspect.getmodule(frame, file_path) module_name = module.__name__ print("File: {}, Line: {}, Func: {}, Module: {}".format(file_path, lineno, func_name, module_name)) for name in ('__class__', 'self', 'cls'): if name in frame.f_locals: print(" {}: '{}'".format(name, frame.f_locals[name])) tb = tb.tb_next print() if __name__ == '__main__': main() From dieter at handshake.de Sun Nov 16 02:14:05 2014 From: dieter at handshake.de (dieter) Date: Sun, 16 Nov 2014 08:14:05 +0100 Subject: caught in the import web again References: Message-ID: <8761efk476.fsf@handshake.de> "Charles T. Smith" writes: > Now, I'm getting these errors: > > ImportError: cannot import name ... > > and > > AttributeError: 'module' object has no attribute ... > > (what is 'module'?) > > Is there a way to resolve this without having to restructure my code > every couple of days? > > I thought using imports of the form: > > from module import symbol > > was the "right way" to avoid these hassles... I have not noticed your previous posts regarding import problems -- thus, I may repeats things already said. Usually, Python imports are straight forward and do not lead to surprises. There are two exceptions: recursive imports and imports in separate threads. Let's look at the problem areas in turn. Recursive imports. In this case you have module "A" which imports module "B" (maybe indirectly via a sequence of intervening imports) which imports module "A". In this, "import" means either "import ..." or "from ... import ..." (it does not matter). When module "B" tries to import module "A", then "A" is not yet complete (as during the execution of "A"'s initialization code, it started to import "B" (maybe indirectly) and the following initialization code has not yet been executed). As a consequence, you may get "AttributeError" (or "ImportError") when you try to access things from "A". To avoid problems like this, try to avoid recursive imports. One way to do this, are local imports -- i.e. imports inside a function. This way, the import happens when the functions is called which (hopefully) happens after module initialization. Imports and threads. The import machinery changes global data structures (e.g. "sys.modules"). To protect those changes, it uses a lock, held while an import is in progress. When, during an import, a separate thread tries to import something, it blocks - waiting for the import lock to be released. In case, the importing thread waits on this thread, then the system deadlocks. To avoid this: do not start threads during imports. From googberg at gmail.com Sun Nov 16 02:39:50 2014 From: googberg at gmail.com (Garrett Berg) Date: Sun, 16 Nov 2014 00:39:50 -0700 Subject: encode and decode builtins Message-ID: I made the switch to python 3 about two months ago, and I have to say I love everything about it, *especially* the change to using only bytes and str (no more unicode! or... everything is unicode!) As someone who works with embedded devices, it is great to know what data I am working with. However, there are times that I do not care what data I am working with, and I find myself writing something like: if isinstance(data, bytes): data = data.decode() This is tedious and breaks the pythonic method of not caring about what your input is. If I expect that my input can always be decoded into valid data, then why do I have to write this? Instead, I would like to propose to add *encode* and *decode* as builtins. I have written simple code to demonstrate my desire: https://gist.github.com/cloudformdesign/d8065a32cdd76d1b3230 There may be a few edge cases I am missing, which would all the more prove my point -- we need a function like this! Basically, if I expect my data to be a string I can just write: data = decode(data) ?Which would accomplish two goals: explicitly stating what I expect of my data, and doing so concisely and cleanly. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Sun Nov 16 02:50:45 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 16 Nov 2014 18:50:45 +1100 Subject: encode and decode builtins References: Message-ID: <85ppcn37oq.fsf@benfinney.id.au> Garrett Berg writes: > I made the switch to python 3 about two months ago, and I have to say > I love everything about it, *especially* the change to using only > bytes and str (no more unicode! or... everything is unicode!) As > someone who works with embedded devices, it is great to know what data > I am working with. THanks! It is great to hear from people directly benefiting from this clear distinction. > However, there are times that I do not care what data I am working > with, and I find myself writing something like: > > if isinstance(data, bytes): data = data.decode() Why are you in a position where ?data? is not known to be bytes? If you want ?unicode? objects, isn't the API guaranteeing to provide them? > This is tedious and breaks the pythonic method of not caring about > what your input is. I wouldn't call that Pythonic. Rather, in the face of ambiguity (?is this text or bytes??), Pythonic code refuses the temptation to guess: you need to clarify what you have as early as possible in the process. > If I expect that my input can always be decoded into valid data, then > why do I have to write this? I don't know. Why do you have to? -- \ ?God was invented to explain mystery. God is always invented to | `\ explain those things that you do not understand.? ?Richard P. | _o__) Feynman, 1988 | Ben Finney From googberg at gmail.com Sun Nov 16 02:57:27 2014 From: googberg at gmail.com (Garrett Berg) Date: Sun, 16 Nov 2014 00:57:27 -0700 Subject: isiter builtin Message-ID: I have been working with python for a few years now, and two of my favorite features about it are iterators and duck typing. The fact that every iterator under the sun can be accessed with a simple for loop is one of the most amazing features of python. However, there are times when I want to do type checking, and the builtin function *isinstance* is of great use. However, this function fails to be satisfactory in returning whether the object is a valid iterator. The call hasattr(obj, '__iter__') also fails because str and bytes types both have that, and are rarely what you mean when you are asking if something is an iterator (how often have you iterated over a string?) I propose a new builtin to address this problem. I have created code for it here: https://gist.github.com/cloudformdesign/de9b54d30547ddd28ec4 This will allow simple type checking on an input to determine whether it is an iterator. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Sun Nov 16 03:14:10 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Nov 2014 19:14:10 +1100 Subject: isiter builtin In-Reply-To: References: Message-ID: On Sun, Nov 16, 2014 at 6:57 PM, Garrett Berg wrote: > However, there are times when I want to do type checking, and the builtin > function isinstance is of great use. However, this function fails to be > satisfactory in returning whether the object is a valid iterator. The call > hasattr(obj, '__iter__') also fails because str and bytes types both have > that, and are rarely what you mean when you are asking if something is an > iterator (how often have you iterated over a string?) But the correct answer is that str and bytes are both iterable. So what you're asking is not whether something's a valid iterator, but whether it is a non-string-iterable, which is a definitely different thing. And that's basically what your gist is doing, although there's a slight error in its docstring: you talk about "iterators", but you're actually looking for "iterables". In Python, an iterable is something which you can iterate over: calling iter() on it will return something (rather than raising TypeError), which means you can use it in a 'for' loop. An iterator is an iterable which, when you call iter() on it, returns *itself*. Normally, you get an iterator by calling iter() on something iterable, if that makes sense. For example: >>> iter([1,2,3,4]) >>> iter(_) >>> iter(range(10)) >>> iter(_) >>> iter(globals()) >>> iter(_) The list, range, and dict (as returned by globals()) are all iterable; the ...iterator objects are iterators. I suspect that your use-case is actually looking for iterables, not iterators, so the fix is simply a docs change. At that point, your function becomes 100% correct, and a perfectly idiomatic way to express "iterable that isn't one of these types". It doesn't need to be a builtin, though. Incidentally, if you're doing a lot of isinstance tests like this, you might want to look at the collections module, which has some 'base classes' which can be used like that. >>> isinstance([1,2,3],collections.Iterable) True ChrisA From ben+python at benfinney.id.au Sun Nov 16 03:23:36 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 16 Nov 2014 19:23:36 +1100 Subject: isiter builtin References: Message-ID: <85lhnb365z.fsf@benfinney.id.au> Garrett Berg writes: > However, there are times when I want to do type checking, and the > builtin function *isinstance* is of great use. I would advise that when you think you want type checking, you are probably being overly restrictive. > However, this function fails to be satisfactory in returning whether > the object is a valid iterator. The call hasattr(obj, '__iter__') also > fails because str and bytes types both have that Yes, because both ?str? and ?bytes? objects are valid iterables. Using ?isinstance? in particular is a code smell: it breaks duck typing (checking not for the object's type, but for how the object behaves, which is usually what matters) and is almost always the wrong choice. Not *always* the wrong choice, which is why it's provided, and which is why I call it a code smell: a strong but not infallible sign something is wrong with the code as written. When you reach for ?isinstance? (LBYL, which is un-Pythonic), instead ask yourself: ignoring what type this object is, how do I want it to behave, and should I just use it in the expectation that it will raise an exception if it doesn't support that (EAFP, which is very Pythonic)? -- \ ?What is needed is not the will to believe but the will to find | `\ out, which is the exact opposite.? ?Bertrand Russell, _Free | _o__) Thought and Official Propaganda_, 1928 | Ben Finney From cts.private.yahoo at gmail.com Sun Nov 16 03:53:34 2014 From: cts.private.yahoo at gmail.com (Charles T. Smith) Date: Sun, 16 Nov 2014 08:53:34 +0000 (UTC) Subject: caught in the import web again References: Message-ID: On Sun, 16 Nov 2014 08:14:05 +0100, dieter wrote: > "Charles T. Smith" writes: >> Now, I'm getting these errors: >> >> ImportError: cannot import name ... >> >> and >> >> AttributeError: 'module' object has no attribute ... >> >> (what is 'module'?) >> >> Is there a way to resolve this without having to restructure my code >> every couple of days? >> >> I thought using imports of the form: >> >> from module import symbol >> >> was the "right way" to avoid these hassles... > > I have not noticed your previous posts regarding import problems -- > thus, I may repeats things already said. > > Usually, Python imports are straight forward and do not lead to > surprises. There are two exceptions: recursive imports and imports in > separate threads. Let's look at the problem areas in turn. > > Recursive imports. In this case you have module "A" which imports module > "B" (maybe indirectly via a sequence of intervening imports) which > imports module "A". In this, "import" means either "import ..." or "from > ... import ..." (it does not matter). When module "B" tries to import > module "A", then "A" is not yet complete (as during the execution of > "A"'s initialization code, it started to import "B" (maybe indirectly) > and the following initialization code has not yet been executed). As a > consequence, you may get "AttributeError" (or "ImportError") when you > try to access things from "A". To avoid problems like this, try to avoid > recursive imports. One way to do this, are local imports -- i.e. imports > inside a function. This way, the import happens when the functions is > called which (hopefully) happens after module initialization. Yes, we're talking about recursive imports here. It's a complex, object- oriented system with big classes and little classes that are strongly interrelated. I can get the imports configured properly so everything works but if I make a little change to the code, then suddenly all my imports are broken and I must painstakingly go through the whole structure, reorganizing them. Are others equally frustrated by this or is there a trick or principle that I'm missing. At this point, I guess the way I'll have to proceed is to put every class in its own file, no matter how small. Hopefully that takes care of the problem. I compared perl's object-oriented philosophy with python's and didn't like how perl *requires* you to put everything into its own file. Now it looks like python does, too, implicitly. cts www.creative-telcom-solutions.de From pierre.quentel at gmail.com Sun Nov 16 03:54:14 2014 From: pierre.quentel at gmail.com (Pierre Quentel) Date: Sun, 16 Nov 2014 00:54:14 -0800 (PST) Subject: [ANN] Brython 3.0.0 relased Message-ID: <3938dee7-35d6-46fc-8606-13906f3202f8@googlegroups.com> Hi, Version 3.0.0 of Brython has been released recently Brython is an implementation of Python 3 running in the browser, with an interface to DOM elements and events. It allows writing web client applications with Python instead of Javascript. Python programs are inserted in the HTML page inside tags