DAGDA SEARCH | Back to results | Support

Mailman 3 June 2002 - Python-Dev - python.org

Source: https://mail.python.org/archives/list/python-dev@python.org/2002/6/

Keyboard Shortcuts

Thread View

Python-Dev

Download Threads by month python-dev@python.org

June 2002

RE: [Python-Dev] Those import related syntax errors again...
by Samuele Pedroni Feb. 23, 2005
Feb. 23, 2005 Hi. [Mark Hammond] > The point isn't about my suffering as such. The point is more that > python-dev owns a tiny amount of the code out there, and I don't believe we > should put Python's users through this. > > Sure - I would be happy to "upgrade" all the win32all code, no problem. I > am also happy to live in the bleeding edge and take some pain that will > cause. > > The issue is simply the user base, and giving Python a reputation of not > being able to painlessly upgrade even dot revisions. I agree with all this. [As I imagined explicit syntax did not catch up and would require lot of discussions.] [GvR] > > Another way is to use special rules > > (similar to those for class defs), e.g. having > > > > <frag> > > y=3 > > def f(): > > exec "y=2" > > def g(): > > return y > > return g() > > > > print f() > > </frag> > > > > # print 3. > > > > Is that confusing for users? maybe they will more naturally expect 2 > > as outcome (given nested scopes). > > This seems the best compromise to me. It will lead to the least > broken code, because this is the behavior that we had before nested > scopes! It is also quite easy to implement given the current > implementation, I believe. > > Maybe we could introduce a warning rather than an error for this > situation though, because even if this behavior is clearly documented, > it will still be confusing to some, so it is better if we outlaw it in > some future version. > Yes this can be easy to implement but more confusing situations can arise: <frag> y=3 def f(): y=9 exec "y=2" def g(): return y return y,g() print f() </frag> What should this print? the situation leads not to a canonical solution as class def scopes. or <frag> def f(): from foo import * def g(): return y return g() print f() </frag> [Mark Hammond] > > This probably won't be a very popular suggestion, but how about pulling > > nested scopes (I assume they are at the root of the problem) > > until this can be solved cleanly? > > Agreed. While I think nested scopes are kinda cool, I have lived without > them, and really without missing them, for years. At the moment the cure > appears worse then the symptoms in at least a few cases. If nothing else, > it compromises the elegant simplicity of Python that drew me here in the > first place! > > Assuming that people really _do_ want this feature, IMO the bar should be > raised so there are _zero_ backward compatibility issues. I don't say anything about pulling nested scopes (I don't think my opinion can change things in this respect) but I should insist that without explicit syntax IMO raising the bar has a too high impl cost (both performance and complexity) or creates confusion. [Andrew Kuchling] > >Assuming that people really _do_ want this feature, IMO the bar should be > >raised so there are _zero_ backward compatibility issues. > > Even at the cost of additional implementation complexity? At the cost > of having to learn "scopes are nested, unless you do these two things > in which case they're not"? > > Let's not waffle. If nested scopes are worth doing, they're worth > breaking code. Either leave exec and from..import illegal, or back > out nested scopes, or think of some better solution, but let's not > introduce complicated backward compatibility hacks. IMO breaking code would be ok if we issue warnings today and implement nested scopes issuing errors tomorrow. But this is simply a statement about principles and raised impression. IMO import * in an inner scope should end up being an error, not sure about 'exec's. We will need a final BDFL statement. regards, Samuele Pedroni. 18 78 PEP 293, Codec Error Handling Callbacks
by Walter Dörwald Aug. 14, 2002

Aug. 14, 2002 Here's another new PEP. Bye, Walter Dörwald ---------------------------------------------------------------------- PEP: 293 Title: Codec Error Handling Callbacks Version: $Revision: 1.1 $ Last-Modified: $Date: 2002/06/19 03:22:11 $ Author: Walter Dörwald Status: Draft Type: Standards Track Created: 18-Jun-2002 Python-Version: 2.3 Post-History: Abstract This PEP aims at extending Python's fixed codec error handling schemes with a more flexible callback based approach. Python currently uses a fixed error handling for codec error handlers. This PEP describes a mechanism which allows Python to use function callbacks as error handlers. With these more flexible error handlers it is possible to add new functionality to existing codecs by e.g. providing fallback solutions or different encodings for cases where the standard codec mapping does not apply. Specification Currently the set of codec error handling algorithms is fixed to either "strict", "replace" or "ignore" and the semantics of these algorithms is implemented separately for each codec. The proposed patch will make the set of error handling algorithms extensible through a codec error handler registry which maps handler names to handler functions. This registry consists of the following two C functions: int PyCodec_RegisterError(const char *name, PyObject *error) PyObject *PyCodec_LookupError(const char *name) and their Python counterparts codecs.register_error(name, error) codecs.lookup_error(name) PyCodec_LookupError raises a LookupError if no callback function has been registered under this name. Similar to the encoding name registry there is no way of unregistering callback functions or iterating through the available functions. The callback functions will be used in the following way by the codecs: when the codec encounters an encoding/decoding error, the callback function is looked up by name, the information about the error is stored in an exception object and the callback is called with this object. The callback returns information about how to proceed (or raises an exception). For encoding, the exception object will look like this: class UnicodeEncodeError(UnicodeError): def __init__(self, encoding, object, start, end, reason): UnicodeError.__init__(self, "encoding '%s' can't encode characters " + "in positions %d-%d: %s" % (encoding, start, end-1, reason)) self.encoding = encoding self.object = object self.start = start self.end = end self.reason = reason This type will be implemented in C with the appropriate setter and getter methods for the attributes, which have the following meaning: * encoding: The name of the encoding; * object: The original unicode object for which encode() has been called; * start: The position of the first unencodable character; * end: (The position of the last unencodable character)+1 (or the length of object, if all characters from start to the end of object are unencodable); * reason: The reason why object[start:end] couldn't be encoded. If object has consecutive unencodable characters, the encoder should collect those characters for one call to the callback if those characters can't be encoded for the same reason. The encoder is not required to implement this behaviour but may call the callback for every single character, but it is strongly suggested that the collecting method is implemented. The callback must not modify the exception object. If the callback does not raise an exception (either the one passed in, or a different one), it must return a tuple: (replacement, newpos) replacement is a unicode object that the encoder will encode and emit instead of the unencodable object[start:end] part, newpos specifies a new position within object, where (after encoding the replacement) the encoder will continue encoding. If the replacement string itself contains an unencodable character the encoder raises the exception object (but may set a different reason string before raising). Should further encoding errors occur, the encoder is allowed to reuse the exception object for the next call to the callback. Furthermore the encoder is allowed to cache the result of codecs.lookup_error. If the callback does not know how to handle the exception, it must raise a TypeError. Decoding works similar to encoding with the following differences: The exception class is named UnicodeDecodeError and the attribute object is the original 8bit string that the decoder is currently decoding. The decoder will call the callback with those bytes that constitute one undecodable sequence, even if there is more than one undecodable sequence that is undecodable for the same reason directly after the first one. E.g. for the "unicode-escape" encoding, when decoding the illegal string "\\u00\\u01x", the callback will be called twice (once for "\\u00" and once for "\\u01"). This is done to be able to generate the correct number of replacement characters. The replacement returned from the callback is a unicode object that will be emitted by the decoder as-is without further processing instead of the undecodable object[start:end] part. There is a third API that uses the old strict/ignore/replace error handling scheme: PyUnicode_TranslateCharmap/unicode.translate The proposed patch will enhance PyUnicode_TranslateCharmap, so that it also supports the callback registry. This has the additional side effect that PyUnicode_TranslateCharmap will support multi-character replacement strings (see SF feature request #403100 [1]). For PyUnicode_TranslateCharmap the exception class will be named UnicodeTranslateError. PyUnicode_TranslateCharmap will collect all consecutive untranslatable characters (i.e. those that map to None) and call the callback with them. The replacement returned from the callback is a unicode object that will be put in the translated result as-is, without further processing. All encoders and decoders are allowed to implement the callback functionality themselves, if they recognize the callback name (i.e. if it is a system callback like "strict", "replace" and "ignore"). The proposed patch will add two additional system callback names: "backslashreplace" and "xmlcharrefreplace", which can be used for encoding and translating and which will also be implemented in-place for all encoders and PyUnicode_TranslateCharmap. The Python equivalent of these five callbacks will look like this: def strict(exc): raise exc def ignore(exc): if isinstance(exc, UnicodeError): return (u"", exc.end) else: raise TypeError("can't handle %s" % exc.__name__) def replace(exc): if isinstance(exc, UnicodeEncodeError): return ((exc.end-exc.start)*u"?", exc.end) elif isinstance(exc, UnicodeDecodeError): return (u"\\ufffd", exc.end) elif isinstance(exc, UnicodeTranslateError): return ((exc.end-exc.start)*u"\\ufffd", exc.end) else: raise TypeError("can't handle %s" % exc.__name__) def backslashreplace(exc): if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)): s = u"" for c in exc.object[exc.start:exc.end]: if ord(c)<=0xff: s += u"\\x%02x" % ord(c) elif ord(c)<=0xffff: s += u"\\u%04x" % ord(c) else: s += u"\\U%08x" % ord(c) return (s, exc.end) else: raise TypeError("can't handle %s" % exc.__name__) def xmlcharrefreplace(exc): if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)): s = u"" for c in exc.object[exc.start:exc.end]: s += u"&#%d;" % ord(c) return (s, exc.end) else: raise TypeError("can't handle %s" % exc.__name__) These five callback handlers will also be accessible to Python as codecs.strict_error, codecs.ignore_error, codecs.replace_error, codecs.backslashreplace_error and codecs.xmlcharrefreplace_error. Rationale Most legacy encoding do not support the full range of Unicode characters. For these cases many high level protocols support a way of escaping a Unicode character (e.g. Python itself supports the \x, \u and \U convention, XML supports character references via &#xxx; etc.). When implementing such an encoding algorithm, a problem with the current implementation of the encode method of Unicode objects becomes apparent: For determining which characters are unencodable by a certain encoding, every single character has to be tried, because encode does not provide any information about the location of the error(s), so # (1) us = u"xxx" s = us.encode(encoding) has to be replaced by # (2) us = u"xxx" v = [] for c in us: try: v.append(c.encode(encoding)) except UnicodeError: v.append("&#%d;" % ord(c)) s = "".join(v) This slows down encoding dramatically as now the loop through the string is done in Python code and no longer in C code. Furthermore this solution poses problems with stateful encodings. For example UTF-16 uses a Byte Order Mark at the start of the encoded byte string to specify the byte order. Using (2) with UTF-16, results in an 8 bit string with a BOM between every character. To work around this problem, a stream writer - which keeps state between calls to the encoding function - has to be used: # (3) us = u"xxx" import codecs, cStringIO as StringIO writer = codecs.getwriter(encoding) v = StringIO.StringIO() uv = writer(v) for c in us: try: uv.write(c) except UnicodeError: uv.write(u"&#%d;" % ord(c)) s = v.getvalue() To compare the speed of (1) and (3) the following test script has been used: # (4) import time us = u"äa"*1000000 encoding = "ascii" import codecs, cStringIO as StringIO t1 = time.time() s1 = us.encode(encoding, "replace") t2 = time.time() writer = codecs.getwriter(encoding) v = StringIO.StringIO() uv = writer(v) for c in us: try: uv.write(c) except UnicodeError: uv.write(u"?") s2 = v.getvalue() t3 = time.time() assert(s1==s2) print "1:", t2-t1 print "2:", t3-t2 print "factor:", (t3-t2)/(t2-t1) On Linux this gives the following output (with Python 2.3a0): 1: 0.274321913719 2: 51.1284689903 factor: 186.381278466 i.e. (3) is 180 times slower than (1). Codecs must be stateless, because as soon as a callback is registered it is available globally and can be called by multiple encode() calls. To be able to use stateful callbacks, the errors parameter for encode/decode/translate would have to be changed from char * to PyObject *, so that the callback could be used directly, without the need to register the callback globally. As this requires changes to lots of C prototypes, this approach was rejected. Currently all encoding/decoding functions have arguments const Py_UNICODE *p, int size or const char *p, int size to specify the unicode characters/8bit characters to be encoded/decoded. So in case of an error the codec has to create a new unicode or str object from these parameters and store it in the exception object. The callers of these encoding/decoding functions extract these parameters from str/unicode objects themselves most of the time, so it could speed up error handling if these object were passed directly. As this again requires changes to many C functions, this approach has been rejected. Implementation Notes A sample implementation is available as SourceForge patch #432401 [2]. The current version of this patch differs from the specification in the following way: * The error information is passed from the codec to the callback not as an exception object, but as a tuple, which has an additional entry state, which can be used for additional information the codec might want to pass to the callback. * There are two separate registries (one for encoding/translating and one for decoding) The class codecs.StreamReaderWriter uses the errors parameter for both reading and writing. To be more flexible this should probably be changed to two separate parameters for reading and writing. The errors parameter of PyUnicode_TranslateCharmap is not availably to Python, which makes testing of the new functionality of PyUnicode_TranslateCharmap impossible with Python scripts. The patch should add an optional argument errors to unicode.translate to expose the functionality and make testing possible. Codecs that do something different than encoding/decoding from/to unicode and want to use the new machinery can define their own exception classes and the strict handlers will automatically work with it. The other predefined error handlers are unicode specific and expect to get a Unicode(Encode|Decode|Translate)Error exception object so they won't work. Backwards Compatibility The semantics of unicode.encode with errors="replace" has changed: The old version always stored a ? character in the output string even if no character was mapped to ? in the mapping. With the proposed patch, the replacement string from the callback callback will again be looked up in the mapping dictionary. But as all supported encodings are ASCII based, and thus map ? to ?, this should not be a problem in practice. References [1] SF feature request #403100 "Multicharacter replacements in PyUnicode_TranslateCharmap" http://www.python.org/sf/403100 [2] SF patch #432401 "unicode encoding error callbacks" http://www.python.org/sf/432401 Copyright This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: 7 34 Priority queue (binary heap) python code
by Kevin O'Connor Aug. 11, 2002

Aug. 11, 2002 I often find myself needing priority queues in python, and I've finally broken down and written a simple implementation. Previously I've used sorted lists (via bisect) to get the job done, but the heap code significantly improves performance. There are C based implementations, but the effort of compiling in an extension often isn't worth the effort. I'm including the code here for everyone's amusement. Any chance something like this could make it into the standard python library? It would save a lot of time for lazy people like myself. :-) Cheers, -Kevin def heappush(heap, item): pos = len(heap) heap.append(None) while pos: parentpos = (pos - 1) / 2 parent = heap[parentpos] if item <= parent: break heap[pos] = parent pos = parentpos heap[pos] = item def heappop(heap): endpos = len(heap) - 1 if endpos <= 0: return heap.pop() returnitem = heap[0] item = heap.pop() pos = 0 while 1: child2pos = (pos + 1) * 2 child1pos = child2pos - 1 if child2pos < endpos: child1 = heap[child1pos] child2 = heap[child2pos] if item >= child1 and item >= child2: break if child1 > child2: heap[pos] = child1 pos = child1pos continue heap[pos] = child2 pos = child2pos continue if child1pos < endpos: child1 = heap[child1pos] if child1 > item: heap[pos] = child1 pos = child1pos break heap[pos] = item return returnitem -- ------------------------------------------------------------------------ | Kevin O'Connor "BTW, IMHO we need a FAQ for | | kevin(a)koconnor.net 'IMHO', 'FAQ', 'BTW', etc. !" | ------------------------------------------------------------------------ 16 43 test_socket failure on FreeBSD
by Andrew MacIntyre July 19, 2002

July 19, 2002 Below is the output of test_socket with the -v option, from a CVS tree of about 1915 UTC June 18. FreeBSD 4.4, gcc 2.95.3 (-g -O3). In speaking up now, I'm making the assumption that the non-blocking socket changes should be complete, modulo bugfixes. If this is not the case, please let me know, and I'll wait for the situation to stabilise. Otherwise, is there any more info I can (attempt to) provide? I tried "print"ing the addr variable when running the test, and just get "ERROR" (sans quotes of course). I've not yet tried to build the OS/2 port with the current CVS code, so I don't yet know what the situation is there. Won't have much time to dig until the weekend... -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac(a)bullseye.apana.org.au | Snail: PO Box 370 andymac(a)pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia ---------- Forwarded message ---------- Date: Wed, 19 Jun 2002 22:13:45 +1000 (EST) {...} test_socket Testing for mission critical constants. ... ok Testing getservbyname(). ... ok Testing getsockopt(). ... ok Testing hostname resolution mechanisms. ... ok Making sure getnameinfo doesn't crash the interpreter. ... ok Testing for existance of non-crucial constants. ... ok Testing reference count for getnameinfo. ... ok Testing setsockopt(). ... ok Testing getsockname(). ... ok Testing that socket module exceptions. ... ok Testing fromfd(). ... ok Testing receive in chunks over TCP. ... ok Testing recvfrom() in chunks over TCP. ... ERROR Testing large receive over TCP. ... ok Testing large recvfrom() over TCP. ... ERROR Testing sendall() with a 2048 byte string over TCP. ... ok Testing shutdown(). ... ok Testing recvfrom() over UDP. ... ok Testing sendto() and Recv() over UDP. ... ok Testing non-blocking accept. ... FAIL Testing non-blocking connect. ... ok Testing non-blocking recv. ... FAIL Testing whether set blocking works. ... ok Performing file readline test. ... ok Performing small file read test. ... ok Performing unbuffered file read test. ... ok ====================================================================== ERROR: Testing recvfrom() in chunks over TCP. ---------------------------------------------------------------------- Traceback (most recent call last): File "./Lib/test/test_socket.py", line 359, in testOverFlowRecvFrom hostname, port = addr TypeError: unpack non-sequence ====================================================================== ERROR: Testing large recvfrom() over TCP. ---------------------------------------------------------------------- Traceback (most recent call last): File "./Lib/test/test_socket.py", line 347, in testRecvFrom hostname, port = addr TypeError: unpack non-sequence ====================================================================== FAIL: Testing non-blocking accept. ---------------------------------------------------------------------- Traceback (most recent call last): File "./Lib/test/test_socket.py", line 451, in testAccept self.fail("Error trying to do non-blocking accept.") File "/home/andymac/cvs/python/python-cvs/Lib/unittest.py", line 254, in fail raise self.failureException, msg AssertionError: Error trying to do non-blocking accept. ====================================================================== FAIL: Testing non-blocking recv. ---------------------------------------------------------------------- Traceback (most recent call last): File "./Lib/test/test_socket.py", line 478, in testRecv self.fail("Error trying to do non-blocking recv.") File "/home/andymac/cvs/python/python-cvs/Lib/unittest.py", line 254, in fail raise self.failureException, msg AssertionError: Error trying to do non-blocking recv. ---------------------------------------------------------------------- Ran 26 tests in 0.330s FAILED (failures=2, errors=2) test test_socket failed -- errors occurred; run in verbose mode for details 1 test failed: test_socket 2 5 Fw: Behavior of buffer()
by Raymond Hettinger July 18, 2002

July 18, 2002 GvR thought you guys might have some ideas on this one for me. If I don't get any replies, I may have to rely on my own instincts and judgment and no one knows what follies might ensue ;) Raymond Hettinger ----- Original Message ----- From: "Raymond Hettinger" <python(a)rcn.com> To: <python-dev(a)python.org> Sent: Friday, June 21, 2002 1:16 PM Subject: Behavior of buffer() > I would like to solicit py-dev's thoughts on the best way to resolve a bug, > www.python.org/sf/546434 . > > The root problem is that mybuf[:] returns a buffer type and mybuf[2:4] > returns a string type. A similar issue exists for buffer repetition. > > One way to go is to have the slices always return a string. If code > currently relies on the type of a buffer slice, it is more likely to be > relying on it being a string as in: print mybuf[:4]. This is an intuitive > guess because I can't find empirical evidence. Another reason to choose a > string return type is that buffer() appears to have been designed to be as > stringlike as possible so that it can be easily substituted in code > originally designed for strings. > > The other way to go is to return a buffer object everytime. Slices usually, > but not always (see subclasses of list), return the same type that was being > sliced. If we choose this route, another issue remains -- mybuf[:] returns > self instead of a new buffer. I think that behavior is also a bug and > should be changed to be consistent with the Python idiom where: > b = a[:] > assert id(a) != id(b) > > Incidental to the above, GvR had a thought that slice repetition ought to > always return an error. Though I don't see any use cases for buffer > repetition, bufferobjects do implement all other sequence behaviors and I > think it would be weird to nullify the sq_repeat slot. > > I appreciate your thoughts on the best way to proceed. > > fixing-bugs-is-easier-than-deciding-appropriate-behavior-ly yours, > > > 'regnitteh dnomyar'[::-1] > > > > > > > > > > > > > > 9 33 PEP 292-related: why string substitution is not the same operation as data formatting
by Lalo Martins July 18, 2002

July 18, 2002 For a moment, please remove for your mind your experience of C and printf. Meditate with me and picture yourself in a happy world of object-orientation and code readability, where everything cryptic and obscured is banished. Just to help you do that, I'll avoid the notation chosen by the PEP. Let's use, for the duration of this post, the hypothetic notation suggested by some other reader: "<<name>> is from <<country>>". Now, this thing we're talking about is replacing parts of the string with other strings. These strings may be the result of running some non-string objects trough str(foo) - but, we are making no assumptions about these objects. Just that str(foo) is somehow meaningful. And, to my knowledge, there are no python objects for which str(foo) doesn't work. So, string substitution is non-intrusive. Also, if you keep your templates (let's call a string containing substitution markup a template, shall we?) outside your source code, as is the case with i18n, pure substitution doesn't require the people who edit them (for example, translators) to know anything about python *or* even programming. String substitution only depends on an identifier ('name' or 'country'), no sick abbreviations like 's' or 'd' or 'f' or 'r' or 'x' that you have to keep a table for. So, string substitution is readable and non-cryptic. Now, data formatting is another animal entirely. It's a way to request one specific representation of a piece of data. But there is a catch. When you do '%8.3d' % foo you are *expecting* that foo a floating-point number and you know you'll get TypeError otherwise. This is, IMO, invasive. In my ideal OO-paradise I would rather have something like foo.format(8, 3) (THIS IS NOT A PEP!). IMO, if you, as I asked in the first paragraph, pretend you don't know C and printf and python's % operator and then pretend you're having your first contact with it, while already having some experience with python's readability, it's hard not to be shocked. And I bet you'd go to great lengths to avoid using the "feature". Conclusion: I think string formatting is a cryptic and obscure misfeature inherited from C that should be deprecated in favour of something less invasive and more readable/explicit. More, I'm completely opposed to "<<name>> is <<age:.0d>> years old" because it's still cryptic and invasive. This should instead read similar to "<<name>> is <<age>> years old".sub({'name': x.name, 'age': x.age.format(None, 0)}) Guido, can you please, for our enlightenment, tell us what are the reasons you feel %(foo)s was a mistake? []s, |alo +---- -- It doesn't bother me that people say things like "you'll never get anywhere with this attitude". In a few decades, it will make a good paragraph in my biography. You know, for a laugh. -- http://www.laranja.org/ mailto:lalo@laranja.org pgp key: http://www.laranja.org/pessoal/pgp Python Foundry Guide http://www.sf.net/foundry/python-foundry/ 10 15 Provide a Python wrapper for any new C extension
by Hamish Lawson July 15, 2002

July 15, 2002 One of the arguments put forward against renaming the existing time module to _time (as part of incorporating a pure-Python strptime function) is that it could break some builds. Therefore I'd suggest that it could be a useful principle for any C extension added in the future to the standard library to have an accompanying pure-Python wrapper that would be the one that client code would usually import. Hamish Lawson 9 35 PEP 294: Type Names in the types Module
by Oren Tirosh July 15, 2002

July 15, 2002 PEP: 294 Title: Type Names in the types Module Version: $Revision: 1.1 $ Last-Modified: $Date: 2002/06/23 23:52:19 $ Author: oren at hishome.net (Oren Tirosh) Status: Draft Type: Standards track Created: 19-Jun-2002 Python-Version: 2.3 Post-History: Abstract This PEP proposes that symbols matching the type name should be added to the types module for all basic Python types in the types module: types.IntegerType -> types.int types.FunctionType -> types.function types.TracebackType -> types.traceback ... The long capitalized names currently in the types module will be deprecated. With this change the types module can serve as a replacement for the new module. The new module shall be deprecated and listed in PEP 4. Rationale Using two sets of names for the same objects is redundant and confusing. In Python versions prior to 2.2 the symbols matching many type names were taken by the factory functions for those types. Now all basic types have been unified with their factory functions and therefore the type names are available to be consistently used to refer to the type object. Most types are accessible as either builtins or in the new module but some types such as traceback and generator are only accssible through the types module under names which do not match the type name. This PEP provides a uniform way to access all basic types under a single set of names. Specification The types module shall pass the following test: import types for t in vars(types).values(): if type(t) is type: assert getattr(types, t.__name__) is t The types 'class', 'instance method' and 'dict-proxy' have already been renamed to the valid Python identifiers 'classobj', 'instancemethod' and 'dictproxy', making this possible. Backward compatibility Because of their widespread use it is not planned to actually remove the long names from the types module in some future version. However, the long names should be changed in documentation and library sources to discourage their use in new code. Reference Implementation A reference implementation is available in SourceForge patch #569328: http://www.python.org/sf/569328 Copyright This document has been placed in the public domain. 5 7 Minor socket timeout quibble - timeout raises socket.error
by Skip Montanaro July 14, 2002

July 14, 2002 I just noticed in the development docs that when a timeout on a socket occurs, socket.error is raised. I rather liked the idea that a different exception was raised for timeouts (I used Tim O'Malley's timeout_socket module). Making a TimeoutError exception a subclass of socket.error would be fine so you can catch it with existing code, but I could see recovering differently for a timeout as opposed to other possible errors: sock.settimeout(5.0) try: data = sock.recv(8192) except socket.TimeoutError: # maybe requeue the request ... except socket.error, codes: # some more drastic solution is needed ... Skip 4 7 Dict constructor
by Raymond Hettinger July 14, 2002

July 14, 2002 Second wild idea of the day: The dict constructor currently accepts sequences where each element has length 2, interpreted as a key-value pair. Let's have it also accept sequences with elements of length 1, interpreted as a key:None pair. The benefit is that it provides a way to rapidly construct sets: lowercase = dict('abcdefghijklmnopqrstuvwxyz') if char in lowercase: ... dict([key1, key2, key3, key1]).keys() # eliminate duplicate keys Raymond Hettinger 'regnitteh dnomyar'[::-1] 13 27