Re: xlrd 0.7.6 released!
On 04/04/2012 20:26, Karim wrote: By the way, I reported an issue to you in this mailing list some time ago about unicode data. I have no recollection of this. If you experience any bugs, the correct place to report them is: https://github.com/python-excel/xlrd/issues cheers, Chris -- Simplistix - Content Management, Batch Processing Python Consulting - http://www.simplistix.co.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: Cannot connect to IMAP server in Python 3.2
On Wed, 04 Apr 2012 22:13:55 -0700, Steve Howell wrote: On Apr 4, 9:49 pm, Steven D'Aprano steve +comp.lang.pyt...@pearwood.info wrote: I can connect to an IMAP server using Python 2.6: steve@runes:~$ python2.6 Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) [GCC 4.4.5] on linux2 Type help, copyright, credits or license for more information. import imaplib server = imaplib.IMAP4_SSL('x') print server imaplib.IMAP4_SSL instance at 0xb7183c4c But when I try with Python 3.2, it just sits there until it times out: steve@runes:~$ python3.2 Python 3.2.2 (default, Feb 29 2012, 18:11:33) [GCC 4.4.5] on linux2 Type help, copyright, credits or license for more information. import imaplib server = imaplib.IMAP4('x', imaplib.IMAP4_SSL_PORT) Traceback (most recent call last): [...] socket.timeout: timed out What am I doing wrong? Is it simply the wrong port? (IMAP4_SSL_PORT vs. IMAP4_PORT) No, it is the correct port, 993. How long do you wait before seeing the timeout? Indefinitely. Have you tried print-debugging within your local copy of imaplib.py? The code related to making the connection just wraps socket.create_connection: I'm not going to start debugging the standard library until after I'm satisfied that I'm not doing something wrong. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Cannot connect to IMAP server in Python 3.2
On Apr 5, 12:09 am, Steven D'Aprano steve +comp.lang.pyt...@pearwood.info wrote: On Wed, 04 Apr 2012 22:13:55 -0700, Steve Howell wrote: On Apr 4, 9:49 pm, Steven D'Aprano steve +comp.lang.pyt...@pearwood.info wrote: I can connect to an IMAP server using Python 2.6: steve@runes:~$ python2.6 Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) [GCC 4.4.5] on linux2 Type help, copyright, credits or license for more information. import imaplib server = imaplib.IMAP4_SSL('x') print server imaplib.IMAP4_SSL instance at 0xb7183c4c But when I try with Python 3.2, it just sits there until it times out: steve@runes:~$ python3.2 Python 3.2.2 (default, Feb 29 2012, 18:11:33) [GCC 4.4.5] on linux2 Type help, copyright, credits or license for more information. import imaplib server = imaplib.IMAP4('x', imaplib.IMAP4_SSL_PORT) Traceback (most recent call last): [...] socket.timeout: timed out What am I doing wrong? Is it simply the wrong port? (IMAP4_SSL_PORT vs. IMAP4_PORT) No, it is the correct port, 993. How long do you wait before seeing the timeout? Indefinitely. Have you tried print-debugging within your local copy of imaplib.py? The code related to making the connection just wraps socket.create_connection: I'm not going to start debugging the standard library until after I'm satisfied that I'm not doing something wrong. I'm not suggesting that you debug the standard library because I think the library itself is broken. I'm suggesting that using the source code that's freely available to you can help you have some insight on what's going wrong. Do you have a working theory on what you're doing wrong? You've already ruled out the port. Why are you changing the invocation between versions of Python? imaplib.IMAP4_SSL('x') # 2.6 imaplib.IMAP4('x', imaplib.IMAP4_SSL_PORT) # 3.2 I'm sure the standard library works fine, and you're just doing something silly, like mistyping the host name or forgetting to start the server. Maybe you're running 3.2 in a slightly different OS environment? The ONE thing that you can find out almost immediately is what self.host and self.post are set to when _create_socket gets called. You could almost immediately narrow down the problem to socket.create_connection() instead of IMAP. -- http://mail.python.org/mailman/listinfo/python-list
regexp partial matching, or hitEnd
I want something like this in python : http://stackoverflow.com/questions/2526756/can-java-util-regex-pattern-do-partia...http://stackoverflow.com/questions/2526756/can-java-util-regex-pattern-do-partial-matches First you have to call one of the standard methods to apply the regex, like matches() or find(). If that returns false, you can use the hitEnd() method to find out if some longer string could have matched: String[] inputs = { AA, BB }; Pattern p = Pattern.compile(AB); Matcher m = p.matcher(); for (String s : inputs) { m.reset(s); System.out.printf(%s -- full match: %B; partial match: %B%n, s, m.matches(), m.hitEnd()); } output: AA -- full match: FALSE; partial match: TRUE BB -- full match: FALSE; partial match: FALSE So. Is there already some function like hitEnd() in any python regexp library? Or if not, maybe it's could be added in the feature to the standart re module? :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Cannot connect to IMAP server in Python 3.2
On Apr 5, 12:09 am, Steven D'Aprano steve +comp.lang.pyt...@pearwood.info wrote: On Wed, 04 Apr 2012 22:13:55 -0700, Steve Howell wrote: On Apr 4, 9:49 pm, Steven D'Aprano steve +comp.lang.pyt...@pearwood.info wrote: I can connect to an IMAP server using Python 2.6: steve@runes:~$ python2.6 Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) [GCC 4.4.5] on linux2 Type help, copyright, credits or license for more information. import imaplib server = imaplib.IMAP4_SSL('x') print server imaplib.IMAP4_SSL instance at 0xb7183c4c But when I try with Python 3.2, it just sits there until it times out: steve@runes:~$ python3.2 Python 3.2.2 (default, Feb 29 2012, 18:11:33) [GCC 4.4.5] on linux2 Type help, copyright, credits or license for more information. import imaplib server = imaplib.IMAP4('x', imaplib.IMAP4_SSL_PORT) Traceback (most recent call last): [...] socket.timeout: timed out What am I doing wrong? Is it simply the wrong port? (IMAP4_SSL_PORT vs. IMAP4_PORT) No, it is the correct port, 993. How long do you wait before seeing the timeout? Indefinitely. Have you tried print-debugging within your local copy of imaplib.py? The code related to making the connection just wraps socket.create_connection: I'm not going to start debugging the standard library until after I'm satisfied that I'm not doing something wrong. -- Steven What happens when you do this? import imaplib, socket socket.create_connection(('x', imaplib.IMAP4_SSL_PORT)) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: JSON expects double-quote marks, not single: v = json.loads({'test':'test'}) fails v = json.loads('{test:test}') succeeds You mean JSON expects a string with valid JSON? Quelle surprise. -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Thu, Apr 5, 2012 at 9:06 PM, Duncan Booth duncan.booth@invalid.invalid wrote: Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: JSON expects double-quote marks, not single: v = json.loads({'test':'test'}) fails v = json.loads('{test:test}') succeeds You mean JSON expects a string with valid JSON? Quelle surprise. The surprise is between JSON and JavaScript (the latter does accept single quotes), and Python is correctly implementing the JSON spec. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Thu, 05 Apr 2012 11:06:11 +, Duncan Booth wrote: Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: JSON expects double-quote marks, not single: v = json.loads({'test':'test'}) fails v = json.loads('{test:test}') succeeds You mean JSON expects a string with valid JSON? Quelle surprise. No. The surprise is that there exists a tool invented in the 21st century that makes a distinction between strings quoted with and those quoted with '. Being used to a sensible language like Python, it boggled my brain the first time I tried to write some JSON and naturally treated the choice of quote mark as arbitrary. It especially boggled my brain when I saw the pathetically useless error message generated: py json.loads({'test':'test'}) Traceback (most recent call last): File stdin, line 1, in module File /usr/local/lib/python3.2/json/__init__.py, line 307, in loads return _default_decoder.decode(s) File /usr/local/lib/python3.2/json/decoder.py, line 351, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File /usr/local/lib/python3.2/json/decoder.py, line 367, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Expecting property name: line 1 column 1 (char 1) Expecting property name??? WTF??? The reason this is a Gotcha rather than a bug is because the JSON standard specifies the behaviour (probably in order to be compatible with Javascript). Hence, although the behaviour is mind-numbingly stupid, it is deliberate and not a bug. Hence, a gotcha. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: regexp partial matching, or hitEnd
On 05/04/2012 08:29, Константин Куликов wrote: I want something like this in python : http://stackoverflow.com/questions/2526756/can-java-util-regex-pattern-do-partia...http://stackoverflow.com/questions/2526756/can-java-util-regex-pattern-do-partial-matches First you have to call one of the standard methods to apply the regex, like matches() or find(). If that returns false, you can use the hitEnd() method to find out if some longer string could have matched: Dark satanic writing snipped :) So. Is there already some function like hitEnd() in any python regexp library? Or if not, maybe it's could be added in the feature to the standart re module? :) More likely to go into the new regex module that's on pypi. Talking of which is this going into Python 3.3, I see it's mentioned in PEP398 but can't find any mention in the Python 3.3 What's New docs, or have I simply missed something? -- Cheers. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Cannot connect to IMAP server in Python 3.2
On Thu, 05 Apr 2012 00:21:31 -0700, Steve Howell wrote: I'm not suggesting that you debug the standard library because I think the library itself is broken. I'm suggesting that using the source code that's freely available to you can help you have some insight on what's going wrong. Do you have a working theory on what you're doing wrong? Actually, between you and me and the thousands of others reading this thread, I actually do suspect it is a bug in the std library implementation. But the suspicion is only that, and my first *assumption* is that it is more likely I am doing something wrong. Hence my question. You've already ruled out the port. Why are you changing the invocation between versions of Python? Because imaplib.IMAP4_SSL apparently no longer exists in Python 3. server = imaplib.IMAP4_SSL('x') Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'module' object has no attribute 'IMAP4_SSL' imaplib.IMAP4_SSL('x') # 2.6 imaplib.IMAP4('x', imaplib.IMAP4_SSL_PORT) # 3.2 I'm sure the standard library works fine, and you're just doing something silly, like mistyping the host name or forgetting to start the server. Maybe you're running 3.2 in a slightly different OS environment? If you look carefully at my copy-and-pasted sessions, you will see that both of them are on the same host, runes. While I suppose that technically I could have two hosts both called runes, in fact I only have one :) And no, I have not mistyped the host name. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Cannot connect to IMAP server in Python 3.2
On Thu, 05 Apr 2012 12:16:09 +, Steven D'Aprano wrote: On Thu, 05 Apr 2012 00:21:31 -0700, Steve Howell wrote: Why are you changing the invocation between versions of Python? Because imaplib.IMAP4_SSL apparently no longer exists in Python 3. server = imaplib.IMAP4_SSL('x') Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'module' object has no attribute 'IMAP4_SSL' Wait a minute... IMAP4_SSL is documented as existing in Python 3. And when I run Python 3.2 on a Centos machine, instead of Debian, it includes IMAP4_SSL which works fine. [steve@ando ~]$ python3.2 Python 3.2.2 (default, Mar 4 2012, 10:50:33) [GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2 Type help, copyright, credits or license for more information. py import imaplib py server = imaplib.IMAP4_SSL('x') py server imaplib.IMAP4_SSL object at 0xb7b8632c So there's something screwy going on here. Why does my Python 3.2 on Debian not include IMAP4_SSL, but Python 2.6 does? raises eyebrow -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
In article 4f7d896f$0$29983$c3e8da3$54964...@news.astraweb.com, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: You mean JSON expects a string with valid JSON? Quelle surprise. No. The surprise is that there exists a tool invented in the 21st century that makes a distinction between strings quoted with and those quoted with '. Being used to a sensible language like Python, it boggled my brain the first time I tried to write some JSON and naturally treated the choice of quote mark as arbitrary. Your brain has a low boggle threshold. There's absolutely no reason why JSON should follow Python syntax rules. Making it support either kind of quotes would have complicated every JSON library in the world, for no added value. Nobody should ever be hand-writing JSON (just like nobody should ever be hand-writing XML). Just use the supplied library calls and you'll never have to worry about low-level minutia like this again. It especially boggled my brain when I saw the pathetically useless error message generated: py json.loads({'test':'test'}) [...] ValueError: Expecting property name: line 1 column 1 (char 1) Expecting property name??? WTF??? One of the hardest things about writing parsers is generating helpful error messages when things don't parse. But, it's only of value to do that when you're parsing something you expect to be written by a human, and thus a human has to puzzle out what they did wrong. Nobody expects that a JSON parser will be parsing human-written input, so there's little value to saying anything more than parse error. The reason this is a Gotcha rather than a bug is because the JSON standard specifies the behaviour (probably in order to be compatible with Javascript). Well, considering that the JS in JSON stands for JavaScript... Hence, although the behaviour is mind-numbingly stupid, it is deliberate and not a bug. Hence, a gotcha. But surely not a Python gotcha. If anything, it's a JSON gotcha. The same is true with PHP's JSON library, and Ruby's, and Perl's, and Scala's, and C++'s, and so on. It's a JSON issue, and a silly one to be complaining about at that. -- http://mail.python.org/mailman/listinfo/python-list
Re: Cannot connect to IMAP server in Python 3.2
* Steven D'Aprano steve+comp.lang.pyt...@pearwood.info in comp.lang.python: IMAP4_SSL is documented as existing in Python 3. And when I run Python 3.2 on a Centos machine, instead of Debian, it includes IMAP4_SSL which works fine. So there's something screwy going on here. Why does my Python 3.2 on Debian not include IMAP4_SSL, but Python 2.6 does? Could you try import ssl on your Debian machine and see if some errors are reported? Some ssl libs used by ssl.py might not be installed. -- DW -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Thu, 2012-04-05 at 12:00 +, Steven D'Aprano wrote: The reason this is a Gotcha rather than a bug is because the JSON standard specifies the behaviour (probably in order to be compatible with Javascript). It's not to be compatible with javascript (you can use either in javascript) I believe the choice is to make the parser as simple as possible. Agreed it's a gotcha, but json is almost always generated automatically. Tim -- http://mail.python.org/mailman/listinfo/python-list
Re: Cannot connect to IMAP server in Python 3.2
On Apr 5, 5:25 am, Steven D'Aprano steve +comp.lang.pyt...@pearwood.info wrote: On Thu, 05 Apr 2012 12:16:09 +, Steven D'Aprano wrote: On Thu, 05 Apr 2012 00:21:31 -0700, Steve Howell wrote: Why are you changing the invocation between versions of Python? Because imaplib.IMAP4_SSL apparently no longer exists in Python 3. server = imaplib.IMAP4_SSL('x') Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'module' object has no attribute 'IMAP4_SSL' Wait a minute... IMAP4_SSL is documented as existing in Python 3. And when I run Python 3.2 on a Centos machine, instead of Debian, it includes IMAP4_SSL which works fine. [steve@ando ~]$ python3.2 Python 3.2.2 (default, Mar 4 2012, 10:50:33) [GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2 Type help, copyright, credits or license for more information. py import imaplib py server = imaplib.IMAP4_SSL('x') py server imaplib.IMAP4_SSL object at 0xb7b8632c So there's something screwy going on here. Why does my Python 3.2 on Debian not include IMAP4_SSL, but Python 2.6 does? Looking at the source can give you some insight: http://hg.python.org/cpython/file/3.2/Lib/imaplib.py Look for where IMAP4_SSL is defined. On your 3.2/Debian setup, the HAVE_SSL flag (see two lines above the class statement) is apparently false: 1174 if HAVE_SSL: 1175 1176 class IMAP4_SSL(IMAP4): If you look for the first mention of HAVE_SSL, it becomes apparent that you have some issue with importing the ssl module, which unfortunately gets buried fairly silently by imaplib: 27 try: 28 import ssl 29 HAVE_SSL = True 30 except ImportError: 31 HAVE_SSL = False Damien, in his response, asks you to try import ssl on your Debian machine. I think he's on the right track in identifying the problem, based on the simple code above. Once you are able to import ssl, you should be able to use IMAP4_SSL, but that still doesn't entirely explain to me why you got a timeout error with plain IMAP4 and the proper port. (I would have expected a failure, but of a different kind.) I'd still be curious to see what happens when you try this: import socket, imaplib your_host_name = # ... socket.create_connection((your_host_name, imaplib.IMAP4_SSL_PORT)) -- http://mail.python.org/mailman/listinfo/python-list
python polygon
Hi, I found python polygon link in this page http://pypi.python.org/pypi/Polygon/1.17 was invalid now. http://polygon.origo.ethz.ch/download 404 - Project not found Ooops, the subdomain is not valid because the according project does not (yet) exist. Go to the Origo main page at http://origo.ethz.ch Can anyone provide some updates on this? Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: Python Gotcha's?
On 4/4/2012 7:32 PM, Chris Angelico wrote: Don't know if it's what's meant on that page by the += operator, Yes, it is. a=([1],) a[0].append(2) # This is fine [In the following, I use the term name rather loosely.] The append() method attempts to modify the object whose name is a[0]. That object is a LIST, so the attempt succeeds. a[0]+=[3] # This is not. The assignment attempts to modify the object whose name is a. That object is a TUPLE, so the attempt fails. This might be a surprise, but I'm not sure it deserves to be called a wart. Note the similarity to: temp = a[0] + [3] # succeeds a[0] = temp # fails -John -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Apr 5, 5:32 am, Roy Smith r...@panix.com wrote: [...] Nobody expects that a JSON parser will be parsing human-written input, [...] Humans write JSON all the time. People use JSON as a configuration language, and some people actually write JSON files by hand. A common example would be writing package.json for an npm package. Here are a couple examples: https://github.com/jashkenas/coffee-script/blob/master/package.json https://github.com/github/hubot/blob/master/package.json so there's little value to saying anything more than parse error. So, there's little value to say anything more than parse error...except to help all those dumb humans that expect JSON to be human-writable. ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Apr 5, 5:00 am, Steven D'Aprano steve +comp.lang.pyt...@pearwood.info wrote: On Thu, 05 Apr 2012 11:06:11 +, Duncan Booth wrote: Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: JSON expects double-quote marks, not single: v = json.loads({'test':'test'}) fails v = json.loads('{test:test}') succeeds You mean JSON expects a string with valid JSON? Quelle surprise. No. The surprise is that there exists a tool invented in the 21st century that makes a distinction between strings quoted with and those quoted with '. Being used to a sensible language like Python, it boggled my brain the first time I tried to write some JSON and naturally treated the choice of quote mark as arbitrary. I've been bitten by this gotcha too. Maybe boggled my brain would be a bit of hyperbole, but it did cause me minor pain, and brief but frustrating pain is the whole point of gotcha presentations. It especially boggled my brain when I saw the pathetically useless error message generated: [...] ValueError: Expecting property name: line 1 column 1 (char 1) Expecting property name??? WTF??? I agree with you that the error message is pretty puzzling. I can understand the rationale of the parser authors not to go overboard with diagnosing these errors correctly to users, since it would complicate the parser code and possibly slow it down even for well formed JSON. On the other hand, I think that parsers can distinguish themselves by anticipating the most common gotchas and giving clear messages. The reason this is a Gotcha rather than a bug is because the JSON standard specifies the behaviour (probably in order to be compatible with Javascript). Hence, although the behaviour is mind-numbingly stupid, it is deliberate and not a bug. Hence, a gotcha. Yep. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On 4/5/12 3:15 PM, John Posner wrote: On 4/4/2012 7:32 PM, Chris Angelico wrote: Don't know if it's what's meant on that page by the += operator, Yes, it is. a=([1],) a[0].append(2) # This is fine [In the following, I use the term name rather loosely.] The append() method attempts to modify the object whose name is a[0]. That object is a LIST, so the attempt succeeds. a[0]+=[3] # This is not. The assignment attempts to modify the object whose name is a. That object is a TUPLE, so the attempt fails. This might be a surprise, but I'm not sure it deserves to be called a wart. The wart is not that it fails, but that it does not fail atomically. The list inside the tuple gets modified even though an exception is raised for the statement as a whole. -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Difference between tempfile and spooled tempfile?
I do not understand why the spooled write gives an error. See below. The normal tempfile works just fine. They are supposed to behave equal? All insight you can provide is welcome. Alex van der Spek + 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 array import tempfile stf = tempfile.SpooledTemporaryFile(max_size=1024) ptf = tempfile.TemporaryFile() fff = [float(x) for x in range(2048)] ffa = array.array('f',fff) ptf.write(ffa) stf.write(ffa) Traceback (most recent call last): File pyshell#7, line 1, in module stf.write(ffa) File C:\Python27\lib\tempfile.py, line 595, in write rv = file.write(s) TypeError: must be string or read-only character buffer, not array.array -- http://mail.python.org/mailman/listinfo/python-list
Re: Difference between tempfile and spooled tempfile?
On Apr 5, 7:50 am, Alex van der Spek zd...@xs4all.nl wrote: I do not understand why the spooled write gives an error. See below. The normal tempfile works just fine. They are supposed to behave equal? All insight you can provide is welcome. Alex van der Spek + 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 array import tempfile stf = tempfile.SpooledTemporaryFile(max_size=1024) ptf = tempfile.TemporaryFile() fff = [float(x) for x in range(2048)] ffa = array.array('f',fff) ptf.write(ffa) stf.write(ffa) Traceback (most recent call last): File pyshell#7, line 1, in module stf.write(ffa) File C:\Python27\lib\tempfile.py, line 595, in write rv = file.write(s) TypeError: must be string or read-only character buffer, not array.array I think the docs are slightly misleading. While SpooledTemporaryFile allows you to write(), it's more finicky about serializing arrays, hence the error message. If you look under the hood, you'll see that it's mostly a limitation of StringIO. http://hg.python.org/cpython/file/2.7/Lib/tempfile.py 494 Temporary file wrapper, specialized to switch from 495 StringIO to a real file when it exceeds a certain size or 496 when a fileno is needed. 497 498 _rolled = False 499 500 def __init__(self, max_size=0, mode='w+b', bufsize=-1, 501 suffix=, prefix=template, dir=None): 502 self._file = _StringIO() 503 self._max_size = max_size 504 self._rolled = False 505 self._TemporaryFileArgs = (mode, bufsize, suffix, prefix, dir) (See line 502.) 600 def write(self, s): 601 file = self._file 602 rv = file.write(s) 603 self._check(file) 604 return rv (See line 602.) I'm looking at a slightly different version of the module than you, but hopefully you get the idea. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
A common one used to be expecting .sort() to return, rather than mutate (as it does). Same with .reverse() - sorted and reversed have this covered, not sure how common a gotcha it is any more. Iain On Wednesday, 4 April 2012 23:34:20 UTC+1, Miki Tebeka wrote: Greetings, I'm going to give a Python Gotcha's talk at work. If you have an interesting/common Gotcha (warts/dark corners ...) please share. (Note that I want over http://wiki.python.org/moin/PythonWarts already). Thanks, -- Miki -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Apr 5, 8:23 am, Iain King iaink...@gmail.com wrote: A common one used to be expecting .sort() to return, rather than mutate (as it does). Same with .reverse() - sorted and reversed have this covered, not sure how common a gotcha it is any more. The sort()/sorted() variations are good to cover. To give another example, folks who had been immersed in legacy versions of Python for a long time might still be in the habit of hand-writing compare functions. With newer versions of Python, it usually makes sense to just use the key feature. -- http://mail.python.org/mailman/listinfo/python-list
Re: Google Tech Talk: lisp at JPL
In article 6a4a234d-db48-4659-8714-098d79fb9...@l30g2000yqb.googlegroups.com, ccc31807 carte...@gmail.com wrote: On Apr 3, 1:53ハam, Xah Lee xah...@gmail.com wrote: 〈The Remote Agent Experiment: Debugging Code from 60 Million Miles Away〉 Google Tech Talk, (2012-02-14) Presented by Ron Garret. @http://www.youtube.com/watch?v=_gZK0tW8EhQ RG mentions giving a more technical version to a Lisp User Group. Any chance that this talk is publicly available? Nope. It wasn't recorded. Sorry. Thanks for the talk, Ron, I really enjoyed it, and wish you (and NASA) all the best. I haven't worked at NASA for nearly ten years now, but thanks for the kinds words nonetheless. rg -- http://mail.python.org/mailman/listinfo/python-list
Re: python polygon
On 05/04/2012 14:49, Kevin Zhang wrote: Hi, I found python polygon link in this page http://pypi.python.org/pypi/Polygon/1.17 was invalid now. http://polygon.origo.ethz.ch/download 404 - Project not found Ooops, the subdomain is not valid because the according project does not (yet) exist. Go to the Origo main page at http://origo.ethz.ch Can anyone provide some updates on this? Thanks, It's now http://pypi.python.org/pypi/Polygon/2.0.4 -- Cheers. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
In 7367295.815.1333578860181.JavaMail.geo-discussion-forums@ynpp8 Miki Tebeka miki.teb...@gmail.com writes: Greetings, I'm going to give a Python Gotcha's talk at work. If you have an interesting/common Gotcha (warts/dark corners ...) please share. This is fairly pedestrian as gotchas go, but it has bitten me: If you are working with data that is representable as either an integer or a string, choose one and stick to it. Treating it as both/either will eventually lead to grief. Or, in other words: 1 != '1' -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, The Gashlycrumb Tinies -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On 05.04.2012, Roy Smith r...@panix.com wroted: There's absolutely no reason why JSON should follow Python syntax rules. Making it support either kind of quotes would have complicated every JSON library in the world, for no added value. I think these days it's not just Python syntax, it's kinda something that you can get accustommed to take for granted. Realistically, how much more complication could the support for either quote marks introduce? I doubt anyone would even notice. And you don't have to write JSON by hand for this gotcha to bite you, all it takes is to start playing with generating JSON without the use of specialized JSON libraries/functions. For testing, for fun, out of curiosity... GS -- Grzegorz Staniak gstaniak _at_ gmail [dot] com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Thu, Apr 05, 2012 at 08:32:10AM -0400, Roy Smith wrote: One of the hardest things about writing parsers is generating helpful error messages when things don't parse. But, it's only of value to do that when you're parsing something you expect to be written by a human, and thus a human has to puzzle out what they did wrong. Nobody expects that a JSON parser will be parsing human-written input, so there's little value to saying anything more than parse error. Except for the human that has to debug why something automatically generated doesn't parse. That guy would probably appreciate a reasonable error message. (And indeed, as a sibling poster points out, people do write JSON by hand quite frequently.) \t -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Fri, Apr 6, 2012 at 2:25 AM, Grzegorz Staniak gstan...@gmail.com wrote: On 05.04.2012, Roy Smith r...@panix.com wroted: There's absolutely no reason why JSON should follow Python syntax rules. Making it support either kind of quotes would have complicated every JSON library in the world, for no added value. I think these days it's not just Python syntax, it's kinda something that you can get accustommed to take for granted. Realistically, how much more complication could the support for either quote marks introduce? I doubt anyone would even notice. And you don't have to write JSON by hand for this gotcha to bite you, all it takes is to start playing with generating JSON without the use of specialized JSON libraries/functions. For testing, for fun, out of curiosity... It all depends on the language. C and several C-derived languages distinguish between string constants and 'integer constants', where the latter are defined by character codepoint; PHP and bash have interpolated strings and 'non-interpolated strings'; Python and REXX have no difference between the two. All are legitimate design choices. Assuming that multiple languages/protocols have the same flexibility is dangerous, and I'm not surprised that JSON's strictness is biting people. Maybe the weird error message should be addressed as a bug, and then there won't be a problem :) ChrisA -- http://mail.python.org/mailman/listinfo/python-list
inheritance
Hello, I am new to python (or to any programming language). My first post on this list, so please go easy. Apologies if its a FAQ. Here is what I have #! /usr/bin/env python3 # -*- coding: utf-8 -*- class A(object): def __init__(self, a): print('a = ', a) self.a = a def foo(self): print('printing from foo in A = ',self.a) class B(A): def __init__(self, b, a): super(B, self).__init__(a) print('b = ', b) self.b = b def foo(self): print('printing from foo in B = ',self.b) class C(B): def __init__(self, c, b, a): super(C, self).__init__(b, a) print('c = ', c) self.c = c def foo(self): print('printing from foo in C = ',self.c) x = C(3,2,1) x.foo() three classes A,B,C and instance x. now how can I call methods foo in class A and B using 'x' instance. (I hope I could pronounce the terminology correct) Thanks. -- YYR -- http://mail.python.org/mailman/listinfo/python-list
Re: inheritance
On Fri, Apr 6, 2012 at 2:50 AM, yag yagn...@live.com wrote: Hello, I am new to python (or to any programming language). My first post on this list, so please go easy. Apologies if its a FAQ. Welcome! class A(object): def foo(self): print('printing from foo in A = ',self.a) class B(A): def foo(self): print('printing from foo in B = ',self.b) class C(B): def foo(self): print('printing from foo in C = ',self.c) In each case, you are overriding the foo() method, so your instance will only execute the last one. If you want to chain to the others, you need to write your methods to do so - which is what you've done with __init__. Hope that helps! Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: inheritance
On Thu, Apr 5, 2012 at 10:50 AM, yag yagn...@live.com wrote: three classes A,B,C and instance x. now how can I call methods foo in class A and B using 'x' instance. (I hope I could pronounce the terminology correct) Do you mean that you want C.foo to call B.foo, and B.foo to call A.foo? If that is the case, just use super(), as you already do with the __init__ method. Or do you want to skip C.foo and call A.foo or B.foo directly? In that case, just call it from the specific class you want. Since you are dispatching from the class instead of the instance, you will have to pass the instance in explicitly as the self argument. For example: B.foo(x) # calls B.foo directly with instance x Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
Miki Tebeka miki.teb...@gmail.com writes: [...] (Note that I want over http://wiki.python.org/moin/PythonWarts already). The local variable and scoping is, imho, something to be really careful about. Here is an example: class A(object): def __init__(self): self.x = 0 def r(self): return x # forgot self a = A() x = 1 print a.r() # prints 1 I know there is no remedy. It's just really tricky. -- Alain. -- http://mail.python.org/mailman/listinfo/python-list
Re: inheritance
Chris Angelico ros...@gmail.com writes: On Fri, Apr 6, 2012 at 2:50 AM, yag yagn...@live.com wrote: [snipped 19 lines] In each case, you are overriding the foo() method, so your instance will only execute the last one. If you want to chain to the others, you need to write your methods to do so - which is what you've done with __init__. Hope that helps! Yes it does. thank you a lot. -- YYR -- http://mail.python.org/mailman/listinfo/python-list
Re: inheritance
Hello Ian, Ian Kelly ian.g.ke...@gmail.com writes: On Thu, Apr 5, 2012 at 10:50 AM, yag yagn...@live.com wrote: three classes A,B,C and instance x. now how can I call methods foo in class A and B using 'x' instance. (I hope I could pronounce the terminology correct) Do you mean that you want C.foo to call B.foo, and B.foo to call A.foo? If that is the case, just use super(), as you already do with the __init__ method. Or do you want to skip C.foo and call A.foo or B.foo directly? yes! In that case, just call it from the specific class you want. Since you are dispatching from the class instead of the instance, I couldn't understand what you mean here, (may be because my poor knowledge with the terminology) you will have to pass the instance in explicitly as the self argument. For example: B.foo(x) # calls B.foo directly with instance x This is interesting, Now I kind of vaguely getting why we keep 'self' argument around in each method. Thanks you -- YYR -- http://mail.python.org/mailman/listinfo/python-list
Re: inheritance
Hello Ian, Yagnesh Raghava Yakkala yagn...@live.com writes: Hello Ian, Ian Kelly ian.g.ke...@gmail.com writes: [snipped 21 lines] you will have to pass the instance in explicitly as the self argument. For example: B.foo(x) # calls B.foo directly with instance x After follow up, I see one problem(can i say that?) with this. With python overwriting methods of super class(es), one need to keep track of all the methods ever defined in the super class(es). do everybody do a check before writing a new method for existing method with the same name.? -- YYR -- http://mail.python.org/mailman/listinfo/python-list
Re: inheritance
On Fri, Apr 6, 2012 at 3:50 AM, Yagnesh Raghava Yakkala yagn...@live.com wrote: After follow up, I see one problem(can i say that?) with this. With python overwriting methods of super class(es), one need to keep track of all the methods ever defined in the super class(es). do everybody do a check before writing a new method for existing method with the same name.? If you're subclassing something, you should generally work with the intention that an instance of your class will function viably in any situation in which an instance of the parent is wanted. So if you're writing a method of the same name as one in the parent, you should be performing the exact same task and with the same parameters (possibly having more parameters accepted, but default values set for them). That's part of what it means to subclass. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Difference between tempfile and spooled tempfile?
On Apr 5, 8:10 am, Steve Howell showel...@yahoo.com wrote: On Apr 5, 7:50 am, Alex van der Spek zd...@xs4all.nl wrote: I do not understand why the spooled write gives an error. See below. The normal tempfile works just fine. They are supposed to behave equal? All insight you can provide is welcome. Alex van der Spek + 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 array import tempfile stf = tempfile.SpooledTemporaryFile(max_size=1024) ptf = tempfile.TemporaryFile() fff = [float(x) for x in range(2048)] ffa = array.array('f',fff) ptf.write(ffa) stf.write(ffa) Traceback (most recent call last): File pyshell#7, line 1, in module stf.write(ffa) File C:\Python27\lib\tempfile.py, line 595, in write rv = file.write(s) TypeError: must be string or read-only character buffer, not array.array I think the docs are slightly misleading. While SpooledTemporaryFile allows you to write(), it's more finicky about serializing arrays, hence the error message. If you look under the hood, you'll see that it's mostly a limitation of StringIO. http://hg.python.org/cpython/file/2.7/Lib/tempfile.py 494 Temporary file wrapper, specialized to switch from 495 StringIO to a real file when it exceeds a certain size or 496 when a fileno is needed. 497 498 _rolled = False 499 500 def __init__(self, max_size=0, mode='w+b', bufsize=-1, 501 suffix=, prefix=template, dir=None): 502 self._file = _StringIO() 503 self._max_size = max_size 504 self._rolled = False 505 self._TemporaryFileArgs = (mode, bufsize, suffix, prefix, dir) (See line 502.) 600 def write(self, s): 601 file = self._file 602 rv = file.write(s) 603 self._check(file) 604 return rv (See line 602.) I'm looking at a slightly different version of the module than you, but hopefully you get the idea. P.S. The problems the OP is encountering may be a side effect of this bug: http://bugs.python.org/issue1730114 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
In article jlkh1c$msc$1...@mx1.internetia.pl, Grzegorz Staniak gstan...@gmail.com wrote: On 05.04.2012, Roy Smith r...@panix.com wroted: There's absolutely no reason why JSON should follow Python syntax rules. Making it support either kind of quotes would have complicated every JSON library in the world, for no added value. I think these days it's not just Python syntax, it's kinda something that you can get accustommed to take for granted. Realistically, how much more complication could the support for either quote marks introduce? I doubt anyone would even notice. And you don't have to write JSON by hand for this gotcha to bite you, all it takes is to start playing with generating JSON without the use of specialized JSON libraries/functions. For testing, for fun, out of curiosity... If you want to talk a protocol, read the protocol specs and follow them. Don't just look at a few examples, guess about the rules, and then act surprised when your guess turns out to be wrong. If you don't want to take the trouble to read and understand the protocol specs, use a library written by somebody who has already done the hard work for you. -- http://mail.python.org/mailman/listinfo/python-list
Re: inheritance
Hello Chris, Chris Angelico ros...@gmail.com writes: If you're subclassing something, you should generally work with the intention that an instance of your class will function viably in any situation in which an instance of the parent is wanted. So if you're writing a method of the same name as one in the parent, you should be performing the exact same task and with the same parameters (possibly having more parameters accepted, but default values set for them). That's part of what it means to subclass. Thanks for explaining. It makes sense. I see that python interpreter can instantly tell the list of defined methods in the super class(es). So keeping track thing is not at all a problem. Thanks a lot again. -- YYR -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
In article jlkg90$ghk$1...@reader1.panix.com, John Gordon gor...@panix.com wrote: In 7367295.815.1333578860181.JavaMail.geo-discussion-forums@ynpp8 Miki Tebeka miki.teb...@gmail.com writes: Greetings, I'm going to give a Python Gotcha's talk at work. If you have an interesting/common Gotcha (warts/dark corners ...) please share. This is fairly pedestrian as gotchas go, but it has bitten me: If you are working with data that is representable as either an integer or a string, choose one and stick to it. Treating it as both/either will eventually lead to grief. Or, in other words: 1 != '1' Tell that to the PHP crowd :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: inheritance
On Fri, Apr 6, 2012 at 4:09 AM, Yagnesh Raghava Yakkala yagn...@live.com wrote: Thanks for explaining. It makes sense. I see that python interpreter can instantly tell the list of defined methods in the super class(es). So keeping track thing is not at all a problem. Thanks a lot again. Most welcome! You can get a list of those methods in your own program using the dir() function. There's a whole lot of double-underscore (dunder) methods in there, but also all of your own. Tip: At the interactive interpreter prompt, type: help(dir) ChrisA -- http://mail.python.org/mailman/listinfo/python-list
[solved] Re: inheritance
Hello, With Chris and Ian help (Thank you both) I end up writing the example script like this,(just for the record) - #! /usr/bin/env python3 # -*- coding: utf-8 -*- class A(object): def __init__(self, a): print('a = ', a) self.a = a def foo(self): print('printing from foo in A = ',self.a) class B(A): def __init__(self, b, a): super(B, self).__init__(a) print('b = ', b) self.b = b def foo(self): print('printing from foo in B = ',self.b) def bar(self): print('printing from foo in B = ',self.b) class C(B): def __init__(self, c, b, a): super(C, self).__init__(b, a) print('c = ', c) self.c = c def foo(self): print('printing from foo in C = ',self.c) def baz(self): print('printing from foo in C = ',self.c) x = C(3,2,1) x.bar() x.baz() print() x.foo() B.foo(x) A.foo(x) # inheritance.py ends here - -- YYR -- http://mail.python.org/mailman/listinfo/python-list
Re: inheritance
On Thu, Apr 5, 2012 at 11:50 AM, Yagnesh Raghava Yakkala yagn...@live.com wrote: you will have to pass the instance in explicitly as the self argument. For example: B.foo(x) # calls B.foo directly with instance x After follow up, I see one problem(can i say that?) with this. With python overwriting methods of super class(es), one need to keep track of all the methods ever defined in the super class(es). do everybody do a check before writing a new method for existing method with the same name.? That syntax is for extraordinary cases where you know that you always want a specific version of the method from a specific class in the inheritance hierarchy to be called. Normally, you would just do x.foo() and allow the type of x to determine the exact method that is called. As long as you design your classes with encapsulation and the Liskov substitution principle in mind, it should not matter to you whether x.foo() results in calling B.foo or C.foo is called, because the end result will be the same, with any variations appropriate to the actual type of x. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Thu, 05 Apr 2012 08:32:10 -0400, Roy Smith wrote: In article 4f7d896f$0$29983$c3e8da3$54964...@news.astraweb.com, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: You mean JSON expects a string with valid JSON? Quelle surprise. No. The surprise is that there exists a tool invented in the 21st century that makes a distinction between strings quoted with and those quoted with '. Being used to a sensible language like Python, it boggled my brain the first time I tried to write some JSON and naturally treated the choice of quote mark as arbitrary. Your brain has a low boggle threshold. There's absolutely no reason why JSON should follow Python syntax rules. Except for the most important reason of all: Python's use of alternate string delimiters is an excellent design, one which Javascript itself follows. http://www.javascripter.net/faq/quotesin.htm I'm not the only one who has had trouble with JSON's poor design choice: http://stackoverflow.com/a/4612914 For a 21st century programming language or data format to accept only one type of quotation mark as string delimiter is rather like having a 21st century automobile with a hand crank to start the engine instead of an ignition. Even if there's a good reason for it (which I doubt), it's still surprising. Making it support either kind of quotes would have complicated every JSON library in the world, for no added value. Ooooh, such complication. I wish my software was that complicated. The added value includes: * semantic simplicity -- a string is a string, regardless of which quotes are used for delimiters; * reducing the number of escaped quotes needed; * compatibility with Javascript; * robustness. As it stands, JSON fails to live up to the Robustness principle and Postel's law: Be liberal in what you accept, and conservative in what you send. http://en.wikipedia.org/wiki/Robustness_principle Nobody should ever be hand-writing JSON So you say, but it is a fact that people do. And even if they don't hand- write it, people do *read* it, and allowing both quotation marks aids readability: \Help me Obiwan,\ she said, \You're my only hope!\ Blah. You can cut the number of escapes needed to one: 'Help me Obiwan, she said, You\'re my only hope!' (just like nobody should ever be hand-writing XML). Just use the supplied library calls and you'll never have to worry about low-level minutia like this again. It especially boggled my brain when I saw the pathetically useless error message generated: py json.loads({'test':'test'}) [...] ValueError: Expecting property name: line 1 column 1 (char 1) Expecting property name??? WTF??? One of the hardest things about writing parsers is generating helpful error messages when things don't parse. But, it's only of value to do that when you're parsing something you expect to be written by a human, Or when debugging a faulty or buggy generator, or when dealing with non- conforming or corrupted data. Essentially any time that you expect the error message will be read by a human being. Which is always. Error messages are for the human reader, always and without exception. If you don't expect it to be read by a person, why bother with a message? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Number of languages known [was Re: Python is readable] - somewhat OT
Re-trolling. On Wed, Apr 4, 2012 at 1:49 AM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: As part of my troll-outreach effort, I will indulge here. I was specifically thinking about some earlier claims that programming languages as they currently exist are somehow inherently superior to a formalized natural language in expressive power. I would argue that they are, but only for the very limited purpose for which they are written. With the possible exception of Inform 7, most programming languages are useless at describing (say) human interactions. I was thinking about this statement this morning. Compression is just the process of finding a more efficient encoding for information. I suppose you could say then that language developers could theoretically be trying to compress natural language representations of information. The problem then is that everyone is doing a horrible job, because they are approaching the subject in an ad hoc manner. There are multiple branches of mathematics and computer science that deal with this exact subject in a rigorous way. The trick is to find an encoding that has low space complexity, and for which the transformation to knowledge is efficient, for human beings. Lets assume that the input to be encoded are logical (proposition/predicate) statements. The first thing that came to mind when thinking this way is radix trees and directed acyclic word graphs (a form of DFA). These structures are fairly easy to work out on paper given a set of inputs, and it is fairly easy to reconstruct a set of inputs from the structure. Perhaps, we could use natural language statements, and some very minimal extended syntax to indicate a data structure (which fans out to a set of statements). As a quick example to see what I mean (mimicking some python syntax for similarity): in the context of chess: a color is either white or black the board: is a cartesian grid having dimension (8, 8) has squares, representing points on the grid a square: has a color contains a piece or is empty a piece: has a color is located in a square or has been captured a { king, queen, rook, bishop, knight, pawn } is a type of piece It should be clear that this is a directed acyclic phrase graph, and if you select a phrase fragment, then one phrase fragment from each child level until reaching a leaf, the concatenation of the phrase fragments forms a logical phrase. Note that the set braces are shorthand for multiple statements. This was really easy to write, and I bet even non programmers would have little or no trouble understanding what was going on. Additionally, I could make a full statement elsewhere, and if we have an algorithm to transform to a canonical phrase structure and merge synonyms, it could be inserted in the phrase graph, just as neatly as if I had written it there in the first place. The sexy thing about that, is that lets you take two sets of propositional statements, and perform set theoretic operations on them (union, complement, etc), and get a phrase graph structure out at the end which looks just like a nice neat little program. You could even get really crazy, if you could define equivalence relations (other than the natural relation) for the union (Set1.A ~ Set2.B) as that would let you compose the graphs in arbitrarily many ways. If you're dealing processes, you would also want to be able to specify temporal equivalence (Process1.T1 ~ Process2.T6). -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Fri, Apr 6, 2012 at 4:08 AM, Roy Smith r...@panix.com wrote: If you are working with data that is representable as either an integer or a string, choose one and stick to it. Treating it as both/either will eventually lead to grief. Or, in other words: 1 != '1' Tell that to the PHP crowd :-) I think this example highlights a major point about gotchas: the difference between an obvious language feature and a gotcha depends on where you come from. To a PHP programmer, 1 and 1 are in many ways indistinguishable. To a C programmer, they're utterly incompatible. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Thu, 05 Apr 2012 11:06:11 +, Duncan Booth wrote: Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: JSON expects double-quote marks, not single: v = json.loads({'test':'test'}) fails v = json.loads('{test:test}') succeeds You mean JSON expects a string with valid JSON? Quelle surprise. Actually, on further thought, and on reading the JSON RFC, I have decided that this is a design bug and not merely a gotcha. The relevant section of the RFC is this: 4. Parsers A JSON parser transforms a JSON text into another representation. A JSON parser MUST accept all texts that conform to the JSON grammar. A JSON parser MAY accept non-JSON forms or extensions. http://www.ietf.org/rfc/rfc4627.txt So a valid parser is permitted to accept data which is not strictly JSON. Given that both Javascript and Python (and I would argue, any sensible modern language) allows both single and double quotation marks as delimiters, the JSON parser should do the same. Failure to take advantage of that is a design flaw. Of course, the RFC goes on to say that a JSON generator MUST only generate text which conforms to the JSON grammar. So a conforming implementation would be perfectly entitled to accept, but not emit, single-quote delimited strings. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to disconnect from ldap?
In jkda88$mrk$1...@reader1.panix.com John Gordon gor...@panix.com writes: I'm writing an application that interacts with ldap, and I'm looking for advice on how to handle the connection. Specifically, how to close the ldap connection when the application is done. I wrote a class to wrap an LDAP connection, similar to this: import ldap import ConfigParser class MyLDAPWrapper(object): def __init__(self): config = ConfigParser.SafeConfigParser() config.read('sample.conf') uri = config.get('LDAP', 'uri') user = config.get('LDAP', 'user') password = config.get('LDAP', 'password') self.ldapClient = ldap.initialize(uri) self.ldapClient.simple_bind_s(user, password) My question is this: what is the best way to ensure the ldap connection gets closed when it should? I could write an explicit close() method, but that seems a bit messy; there would end up being lots of calls to close() scattered around in my code (primarily inside exception handlers.) Or I could write a __del__ method: def __del__(self): self.ldapClient.unbind_s() Thanks everyone for your input. I learned a lot! However, I just ran across this bit of documentation on python-ldap.org: class ldap.LDAPObject Instances of LDAPObject are returned by initialize() and open() (deprecated). The connection is automatically unbound and closed when the LDAP object is deleted. So, given that, do I need to do anything at all? -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, The Gashlycrumb Tinies -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: Python Gotcha's?
This is not a gotcha, and it's not surprising. As John described, you're assigning a new value to an index of a tuple, which tuples don't support. a[0] += [3] is the same as a[0] = a[0] + [3] which after evaluation is the same as a[0] = [1, 3] You can always modify an item that happens to be in a tuple if the item itself is mutable, but you cannot add, remove, or replace items in a tuple. Michael On Thu, Apr 5, 2012 at 10:15 AM, John Posner jjpos...@optimum.net wrote: On 4/4/2012 7:32 PM, Chris Angelico wrote: Don't know if it's what's meant on that page by the += operator, Yes, it is. a=([1],) a[0].append(2) # This is fine [In the following, I use the term name rather loosely.] The append() method attempts to modify the object whose name is a[0]. That object is a LIST, so the attempt succeeds. a[0]+=[3] # This is not. The assignment attempts to modify the object whose name is a. That object is a TUPLE, so the attempt fails. This might be a surprise, but I'm not sure it deserves to be called a wart. Note the similarity to: temp = a[0] + [3] # succeeds a[0] = temp # fails -John -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: Python Gotcha's?
On Fri, Apr 6, 2012 at 4:44 AM, Michael Hrivnak mhriv...@hrivnak.org wrote: This is not a gotcha, and it's not surprising. As John described, you're assigning a new value to an index of a tuple, which tuples don't support. a[0] += [3] is the same as a[0] = a[0] + [3] which after evaluation is the same as a[0] = [1, 3] You can always modify an item that happens to be in a tuple if the item itself is mutable, but you cannot add, remove, or replace items in a tuple. It does make sense, and I've never actually had problems with it myself. But it's come up on the list and clearly been a cause of confusion for people, so I thought it worth mentioning. And, as it turns out, it was the entry already on the list. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
I'm surprised nobody beat me to posting this: def foo(stuff=[]): ... stuff.append('bar') ... print stuff ... foo() ['bar'] foo() ['bar', 'bar'] foo() ['bar', 'bar', 'bar'] On Wed, Apr 4, 2012 at 6:34 PM, Miki Tebeka miki.teb...@gmail.com wrote: Greetings, I'm going to give a Python Gotcha's talk at work. If you have an interesting/common Gotcha (warts/dark corners ...) please share. (Note that I want over http://wiki.python.org/moin/PythonWarts already). Thanks, -- Miki -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to disconnect from ldap?
John Gordon wrote: class ldap.LDAPObject Instances of LDAPObject are returned by initialize() and open() (deprecated). The connection is automatically unbound and closed when the LDAP object is deleted. So, given that, do I need to do anything at all? Hmm, maybe the author of this statement (have to check who) did not know about the caveats with __del__() when this was written ages ago. IIRC first python-ldap release was for Python 1.4 back in '98. See use of dealloc() in Modules/LDAPObject.c. So I'd recommend to use the modern with-statement to make sure LDAPObject.unbind_s() is really called. Being old-fashioned I used try-finally-blocks until now. Ciao, Michael. -- http://mail.python.org/mailman/listinfo/python-list
Re: regexp partial matching, or hitEnd
On 4/5/2012 8:19 AM, Mark Lawrence wrote: More likely to go into the new regex module that's on pypi. Talking of which is this going into Python 3.3, I see it's mentioned in PEP398 but can't find any mention in the Python 3.3 What's New docs, or have I simply missed something? I think it has been approved in principle, but still needs some people to do something to actually make it happen. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: Python Gotcha's?
On 4/5/2012 13:24, Chris Angelico wrote: I think this example highlights a major point about gotchas: the difference between an obvious language feature and a gotcha depends on where you come from. To a PHP programmer, 1 and 1 are in many ways indistinguishable. To a C programmer, they're utterly incompatible. I think I agree with this. For instance, I'd consider the fact that this works in Python to be a gotcha: 1 abc True But that's because I like more strongly-typed systems. [I'm most decidedly not trying to start up that discussion again...] This is changed in Python 3: 1 abc Traceback (most recent call last): File stdin, line 1, in module TypeError: unorderable types: int() str() though you can still compare *some* types I consider logically unorderable: 0 True True I think it also has bearing on the ' vs issue. For instance, I totally think it's not at all surprising that one can be accepted and the other not, or that they behave differently. (Though I *do* find it surprising in the context of JSON given that JS apparently allows either.) Evan signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Wednesday, 4 April 2012 23:34:20 UTC+1, Miki Tebeka wrote: Greetings, I'm going to give a Python Gotcha's talk at work. If you have an interesting/common Gotcha (warts/dark corners ...) please share. (Note that I want over http://wiki.python.org/moin/PythonWarts already). Thanks, -- Miki One I've had to debug... text = 'abcdef' if text.find('abc'): print 'found it!' # Nothing prints as bool(0) is False if text.find('bob'): print 'found it!' found it! Someone new who hasn't read the docs might try this, but then I guess it's not really a gotcha if they haven't bothered doing that. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Thu, Apr 5, 2012 at 12:52 PM, Michael Hrivnak mhriv...@hrivnak.org wrote: I'm surprised nobody beat me to posting this: The OP beat you to it -- it's in the list at the wiki link. -- http://mail.python.org/mailman/listinfo/python-list
Generating custom Windows installers
Hello, I am working on creating an installer of a Python 3.2 application that we programmed. The end goal is to create an installer in which we can specify the install path, and create shortcuts in the Start Menu and Desktop. Ideally, we would like to give the users the option to create the Desktop or Start Menu shortcuts. I was able to create a .msi file with the setup.py and install.py files below. This allowed me to specify the custom default path but not create the shortcut in the Start Menu. Can anyone help me figure out what I'm missing? setup.py from cx_Freeze import setup, Executable import sys productName = ProductName if 'bdist_msi' in sys.argv: sys.argv += ['--initial-target-dir', 'C:\InstallDir\\' + productName] sys.argv += ['--install-script', 'install.py'] exe = Executable( script=main.py, base=Win32GUI, targetName=Product.exe ) setup( name=Product.exe, version=1.0, author=Me, description=Copyright 2012, executables=[exe], scripts=[ 'install.py' ] ) - install.py -- import os import sys import win32com.client as w32client shortcut_group_name = Start Menu Dir shortcut_name = Product Name shortcut_target = http://www.microsoft.com; sh = w32client.Dispatch(WScript.Shell) p = sh.SpecialFolders(AllUsersPrograms) assert(os.path.isdir(p)) p = os.path.join(p, shortcut_group_name) if (not os.path.isdir(p)): os.makedirs(p) lnk = sh.CreateShortcut(os.path.join(p, shortcut_name + .lnk)) lnk.TargetPath = shortcut_target lnk.Save() -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On 4/5/2012 11:10 AM Jon Clements said... On Wednesday, 4 April 2012 23:34:20 UTC+1, Miki Tebeka wrote: Greetings, I'm going to give a Python Gotcha's talk at work. If you have an interesting/common Gotcha (warts/dark corners ...) please share. (Note that I want over http://wiki.python.org/moin/PythonWarts already). Thanks, -- Miki One I've had to debug... text = 'abcdef' if text.find('abc'): print 'found it!' # Nothing prints as bool(0) is False if text.find('bob'): print 'found it!' found it! Someone new who hasn't read the docs might try this, but then I guess it's not really a gotcha if they haven't bothered doing that. Kind of begs for a contains method that returns the appropriate boolean: if text.contains('bob') Emile -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On 5 April 2012 21:06, Emile van Sebille em...@fenx.com wrote: Kind of begs for a contains method that returns the appropriate boolean: if text.contains('bob') It's already there: text.__contains__('bob') It's usually spelt otherwise though: 'bob' in text -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Thu, Apr 5, 2012 at 2:06 PM, Emile van Sebille em...@fenx.com wrote: On 4/5/2012 11:10 AM Jon Clements said... On Wednesday, 4 April 2012 23:34:20 UTC+1, Miki Tebeka wrote: Greetings, I'm going to give a Python Gotcha's talk at work. If you have an interesting/common Gotcha (warts/dark corners ...) please share. (Note that I want over http://wiki.python.org/moin/PythonWarts already). Thanks, -- Miki One I've had to debug... text = 'abcdef' if text.find('abc'): print 'found it!' # Nothing prints as bool(0) is False if text.find('bob'): print 'found it!' found it! Someone new who hasn't read the docs might try this, but then I guess it's not really a gotcha if they haven't bothered doing that. Kind of begs for a contains method that returns the appropriate boolean: if text.contains('bob') You mean like this? if 'bob' in text: print 'found it!' Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On 05.04.2012, Roy Smith r...@panix.com wroted: There's absolutely no reason why JSON should follow Python syntax rules. Making it support either kind of quotes would have complicated every JSON library in the world, for no added value. I think these days it's not just Python syntax, it's kinda something that you can get accustommed to take for granted. Realistically, how much more complication could the support for either quote marks introduce? I doubt anyone would even notice. And you don't have to write JSON by hand for this gotcha to bite you, all it takes is to start playing with generating JSON without the use of specialized JSON libraries/functions. For testing, for fun, out of curiosity... If you want to talk a protocol, read the protocol specs and follow them. Sure, sure. But it still may raise a few eyebrows as people start to play along while still reading the spces. It's just not something that I'd expect (yes, I learnt Perl before I discovered Python). GS -- Grzegorz Staniak gstaniak _at_ gmail [dot] com -- http://mail.python.org/mailman/listinfo/python-list
produce the same output as Unix's date command
Hi, Unix's date command produces this output (example): Thu Apr 5 22:49:42 CEST 2012 I would like to produce the same output with Python, without calling date externally. Before doing it I'd like to ask the list if anyone has an existing solution for this. Thanks, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
* Steven D'Aprano wrote: For a 21st century programming language or data format to accept only one type of quotation mark as string delimiter is rather like having a 21st century automobile with a hand crank to start the engine instead of an ignition. Even if there's a good reason for it (which I doubt), it's still surprising. Here's a reason: KISS. Actually I've never understood the reason for multiple equivalent quote characters. There are languages where these are not equivalent, like perl, C or shell script. There it makes way more sense. (If a parser doesn't accept foreign syntax, that's reasonable enough for me, too.) nd -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
In article 4f7de152$0$29983$c3e8da3$54964...@news.astraweb.com, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: I'm not the only one who has had trouble with JSON's poor design choice: This is getting a bit off-topic. If you wish to argue that JSON is designed poorly, you should do that in some appropriate JSON forum. It's not a Python issue. Now, if you wish to boggle your mind about something pythonic, how about mutexes not being thread safe (http://bugs.python.org/issue1746071)? -- http://mail.python.org/mailman/listinfo/python-list
Re: produce the same output as Unix's date command
On Thu, Apr 5, 2012 at 1:52 PM, Jabba Laci jabba.l...@gmail.com wrote: Hi, Unix's date command produces this output (example): Thu Apr 5 22:49:42 CEST 2012 I would like to produce the same output with Python, without calling date externally. Before doing it I'd like to ask the list if anyone has an existing solution for this. From POSIX (http://pubs.opengroup.org/onlinepubs/009695399/utilities/date.html ): When no formatting operand is specified, the output in the POSIX locale shall be equivalent to specifying: date +%a %b %e %H:%M:%S %Z %Y Therefore: from time import strftime print strftime(%a %b %e %H:%M:%S %Z %Y) But note that `date` is locale-sensitive; imitating that would be a bit more complicated. Cheers, Chris -- http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: Re: Python Gotcha's?
On 4/5/2012 13:44, Michael Hrivnak wrote: This is not a gotcha, and it's not surprising. As John described, you're assigning a new value to an index of a tuple, which tuples don't support. Um, at least for me personally, yes, it is surprising, and yes, it is a gotcha. This goes back to what languages you're used to. I come from a strong C++ background. In C++, something like mytuple[0] += [3] would wind up calling 'operator+=' on the list, that += would mutate the list, and then the expression would be done. The C++ approach doesn't really work with Python because more stuff is immutable, and Python's behavior is arguably the least-bad solution, but it WAS definitely surprising for me (and others!) when I learned about Python's behavior. In particular, the translation of 'a+=b' to 'temp = a + b; a = temp' is *not* a very natural one to me. Evan Michael On Thu, Apr 5, 2012 at 10:15 AM, John Posner jjpos...@optimum.net wrote: On 4/4/2012 7:32 PM, Chris Angelico wrote: Don't know if it's what's meant on that page by the +=perator, Yes, it is. a=1],) a[0].append(2) # This is fine [In the following, I use the term name rather loosely.] The append() method attempts to modify the object whose name is a[0]. That object is a LIST, so the attempt succeeds. a[0]+=] # This is not. The assignment attempts to modify the object whose name is a. That object is a TUPLE, so the attempt fails. This might be a surprise, but I'm not sure it deserves to be called a wart. Note the similarity to: temp =[0] + [3] # succeeds a[0] =emp # fails -John -- http://mail.python.org/mailman/listinfo/python-list signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On 4/5/2012 17:11, Evan Driscoll wrote: In particular, the translation of 'a+=b' to 'temp = a + b; a = temp' is *not* a very natural one to me. To expand on this point slightly, because of common C++ idioms guided by efficiency, I would be much more likely to think of 'a + b' as 'temp = a, temp += b, temp' than the Python way: in other words, to the extent that I think of += and + being implemented in terms of each other, I think of + as being implemented via +=. Evan signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: produce the same output as Unix's date command
Original Message Subject: Re: produce the same output as Unix's date command Date: Thu, 05 Apr 2012 22:07:42 +0100 From: Mark Lawrence breamore...@yahoo.co.uk Newsgroups: gmane.comp.python.general References: caoujsmm5vjwzf9a9mkjuz1zhpff57dpzzaop8ribg9qrb4n...@mail.gmail.com On 05/04/2012 21:52, Jabba Laci wrote: Hi, Unix's date command produces this output (example): Thu Apr 5 22:49:42 CEST 2012 I would like to produce the same output with Python, without calling date externally. Before doing it I'd like to ask the list if anyone has an existing solution for this. Thanks, Laszlo See http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior. -- Cheers. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Fri, Apr 6, 2012 at 4:10 AM, Jon Clements jon...@googlemail.com wrote: One I've had to debug... text = 'abcdef' if text.find('abc'): print 'found it!' # Nothing prints as bool(0) is False if text.find('bob'): print 'found it!' found it! Someone new who hasn't read the docs might try this, but then I guess it's not really a gotcha if they haven't bothered doing that. But your original will actually never work, since find() returns -1 if not found. This one is far more a gotcha in PHP, where the equivalent function returns boolean False if not found, or index (starting from 0) if found. Returning -1 on not-found is far more logical. (Plus, of course, the 'substring in string' syntax exists for just testing.) ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
Now, if you wish to boggle your mind about something pythonic, how about mutexes not being thread safe (http://bugs.python.org/issue1746071)? This is and old and deprecated module, you should not use it. Use http://docs.python.org/library/threading.html#threading.Lock and friends instead. IMO the bug should be to remove this module and it's documentation :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On 05Apr2012 19:13, Alain Ketterlin al...@dpt-info.u-strasbg.fr wrote: | Miki Tebeka miki.teb...@gmail.com writes: | (Note that I want over http://wiki.python.org/moin/PythonWarts already). | | The local variable and scoping is, imho, something to be really | careful about. Here is an example: | | class A(object): | def __init__(self): | self.x = 0 | def r(self): | return x # forgot self | | a = A() | x = 1 | print a.r() # prints 1 | | I know there is no remedy. It's just really tricky. Whoa! I presume this jost happens with globals and not with one function calling another... (I guess I should test that instead of asking such a dumb question). -- Cameron Simpson c...@zip.com.au DoD#743 http://www.cskk.ezoshosting.com/cs/ You see, wire telegraph is a kind of a very, very long cat. You pull his tail in New York and his head is meowing in Los Angeles. Do you understand this? And radio operates exactly the same way: you send signals here, they receive them there. The only difference is that there is no cat. - Albert Einstein, when asked to describe radio -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On 05Apr2012 23:08, André Malo ndpar...@gmail.com wrote: | * Steven D'Aprano wrote: | | For a 21st century programming language or data format to accept only one | type of quotation mark as string delimiter is rather like having a 21st | century automobile with a hand crank to start the engine instead of an | ignition. Even if there's a good reason for it (which I doubt), it's | still surprising. | | Here's a reason: KISS. Actually I've never understood the reason for | multiple equivalent quote characters. There are languages where these are | not equivalent, like perl, C or shell script. There it makes way more | sense. I agree, except that even where the quotes are equivalent there is an advantage: writing a string containing quotes: 'Hello, he said.' It's funny weather. Of course this doesn't scale much if you need both, but it covers a common use. Personally I'm ok with JSON accepting only one kind of quote. And I _have_ been bitten by it and surprised in the past. -- Cameron Simpson c...@zip.com.au DoD#743 http://www.cskk.ezoshosting.com/cs/ This telephone has too many shortcomings to be seriously considered as a means of communication. The device is inherently of no value to us. - Western Union memo, 1877 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Thu, 05 Apr 2012 23:08:11 +0200, André Malo wrote: * Steven D'Aprano wrote: For a 21st century programming language or data format to accept only one type of quotation mark as string delimiter is rather like having a 21st century automobile with a hand crank to start the engine instead of an ignition. Even if there's a good reason for it (which I doubt), it's still surprising. Here's a reason: KISS. KISS is a reason *for* allowing multiple string delimiters, not against it. The simplicity which matters here are: * the user doesn't need to memorise which delimiter is allowed, and which is forbidden, which will be different from probably 50% of the other languages he knows; * the user can avoid the plague of escaping quotes inside strings whenever he needs to embed the delimiter inside a string literal. This is the 21st century, not 1960, and if the language designer is worried about the trivially small extra effort of parsing ' as well as then he's almost certainly putting his efforts in the wrong place. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
String delimiter policy (was Re: Python Gotcha's?)
On Fri, Apr 6, 2012 at 11:03 AM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: KISS is a reason *for* allowing multiple string delimiters, not against it. The simplicity which matters here are: * the user doesn't need to memorise which delimiter is allowed, and which is forbidden, which will be different from probably 50% of the other languages he knows; * the user can avoid the plague of escaping quotes inside strings whenever he needs to embed the delimiter inside a string literal. This is the 21st century, not 1960, and if the language designer is worried about the trivially small extra effort of parsing ' as well as then he's almost certainly putting his efforts in the wrong place. KISS and the Python principle of having one obvious way to do things say that it's illogical to have utterly different ways to accomplish the same thing, UNLESS they are justified. Allowing multiple string delimiters makes it easier to hand-craft JSON; it makes it marginally harder to parse JSON; and it makes it significantly harder to output optimal code - you have to make a judgment call on which delimiter to use, instead of just outputting a string according to the obvious rules. Of course, you could always ignore one of the options and use the other, but then somebody's going to file a bug saying When my strings contain double quotes, some-encoder-library escapes them instead of using single quotes for delimiters. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Apr 5, 6:03 pm, Steven D'Aprano steve +comp.lang.pyt...@pearwood.info wrote: On Thu, 05 Apr 2012 23:08:11 +0200, André Malo wrote: * Steven D'Aprano wrote: For a 21st century programming language or data format to accept only one type of quotation mark as string delimiter is rather like having a 21st century automobile with a hand crank to start the engine instead of an ignition. Even if there's a good reason for it (which I doubt), it's still surprising. Here's a reason: KISS. KISS is a reason *for* allowing multiple string delimiters, not against it. The simplicity which matters here are: * the user doesn't need to memorise which delimiter is allowed, and which is forbidden, which will be different from probably 50% of the other languages he knows; Exactly. One of the reasons that human use computers in the first place is that we have flawed memory with respect to details, especially arbitrary ones. It's the job of the computer to make our lives easier. * the user can avoid the plague of escaping quotes inside strings whenever he needs to embed the delimiter inside a string literal. Unlike JSON, JS itself allows '' and ', although its canonical representation of the latter is '\''. Having said that, I don't mind that JSON is strict; I just hate that certain JSON parsers give cryptic messages on such an obvious gotcha. This is the 21st century, not 1960, and if the language designer is worried about the trivially small extra effort of parsing ' as well as then he's almost certainly putting his efforts in the wrong place. FWIW the JSON parser in Javascript is at least capable of giving a precise explanation in its error message, which put it ahead of Python: config = {'foo': 'bar'} {'foo': 'bar'} JSON.parse(config) SyntaxError: Unexpected token ' (Tested under Chrome and node.js, both based on V8.) Here's Python: config = {'foo': 'bar'} import json json.loads(config) [...] ValueError: Expecting property name: line 1 column 1 (char 1) (Python's implementation at least beats JS by including line/column info.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On 04/05/2012 08:02 PM, Cameron Simpson wrote: On 05Apr2012 19:13, Alain Ketterlin al...@dpt-info.u-strasbg.fr wrote: | Miki Tebeka miki.teb...@gmail.com writes: | (Note that I want over http://wiki.python.org/moin/PythonWarts already). | | The local variable and scoping is, imho, something to be really | careful about. Here is an example: | | class A(object): | def __init__(self): | self.x = 0 | def r(self): | return x # forgot self | | a = A() | x = 1 | print a.r() # prints 1 | | I know there is no remedy. It's just really tricky. Whoa! I presume this jost happens with globals and not with one function calling another... (I guess I should test that instead of asking such a dumb question). It doesn't generally happen with one function calling another. What it does apply to is to variables of nested scope. If the function doesn't have a defining line for x, then the runtime looks one level out. in this case, that's to globals. But in more complex programs, for example with nested functions, it might be to other places. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On 4/5/2012 7:36 PM, Miki Tebeka wrote: Now, if you wish to boggle your mind about something pythonic, how about mutexes not being thread safe (http://bugs.python.org/issue1746071)? This is and old and deprecated module, you should not use it. Use http://docs.python.org/library/threading.html#threading.Lock and friends instead. IMO the bug should be to remove this module and it's documentation :) import mutex Traceback (most recent call last): File pyshell#0, line 1, in module import mutex ImportError: No module named 'mutex' It was closed as won't fix because On 2008/2/23, Guido van Rossum said in python-dev According to the docstring it's only meant to be used with sched.py. Please don't try to make it work with threads! Anyway, this module will be removed, or at least its API hidden, in 3.0. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On 06 Apr 2012 01:03:45 GMT Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: This is the 21st century, not 1960 ... Now there's a slippery slope, indeed. ;-) ... and if the language designer is worried about the trivially small extra effort of parsing ' as well as then he's almost certainly putting his efforts in the wrong place. What about “ and ”, or ‘ and ’, or « and »? Any unicode-aware parser should be able to determine that the next input character is punctuation, open or punctuation, initial (and doesn't already mean something else in the language) and then scan for the a corresponding punctuation, close or punctuation, final character. Dan -- http://mail.python.org/mailman/listinfo/python-list
escaping/encoding/formatting in python
One of the biggest nuisances for programmers, just beneath date/time APIs in the pantheon of annoyances, is that we are constantly dealing with escaping/encoding/formatting issues. I wrote this little program as a cheat sheet for myself and others. Hope it helps. # escaping quotes legal_string = ['', ', '\, '\'', ' ] for s in legal_string: print([ + s + ]) # formatting print 'Hello %s' % 'world' print Hello %s % 'world' planet = 'world' print Hello {planet}.format(**locals()) print Hello {planet}.format(planet=planet) print Hello {0}.format(planet) # Unicode s = u\u0394 print s # prints a triangle print repr(s) == u'\u0394' # True print s.encode(utf-8) == \xce\x94 # True # other examples/resources??? # Web encodings import urllib s = ~foo ~bar print urllib.quote_plus(s) == '%7Efoo+%7Ebar' # True print urllib.unquote_plus(urllib.quote_plus(s)) == s # True import cgi s = x 4 x 5 print cgi.escape(s) == 'x lt; 4 amp; x gt; 5' # True # JSON import json h = {'foo': 'bar'} print json.dumps(h) == '{foo: bar}' # True try: bad_json = {'foo': 'bar'} json.loads(bad_json) except: print 'Must use double quotes in your JSON' It's tested under Python3.2. I didn't dare to cover regexes. It would be great if somebody could flesh out the Unicode examples or remind me (and others) of other common APIs that are useful to have in your bag of tricks. -- http://mail.python.org/mailman/listinfo/python-list
[ANN]: asyncoro: Framework for asynchronous sockets and coroutines
asyncoro is a framework for developing concurrent programs with asynchronous event completions and coroutines. Asynchronous completions currently implemented in asyncoro are socket I/O operations, sleep timers, (conditional) event notification and semaphores. Programs developed with asyncoro will have same logic as Python programs with synchronous sockets and threads, except for a few syntactic changes. asyncoro supports polling mechanisms epoll, kqueue, /dev/poll (and poll, select if necessary), and Windows I/O Completion Ports (IOCP) for high performance and scalability, and SSL for security. More details about asyncoro are at http://dispy.sourceforge.net/asyncoro.html. It can be downloaded from https://sourceforge.net/projects/dispy/files. asyncoro is used in development of dispy (http://dispy.sourceforge.net), which is a framework for parallel execution of computations by distributing them across multiple processors on a single machine (SMP), multiple nodes in a cluster, or large clusters of nodes. The computations can be standalone programs or Python functions. Both asyncoro and dispy have been tested with Python versions 2.7 and 3.2 under Linux, OS X and Windows. Cheers, Giri-- http://mail.python.org/mailman/listinfo/python-list
Re: Generating custom Windows installers
Seeing you are relying on win32com, you might as well add the links directly rather than via the intermediate WScript.shell object. Look in win32comext\shell\demos\create_link.py for an example of how to create shortcuts directly. HTH, Mark On 6/04/2012 5:23 AM, cesar.covarrub...@gmail.com wrote: Hello, I am working on creating an installer of a Python 3.2 application that we programmed. The end goal is to create an installer in which we can specify the install path, and create shortcuts in the Start Menu and Desktop. Ideally, we would like to give the users the option to create the Desktop or Start Menu shortcuts. I was able to create a .msi file with the setup.py and install.py files below. This allowed me to specify the custom default path but not create the shortcut in the Start Menu. Can anyone help me figure out what I'm missing? setup.py from cx_Freeze import setup, Executable import sys productName = ProductName if 'bdist_msi' in sys.argv: sys.argv += ['--initial-target-dir', 'C:\InstallDir\\' + productName] sys.argv += ['--install-script', 'install.py'] exe = Executable( script=main.py, base=Win32GUI, targetName=Product.exe ) setup( name=Product.exe, version=1.0, author=Me, description=Copyright 2012, executables=[exe], scripts=[ 'install.py' ] ) - install.py -- import os import sys import win32com.client as w32client shortcut_group_name = Start Menu Dir shortcut_name = Product Name shortcut_target = http://www.microsoft.com; sh = w32client.Dispatch(WScript.Shell) p = sh.SpecialFolders(AllUsersPrograms) assert(os.path.isdir(p)) p = os.path.join(p, shortcut_group_name) if (not os.path.isdir(p)): os.makedirs(p) lnk = sh.CreateShortcut(os.path.join(p, shortcut_name + .lnk)) lnk.TargetPath = shortcut_target lnk.Save() -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Thu, 05 Apr 2012 10:15:03 -0400 John Posner jjpos...@optimum.net wrote: On 4/4/2012 7:32 PM, Chris Angelico wrote: Don't know if it's what's meant on that page by the += operator, Yes, it is. a=([1],) a[0].append(2) # This is fine [In the following, I use the term name rather loosely.] The append() method attempts to modify the object whose name is a[0]. That object is a LIST, so the attempt succeeds. a[0]+=[3] # This is not. The assignment attempts to modify the object whose name is a. That object is a TUPLE, so the attempt fails. This might be a surprise, but I'm not sure it deserves to be called a wart. There was a thread called copy on write several weeks ago which veered into a discussion of this: http://mail.python.org/pipermail/python-list/2012-January/1286466.html While I follow the reason for the exception noted above, to me this is a gotcha, and has at least two wart-like features: 1) The mutation clearly intended by a[0] += [3] succeeds, even though an exception is raised. What fails is the subsequent assignment, which makes no difference in this case. I wouldn't blame anyone for being surprised to find that a[0] is now [1, 2, 3] despite the exception. 2) Whether the operation succeeds depends on what name we use to refer to the object: a = ([],) b = a[0] b is a[0] True b += [1] a ([1],) a[0] += [2] Traceback (most recent call last): File stdin, line 1, in module TypeError: 'tuple' object does not support item assignment a ([1, 2],) b is a[0] True Very surprising to me, despite knowing why it happens. I used to believe that how an object is referred to had no effect on its behaviour as an operand. In the abovementioned thread, Hrvoje Niksic posted an implementation approach which avoided all this by simply not perform[ing] the final assignment if the in-place method is available on the contained object: http://mail.python.org/pipermail/python-list/2012-February/1287400.html However, I get the impression this issue is generally regarded as least worst, won't fix. Regards, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Apr 5, 4:06 pm, Duncan Booth duncan.bo...@invalid.invalid wrote: Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: JSON expects double-quote marks, not single: v = json.loads({'test':'test'}) fails v = json.loads('{test:test}') succeeds You mean JSON expects a string with valid JSON? Quelle surprise. Are there languages (other than python) in which single and double quotes are equivalent? [No I dont claim to know all the languages out there, just that I dont know any other language which allows single and double quotes to be interconvertible like python does] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Fri, Apr 6, 2012 at 2:28 PM, rusi rustompm...@gmail.com wrote: Are there languages (other than python) in which single and double quotes are equivalent? [No I dont claim to know all the languages out there, just that I dont know any other language which allows single and double quotes to be interconvertible like python does] REXX and JavaScript. And probably others. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Apr 5, 9:28 pm, rusi rustompm...@gmail.com wrote: On Apr 5, 4:06 pm, Duncan Booth duncan.bo...@invalid.invalid wrote: Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: JSON expects double-quote marks, not single: v = json.loads({'test':'test'}) fails v = json.loads('{test:test}') succeeds You mean JSON expects a string with valid JSON? Quelle surprise. Are there languages (other than python) in which single and double quotes are equivalent? [No I dont claim to know all the languages out there, just that I dont know any other language which allows single and double quotes to be interconvertible like python does] Python doesn't treat single quotes and double quotes in *exactly* the same manner, because the choice of outer quotes affects whether you need to escape the outer quote characters inside the string. But I don't want to be overly literal--I think I know what you mean by equivalent here. JS, YAML, and HTML are pretty similar to Python with respect to single vs. double, as far as I know/remember/care. Perl, Ruby, and CoffeeScript have the tradition that single quotes are interpreted literally, whereas double quotes allow for interpolation of things within the string. This is roughly inspired by English, where one says things like Double quotes are an 'enclosing syntax' for single quotes. [Yes, I'm just making that up. Sounds plausible, right?] Both Ruby and CoffeeScript support triple quote syntax similar to Python. C uses double quotes for strings, as opposed to single quotes for characters. Java only allows double quotes for strings. I'll wager a guess that if you took any two programming languages (including declarative languages like SQL/HTML) and compared how they represented string literals, there would be at least one thing different between them, and that difference would be a fairly arbitrary design decision. There are probably exceptions, but languages that have the exact same quoting rules would probably be close dialects of each other in other respects beyond quoting. I'll also wager a guess that at least one thing I said above was wrong, and that's a testament to the arcane nature of representing string literals (as well as my own lack of mental capacity for juggling all these different rules in my brain). And that's just in ASCII with an American English bias. Throw in Unicode--that's when things get really confusing! I'm happy to stand corrected on any fact above. Withhold insults, though. I already know that string literal syntax makes me feel stupid--no need to rub it in. -- http://mail.python.org/mailman/listinfo/python-list
Re: escaping/encoding/formatting in python
On Apr 6, 6:56 am, Steve Howell showel...@yahoo.com wrote: One of the biggest nuisances for programmers, just beneath date/time APIs in the pantheon of annoyances, is that we are constantly dealing with escaping/encoding/formatting issues. [OT for this list] If you run $ find /usr/share/emacs/23.3/lisp/ -name '*.gz'|xargs zgrep '\\ \\' you can get quite a few results. [Suitable assumptions: linux box with emacs installed] -- http://mail.python.org/mailman/listinfo/python-list
Re: escaping/encoding/formatting in python
On Apr 5, 9:59 pm, rusi rustompm...@gmail.com wrote: On Apr 6, 6:56 am, Steve Howell showel...@yahoo.com wrote: One of the biggest nuisances for programmers, just beneath date/time APIs in the pantheon of annoyances, is that we are constantly dealing with escaping/encoding/formatting issues. [OT for this list] If you run $ find /usr/share/emacs/23.3/lisp/ -name '*.gz'|xargs zgrep '\\ \\' you can get quite a few results. [Suitable assumptions: linux box with emacs installed] You've one-upped me with 2-to-the-N backspace escaping. I've written useful scripts before with (scripts that went through three levels of interpretation), but four is setting a new bar. My use of three backslashes back in the day was like Beamon's jump in the Mexico City Olympics. An amazing feat for its time, but every record eventually gets broken. Well done. -- http://mail.python.org/mailman/listinfo/python-list
Re: escaping/encoding/formatting in python
On Apr 5, 9:59 pm, rusi rustompm...@gmail.com wrote: On Apr 6, 6:56 am, Steve Howell showel...@yahoo.com wrote: One of the biggest nuisances for programmers, just beneath date/time APIs in the pantheon of annoyances, is that we are constantly dealing with escaping/encoding/formatting issues. [OT for this list] If you run $ find /usr/share/emacs/23.3/lisp/ -name '*.gz'|xargs zgrep '\\ \\' you can get quite a few results. [Suitable assumptions: linux box with emacs installed] You've one-upped me with 2-to-the-N backslash escaping. I've written useful scripts before with (scripts that went through three levels of interpretation), but four is setting a new bar. My use of three exponentially increasing levels of backslashes back in the day was like Beamon's jump in the Mexico City Olympics. An amazing feat for its time, but every record eventually gets broken. Well done. -- http://mail.python.org/mailman/listinfo/python-list
Re: escaping/encoding/formatting in python
On Apr 6, 10:13 am, Steve Howell showel...@yahoo.com wrote: On Apr 5, 9:59 pm, rusi rustompm...@gmail.com wrote: On Apr 6, 6:56 am, Steve Howell showel...@yahoo.com wrote: One of the biggest nuisances for programmers, just beneath date/time APIs in the pantheon of annoyances, is that we are constantly dealing with escaping/encoding/formatting issues. [OT for this list] If you run $ find /usr/share/emacs/23.3/lisp/ -name '*.gz'|xargs zgrep '\\ \\' you can get quite a few results. [Suitable assumptions: linux box with emacs installed] You've one-upped me with 2-to-the-N backslash escaping. I've written useful scripts before with (scripts that went through three levels of interpretation), but four is setting a new bar. My use of three exponentially increasing levels of backslashes back in the day was like Beamon's jump in the Mexico City Olympics. An amazing feat for its time, but every record eventually gets broken. Well done. There was a competition here?! If so I can break my own record -- double the number of backslashes and you still get hits. Its just that I was unsure of my ability at typing 32 backslashes (and making a reasonable post). On a more serious note this indicates that it is (may be?) a bad idea for old-fashioned languages (like elisp and C) to have only 1 string- quoter. May-be-question-mark because programming language experience tells us that avoiding recursion (in its infinite guises) by special-casing is usually a bad idea. All this mess would vanish if the string-literal-starter and ender were different. [You dont need to escape a open-paren in a lisp sexp] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
On Apr 6, 9:54 am, Steve Howell showel...@yahoo.com wrote: JS, YAML, and HTML are pretty similar to Python with respect to single vs. double, as far as I know/remember/care. [Complete ignoramus here -- writing after a few minutes of googling] YAML: http://yaml.org/spec/current.html#single%20quoted%20style/syntax seems to indicate that the double-quote is multi-lineable the single not. [So YAML double-quote is like python triple-quote] JS: http://stackoverflow.com/questions/242813/when-to-use-double-or-single-quotes-in-javascript seems to have some arcane argument about whether there is a difference or not -- http://mail.python.org/mailman/listinfo/python-list
[issue14501] Error initialising BaseManager class with 'authkey' argument of string type.
New submission from Максим Цыпкин drauger...@gmail.com: The following code: class TestServer(BaseManager):pass Server_1=TestServer(address=(127.0.0.1,5),authkey=passkey) produces following error in python 3.2 : TypeError: string argument without an encoding The cause is in BaseManager constructor implementation (Python32\Lib\multiprocessing\managers.py): self._authkey = AuthenticationString(authkey) The AuthenticationString class is a substitute of bytes class, and bytes class requires second encoding argument, if first argument is a string. I've solved this problem, changing the code in Python32\Lib\multiprocessing\managers.py to following: if isinstance(authkey,str): self._authkey = AuthenticationString(authkey,'utf-8') else: self._authkey = AuthenticationString(authkey) This works for me. Please consider to fix this issue in release. -- components: Extension Modules messages: 157539 nosy: Drauger priority: normal severity: normal status: open title: Error initialising BaseManager class with 'authkey' argument of string type. type: crash versions: Python 3.2 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue14501 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue14492] pdeps.py has_key
Georg Brandl ge...@python.org added the comment: Should be x not in y BTW to be idiomatic, not not x in y. -- nosy: +georg.brandl ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue14492 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue14497] Invalid syntax Python files in Python sources tree
Georg Brandl ge...@python.org added the comment: Yes, Sphinx is still 2.x, although we could switch to a Python 3 version since now all necessary dependencies are ported. -- nosy: +georg.brandl ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue14497 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue14489] repr() function link on the built-in function documentation is incorrect
Roundup Robot devn...@psf.upfronthosting.co.za added the comment: New changeset 4416efeb0163 by Georg Brandl in branch '2.7': Closes #14489: correct link target. http://hg.python.org/cpython/rev/4416efeb0163 -- nosy: +python-dev resolution: - fixed stage: - committed/rejected status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue14489 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue14489] repr() function link on the built-in function documentation is incorrect
Georg Brandl ge...@python.org added the comment: Shows how it's a bad thing to have a builtin function and a module of the same name :) -- nosy: +georg.brandl ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue14489 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue14502] Document better what happens on releasing an unacquired lock
New submission from Georg Brandl ge...@python.org: From d...@python.org: I recently ran into a situation where I could not be certain that a lock was currently in the acquired state. I checked the documentation to determine what would happen if I attempted to release a lock that was already released, and saw an ominous warning of Do not call this method when the lock is unlocked. Needing to know what would happen, I cautiously tested it out. I half expected my computer to explode as I released a lock for the second time, but was pleased to see it raise a 'thread.error' exception which could be caught and handled. I generally expect the documentation to tell me what will happen if I do something invalid. In this case the documentation should indicate that a thread.error will be raised if you release an unlocked lock. I agree: if we know that a ThreadError will always be raised in this instance, we should document it as such. -- assignee: docs@python components: Documentation messages: 157544 nosy: docs@python, georg.brandl, pitrou priority: normal severity: normal status: open title: Document better what happens on releasing an unacquired lock versions: Python 2.7, Python 3.2, Python 3.3 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue14502 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue14486] Add some versionchanged notes in threading docs
Georg Brandl ge...@python.org added the comment: +1. -- nosy: +georg.brandl ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue14486 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue14492] pdeps.py has_key
Popa Claudiu pcmantic...@gmail.com added the comment: Hello. Here is the new patch. There was a few more problems: 1. in process, fp wasn't closed 2. in process, m_import.match(line) = 0 could fail if the regular expression didn't matched on that line I've included the tests, too. -- Added file: http://bugs.python.org/file25128/pdeps2.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue14492 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com