[issue47001] deadlock in ctypes?
Rocco Matano added the comment: I forgot to say thank you. I would like to make up for that: Thank you, Eryk. -- ___ Python tracker <https://bugs.python.org/issue47001> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue47001] deadlock in ctypes?
Rocco Matano added the comment: @Eryk I think you hit the nail on the head with your recommendation to avoid ctypes.c_wchar_p (i.e. wintypes.LPWSTR) as the parameter type when dealing resource type/name strings. Of course ctypes automatic conversion from a C character pointer to a Python string will cause problems when being confronted with a 16-bit ID that is NOT a valid pointer. Now that it is clear that the problem was in front of the monitor, I consider this case closed. -- stage: -> resolved status: open -> closed ___ Python tracker <https://bugs.python.org/issue47001> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue47001] deadlock in ctypes?
New submission from Rocco Matano : When using ctypes under Windows, I have observed a baffling behavior which I am not sure if it is the result of a bug in ctypes, or is simply due to false expectations on my part. Environment: - Windows 10 Pro, 21H1, 19043.1586, x64 - Python versions 3.6 up to 3.10, x64 What I was trying to do was to enumerate all the icons in the resource section of an executable file. The Windows-API for such a case is EnumResourceNamesW, which requires the pointer to a callback function as an argument. I wanted to hide the details of the corresponding code so that a user of that code does not have to deal with ctypes directly and can supply a regular Python function for the callback. So I added an extra level of indirection. When I ran my code, I was surprised to observe that the program was stuck. After several tries, I found a solution that differed from the original code only in one small detail: Use different types when describing the C callback. Below is a self contained sample that can be used to show the successful case as well as to trigger the blocking. Unfortunately it is quit long. import sys import ctypes from ctypes.wintypes import HMODULE, LPVOID, LPWSTR, BOOL # context structure that is used to use regular python functions as callbacks # where external C code expects C callbacks with a certain signature. class CallbackContext(ctypes.Structure): _fields_ = ( ("callback", ctypes.py_object), ("context", ctypes.py_object), ) CallbackContextPtr = ctypes.POINTER(CallbackContext) # quote from # https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nc-libloaderapi-enumresnameprocw # # BOOL Enumresnameprocw( # [in, optional] HMODULE hModule, # LPCWSTR lpType, # LPWSTR lpName, # [in] LONG_PTR lParam # ) # Note that the arguments lpType and lpName are declared as pointers to strings. if len(sys.argv) > 1 and sys.argv[1].lower() == "fail": # Declaring them as pointers to strings in the ctypes prototype does NOT work. EnumResNameCallback_prototype = ctypes.WINFUNCTYPE( BOOL, HMODULE, LPWSTR, LPWSTR, CallbackContextPtr ) else: # Declaring them as void pointers does work! EnumResNameCallback_prototype = ctypes.WINFUNCTYPE( BOOL, HMODULE, LPVOID, LPVOID, CallbackContextPtr ) # this is the ctypes callback function that mimics the required C call signature @EnumResNameCallback_prototype def EnumResNameCallback(hmod, typ, name, ctxt): cbc = ctxt.contents return cbc.callback(hmod, typ, name, cbc.context) kernel32 = ctypes.windll.kernel32 EnumResourceNames = kernel32.EnumResourceNamesW EnumResourceNames.restype = BOOL EnumResourceNames.argtypes = ( HMODULE, LPWSTR, EnumResNameCallback_prototype, CallbackContextPtr ) # Get a module handle for an executable that contains icons GetModuleHandle = kernel32.GetModuleHandleW GetModuleHandle.restype = HMODULE GetModuleHandle.argtypes = (LPWSTR,) hmod = GetModuleHandle(sys.executable) if hmod == 0: raise ctypes.WinError() RT_GROUP_ICON = ctypes.cast(14, LPWSTR) # this is the 'regular' callback function that does not have to care about # the C call signature def enum_callback(hmod, typ, name, unused_context): print(hmod, typ, name) return True cbc = CallbackContext(enum_callback, None) rcbc = ctypes.byref(cbc) print("Trying to enumerate icons.") print("In the case of failure, this WILL BLOCK indefinitely!") EnumResourceNames(hmod, RT_GROUP_ICON, EnumResNameCallback, rcbc) -- components: ctypes messages: 415029 nosy: rocco.matano priority: normal severity: normal status: open title: deadlock in ctypes? type: behavior versions: Python 3.10, Python 3.7, Python 3.8, Python 3.9 ___ Python tracker <https://bugs.python.org/issue47001> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue36524] identity operator
Rocco Santoro added the comment: You are right. The documentation, that I know, is clear. Anyway in this case "is" and "==" provides the same outcome and this is my remark, that I called bug, wrongly. The reason is the nature of print(), as function, that always remains always NoneType with only the value None. Nevertheless, print, as method, could be referred to the object. This is my goofy remark about the contraddiction between the message of the communication by print method and the nature of the communication by print function. Therefore, the monitor tells you that two things are not equals because they are two different ways to say the same message. Thanks a lot for the patience -- ___ Python tracker <https://bugs.python.org/issue36524> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue36524] identity operator
Rocco Santoro added the comment: Thanks you very much for the explanations. I am sorry for bothering you, actually my question concerned the use of identity operator. I suggest that '==' means equal not identity. Therefore, it concerns the instance not the ontology and makes a comparison between the values not the types. In my modest opinion this is a bug. Anyway, you have explain very well the class None and the role of print as function in Python. My little remark is that a communication act should not change the type of object that shows. Instead it transforms the object in Noneclass. This is a peculiar of Python. Warm regards. Rocco -- ___ Python tracker <https://bugs.python.org/issue36524> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue36524] identity operator
New submission from Rocco Santoro : Hi all Why the identity operator and '==' are both applied to the type (see above)? Is it not convenient to distinguish them? I mean the identity operator applied to the type and '==' applied to the outcome. Thanks for the attention Best regards Rocco Santoro Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> import math >>> x = math.log(1000) >>> y = math.log(10) >>> print(x/y) == x/y 7.0 False >>> print(math.log(1000)/math.log(10)) == math.log(1000)/math.log(10) 7.0 False >>> x = math.sin(32) >>> y = math.cos(41) >>> print(y/x) == y/x -1.7905177807148493 False >>> x = math.pi >>> y = math.tau >>> x/y == print(x/y) 0.5 False >>> x = 153 >>> y = 245 >>> print(x/y) == x/y 0.6244897959183674 False >>> print(x+y) == x + y 398 False >>> print(x*y) == x*y 37485 False >>> s1 = 'Hello, ' >>> s2 = 'how are you?' >>> print(s1 + s2) == s1 + s2 Hello, how are you? False >>> print(s1 + s2) is s1 + s2 Hello, how are you? False >>> type(print(s1 + s2)) Hello, how are you? >>> type(s1 + s2) >>> type(print(y/x)) 1.6013071895424837 >>> type(x/y) -- assignee: terry.reedy components: IDLE messages: 339441 nosy: roccosan, terry.reedy priority: normal severity: normal status: open title: identity operator type: behavior versions: Python 3.7 ___ Python tracker <https://bugs.python.org/issue36524> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue22107] tempfile module misinterprets access denied error on Windows
Rocco Matano added the comment: I just experienced the described problem using Python 3.6.0 (Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32), but i do not understand the current status of this issue: On the one hand it is marked as 'open', which seems to imply that is still not resolved. On the other hand the resolution was set to 'fixed' in May 2015. Should i open a new issue for Python 3.6? -- nosy: +rocco.matano versions: +Python 3.6 ___ Python tracker <rep...@bugs.python.org> <http://bugs.python.org/issue22107> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue25118] OSError in os.waitpid() on Windows [3.5.0 regression]
Rocco Matano added the comment: I know that using os.spawn and and os.waitpid this way is not the best option, but a 3rd party tool i am using (scons) is doing it that way. So no scons with Python 3.5.0. (I am also aware that scons does not yet support Python 3.x officially.) -- ___ Python tracker <rep...@bugs.python.org> <http://bugs.python.org/issue25118> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue25118] OSError in os.waitpid
New submission from Rocco Matano: On windows and python up to 3.4 using the combination of os.spawnX(os.P_NOWAIT, ...) and os.waitpid() worked as expected, but with python 3.5 this no longer works. In fact os.waitpid() now raises an OSError when the child process terminates. Running this simple script demonstrates that: import sys import os import time print(sys.version) file = r'c:\windows\system32\cmd.exe' args = [file, '/C', 'ping', '1.1.1.1', '-n', '1', '>NUL'] env = os.environ t0 = time.time() ret = os.spawnve(os.P_NOWAIT, file, args, env) pid, status = os.waitpid(ret, 0) t1 = time.time() print("process took %.1f seconds" % (t1 - t0)) I get the following outputs: C:\Users\rmatano\test_py35>py -3.4 test_waitpid.py 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:25:23) [MSC v.1600 64 bit (AMD64)] process took 3.6 seconds C:\Users\rmatano\test_py35>py -3.5 test_waitpid.py 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)] Traceback (most recent call last): File "twp.py", line 13, in pid, status = os.waitpid(ret, 0) OSError: [Errno 0] Error I guess this is a bug rather than a intended change in behavior, isn't it? -- components: Library (Lib) messages: 250723 nosy: rocco.matano priority: normal severity: normal status: open title: OSError in os.waitpid type: behavior versions: Python 3.5 ___ Python tracker <rep...@bugs.python.org> <http://bugs.python.org/issue25118> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue12923] test_urllib fails in refleak mode
Daniel Rocco added the comment: Hi, Here is an alternate patch to the test suite that demonstrates the failure without needing refleak mode. The test works by issuing enough requests that, if retries are not independent per request, the test triggers the code path that results in the test failing. It passes with the patch to request.py applied. Thanks, dan -- nosy: +drocco versions: +Python 3.5 -Python 3.3 Added file: http://bugs.python.org/file39004/12923-tries-reset-test.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12923 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
What does it mean when io.TextIOBase.encoding is None
When using nose to run unittests, i discovered that depending on nose' command line parameters, sys.stdout.encoding can be None. I wonder what that means for an io.TextIOBase object. Is None a valid value for 'encoding'? Is None equivalent to 'ascii' in this case? If None is a valid value for io.TextIOBase.encoding, then why is it not a valid value for bytes.encode()? Regards, Rocco -- https://mail.python.org/mailman/listinfo/python-list
Custom CFLAGS with distutils
Hi, I've been trying to make distutils build mercurial with custom cflags. The only way this works is to change Makefile because I don't want to put my changed CFLAGS into the environment and I tend to forget to run make with a CFLAGS=... option. Google brings up a special Setup file which should solve my problem, but it somehow doesn't. I've tried: mercurial mercurial/base85.c -Xcompiler -arch x86_64 mercurial.base85 mercurial/base85.c -Xcompiler -arch x86_64 for base85.c in the mercurial/ subdirectory. Hacking Makefile does the trick, but having a Setup file working would never produce merge conflicts. What am I doing wrong? Rocco -- http://mail.python.org/mailman/listinfo/python-list
Variable by label
Is there any function which will return a variable by passing to it the string containing the variable's name? Something like this for instance: foo = some_function(foo) or perhaps it's a dictionary. I don't know, but I would really like to find out how it can be done. I guess it is achievable. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Variable by label
On May 16, 4:27 pm, inhahe [EMAIL PROTECTED] wrote: a = 1 b = eval(a) b 1 a =1 b = globals()[a] b 1 a =1 b = locals()[a] b 1[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Is there any function which will return a variable by passing to it the string containing the variable's name? Something like this for instance: foo = some_function(foo) or perhaps it's a dictionary. I don't know, but I would really like to find out how it can be done. I guess it is achievable. Thank you. Perfect. Thank you all for your replies. -- http://mail.python.org/mailman/listinfo/python-list
Python generators (coroutines)
I would really like to know more about python 2.5's new generator characteristics that make them more powerful and analogous to coroutines. Is it possible for instance to employ them in situations where I would normally use a thread with a blocking I/O (or socket) operation? If it is, could someone show me how it can be done? There appears to be a very limited amount of documentation in this repect, unfortunately. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python generators (coroutines)
Anyway, if you have a blocking operation, the only solution is to use a thread or a separate process. Michele Simionato That's what I thought. It was in fact rather obvious, but I wanted to be sure that I hadn't overlooked some arcane possibility (ex. with the use of exceptions or something like that). Thanks for the confirmation. -- http://mail.python.org/mailman/listinfo/python-list
Orphaned child processes
I'm using the Python processing module. I've just run into a problem though. Actually, it's a more general problem that isn't specific to this module, but to the handling of Unix (Linux processes) in general. Suppose for instance that for some reason or another, after forking several child processes, the main process terminates or gets killed (or segfaults or whatever) and the child processes are orphaned. Is there any way to automatically arrange things so that they auto- terminate or, in other words, is there a way to make the child processes terminate when the parent terminates? Thank you. -- http://mail.python.org/mailman/listinfo/python-list
xmlrpclib, testing server presence
I'm employing xmlrpclib for a project at work, and I must say that I'm quite impressed with its effectiveness and ease of use. However, I was recently doing some tests when I realized that if the server was down, the client quite simply hanged (no use of try ... except here) with no error or tracebacks or exceptions whatsoever. Is there some way in Python of testing the presence of the server on the other end, so as to avoid this situation? Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question
On Jan 7, 12:09 am, GHZ [EMAIL PROTECTED] wrote: Had the same issue. What you want is: reload() Thanks :) -- http://mail.python.org/mailman/listinfo/python-list
Noob question
Tinkering with Python I find myself often writing scripts and then experimenting with the interactive interpreter, which is really a cool way to learn a language. However, when, after loading a module with import module or from module import * and using it, I make a change to the module file, the changes are not effective after re-importing that same module, and I have to exit the interpreter and restart all over. Isn't there some way to avoid this annoying process? Thank you. -- http://mail.python.org/mailman/listinfo/python-list
PyGTK, libglade, and signal_autoconnect
I was having a real hard time trying to accomplish something. I couldn't find a way to automatically connect the close button (clicked signal) of a GUI app I was working on, to the gtk.main_quit() function. I had entered this handler directly with the GLADE-3 designer (I DON'T WANT TO USE A DICTIONARY, because I think that, using GLADE, I should be able to shortcut that procedure) but in my class the self.wtree.signal_autoconnect(self) wasn't working. Of course, I thought, it's looking for gtk.main_quit() which is obviously somewhere else. So, the only solution I could think of was to add: self.wtree.signal_autoconnect(gtk) --- having already imported gtk, naturally! This automagically worked. What I would like to know is if this is legitimate, and the right way to go. It is basically a solution I cooked up instinctively, which happened to work, but perhaps I am unaware of some other more orthodox way of doing it. Thank you. Rock -- http://mail.python.org/mailman/listinfo/python-list
IDLE question
I'm using IDLE for my Python programming. I can't seem to solve one issue though. Whenever I try to indent a region of code, I simply select it and hit the tab key, as I usually do in most editors, like GEdit or Geany on Linux, for instance, and it works fine. But, if I try to unindent a region of code, which i would do by pressing Shift- Tab in other editors, it just won't work, and I can't find any combination that will. Anybody know if this operation is possible at all with IDLE, and if it is, what's the combination of keys? Thanx. Rock -- http://mail.python.org/mailman/listinfo/python-list
Loops and things
I was wondering how and if it's possible to write a loop in python which updates two or more variables at a time. For instance, something like this in C: for (i = 0, j = 10; i 10 j 20; i++, j++) { printf(i = %d, j = %d\n, i, j); } So that I would get: i = 0, j = 0 i = 1, j = 1 i = 2, j = 2 ... ... ... i = 9, j = 19 Can this be done in Python? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Loops and things
I was wondering how and if it's possible to write a loop in python which updates two or more variables at a time. For instance, something like this in C: for (i = 0, j = 10; i 10 j 20; i++, j++) { printf(i = %d, j = %d\n, i, j); } So that I would get: i = 0, j = 0 i = 1, j = 1 i = 2, j = 2 ... ... ... i = 9, j = 19 Can this be done in Python? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: why not in python 2.4.3
Also with ascii the function does not work. -- http://mail.python.org/mailman/listinfo/python-list
Re: why not in python 2.4.3
Thanks Serge. It's a gzip string. So the code is import urllib2 def takefeed(url): request=urllib2.Request(url) request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5;Windows NT') opener = urllib2.build_opener() data=opener.open(request).read() return data url='http://news.google.it/?output=rss' d=takefeed(url) from StringIO import StringIO zipdata=StringIO(d) import gzip gz=gzip.GzipFile(fileobj=zipdata) rss=gz.read() len(rss) 102529 print rss[0:100] ?xml version=1.0 encoding=UTF-8?rss version=2.0channelgeneratorNFE/1.0/generatortit -- http://mail.python.org/mailman/listinfo/python-list
why not in python 2.4.3
hi I made the upgrade to python 2.4.3 from 2.4.2. I want to take from google news some atom feeds with a funtion like this import urllib2 def takefeed(url): request=urllib2.Request(url) request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT') opener = urllib2.build_opener() data=opener.open(request).read() return data url='http://news.google.it/?output=rss' d=takefeed(url) This woks well with python 2.3.5 but does not work with 2.4.3. Why? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: why not in python 2.4.3
This is the problem when I run the function this is the result from 2.3.5 print rss ?xml version=1.0 encoding=UTF-8?feed version=0.3 xml:lang=it xmlns=http://purl.org/atom/ns#;generatorNFE/1.0/generatortitleGoogle News Italia/titlelink rel=alternate type=text/html href=http://news.google.it//taglineGoogle News Italia/taglineauthornameGoogle Inc./nameemail[EMAIL PROTECTED]/email/authorcopyrightamp;copy;2006 Google/copyrightmodified2006-05-28T19:09:13+00:00/modified !-- A couple notes: * add an output=atom param to get Atom * section pages have a topic=? param; use topic=h for a Top Stories section. --entrytitleBenedetto XVI: Wojtyla santo subito - Libertà /titlelink rel=alternate type=text/html href=http://www.liberta.it/default.asp?IDG=605282024/idtag:news.google.com,2005:cluster=41b535fb/idsummaryPrima pagina/summaryissued2006-05-28T11:05:00+00:00/issuedmodified2006-05-28T11:05:00+00:00/modifiedcontent type=text/html mode=escapedlt;brgt;lt;table border=0 align= cellpadding=5 cellspacing=0gt;lt;trgt;lt;td width=80 align=center valign=topgt;lt;a . import sys sys.getdefaultencoding() 'ascii' this is the result with 2.4.3 print rss ヒ rss '\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff\xe5}Ks\xe3F\xb6\xe6\xfeF\xdc\xff\x90\xd77\xba\xc3\x9e\x10D\xbc\x01\xcaU\xee\xa1\x9eM[\xa2\xd4$\xabl\xf7\x86\x93\x04\x93Tv\x81H\x1a\x0fV\xa9V\xfe\x0f3\x9b\x8e\x98\x89\xb8\xcb\x1b\xd1\xb3\x9a\xddD\xef\xec\x7f\xe2_2\xe7$\x00\x8a/\x11|\x93\xd6\xb4\xa3U\x04\x02\x99\xe7d\x9e\xdfy\xbe\xf9\xd3\xa7\xbeO\x86,\x8c\xb8\x08\xde~\xa1\x9d\xaa_\x10\x16x\xa2\xc3\x83\xde\xdb/\xde5\xaf\x15\xf7\x8b?}\xf3\x8c\xa2\xe7\x9bt\xb8\xe9\x9b7\xde#\r\x02\xe6\x7f\xf3\xa6\xc7\x02\x16\xd2X\x84\xdf\xd4\xae\xafJ\xf0\x847\xa5\xe7Kob\x1e\xfb\xec\x9b\x1b!z#5\xf61\xd5\x98\xfa\x9c\xbe)\xa5\x7fy\xe3\xf3\xe0\xc37\x8fq8+\x95\x02\xf8\xfbiO\xde{\xca\xe3\xd2\x9b\x92\xfc\xe3\x9b\x0e\x8b\xbc\x90\x0fbx\xfb\xdc\'\x8d\xff\xfd\x8dO\x83^B{\xec\x1b\x1e\xc3\xf7\xf3\x0fo\xb2\xf6\x1d\x8db\x16~\x83/Q\xba\x8cu\xda\xd4\xfb\xf0_\xb3\xb7y\xa2\xff\xa6\xf4|\xcf\x1bO\x0c\x9eB\xde{\x8c\xbf\xf9#\xed\x0f\xbe\xc6\x8f_\xeb\xaaj\x93\xf4\xfdoJ\xcf7\xbc\x19$\xedK\x1a\xb3o\x1aIpBt\x97\xdc\xd1\'\xef\xd5\xb53\xcd3\x1crs\xd7|S\xcao\x83\x11F\xf1y\xc2\xfd\xce2\xdf\x9a\xbc\xf9_\xff\xe5\xcd\xbf)\n\xa9\x10O$\x03 C b\x16\x9d\xfd\xeb\xbf\x10\xfc\xdf\x7f!\xb4\xd3!4 [EMAIL PROTECTED]'\xb1 =\x16\x93z\xa31\xba9b\x1eR\x0cn\xe8\xb1\x88\xd2!#\x94|\x11\x8b\x01\xf7\xde\xfe)\xfb\xde\xd7\xd9\xdd\x84$\x11\xcb\xff\xf8\xf8\x05\xe9\x8a\x10nn\x8a\x01i\x00\x979|?{\xda\xe9\xbf\xfe\x8b\xa2|\xf3\x86\xf7%\xd1\x0b\x99\x9f\x84\xfe\xde\x037J\x88\xfd\x12\x8f[\xb0\x0e\xe4\xd3yG+dp\x17\xef\xbe)\xe1W\x97Y\xa5l,f\xfd|D\x15\xf2=\xed\x88\x8f\xdcc\'\xc4\xe3q\xfc\xeb\x7f\x90\x80\xc2\xc8\x18\xe9p\xf2\x1d\r\x85\x7fB\xb8O\x1eD\x10\xb3.\xdc\x05\xd4!\xb4\xdbea\x1f\x1659==%\n\xa9\xfa\xa4\xc9\xfa\x03\xb1\xccB\xc6\x8f8\xe0?E\xf4m3]P\xf1[\xb8\xae*\xf0\x9f\xfc\xdc\xed\xbc\xad\xcb_\xe0\xae\xb7\xd9C~\xfcx\xca\xfd\x18_\x82\x0f\xa1\x83A(\xba\xe8\xf0\x0bb\x0e\x04\xea\xb0O\xa74\x import sys sys.getdefaultencoding() 'latin_1' No exception trace Thanks again -- http://mail.python.org/mailman/listinfo/python-list
Re: looking for atomixlib
here you'll find it in svn. http://trac.defuze.org/browser/oss -- http://mail.python.org/mailman/listinfo/python-list
Re: can't use NetcdfFile
[EMAIL PROTECTED] wrote: Hi, I'm trying to open a Netcdf file using NetcdfFile but I always get an import error DLL failed even though I've tried using all these: import Numeric from Scientific.IO.NetCDF import NetCDFFile from Scientific.IO import NetCDF from Scientific import * from Scientific.IO.NetCDF import * Copy Pasting the exact error message helps tremendously. I've got Scientific,Numeric and numpy installed Are you sure you have them installed successfully? How did you install them? (Precompiled or from source, and if so, with which compiler?) IIRC, Scientific doesn't come with the NetCDF, you have to install the NetCDF library separately. (See http://www.unidata.ucar.edu/software/netcdf/ for download.) After installing the NetCDF library, you might need to reinstall Scientific to get it to recognize the NetCDF install. You might also want to check out http://dirac.cnrs-orleans.fr/mmtk_wiki/WindowsInstallation - strictly speaking, it's installation instructions for MMTK, but you can ignore the final steps of installing MMTK, if you want. If you need further help, you can always try a more specific resource, like the MMTK mailing list - http://starship.python.net/mailman/listinfo/mmtk (MMTK is written by the same person (Konrad Hinsen) as Scientific, and depends on Scientific.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs. Lisp -- please explain
Alexander Schmolck wrote: I wanted to point out that one could with just as much justification claim CL to be more dynamic than python (it is in some regards, but not in others -- how to weight them to achieve some overall score is not obvious. I think it's worth pointing out that not all dynamicism is equal, when it comes to difficulty in compiling to machine code. For example in CL you could just write def foo(x, l=[], N=len(l)): [...] Although computing default arguments at call-time vs. define-time is arguably more dynamic, it really doesn't (appreciably) increase the difficulty in creating machine code. I think (see Caveat) that the one major difference between Lisp and Python that has a major bearing on compilability is mutability. Lisp, like the good functional language that it is, has (primarily) immutable values, and minimal side effects. That is, you can make a function that takes in one value, and outputs a different value, but once you have a handle on a value, that value doesn't ever change. That makes it comparatively easy to track value paths, and assign proper machine code to each operation. Python, on the other hand, is mutable to an absurd degree, with reassignments and side effects galore. Even a relatively simple function like: def f(): act(module.value) random_function() act(module.value) can't be (automatically) replaced with the obvious equivalent: def f(): mv = module.value act(mv) random_function() act(mv) because of the off chance that random_function() will reassign module.value. Even if you look at random_function(), and rule out a change to module.value, there is always a chance that a some other thread will alter module.value in the mean time. Trivial example, true, but when you figure that you can do the same to any operation or builtin function, the compiler is never quite sure what a particular function will do, what side effects it may have, or what type it will return. In order to be ready for any contingency, a compiled Python program will effectively have to incorporate the entire interpreter. C/C++ gets around the mutability issue by straight-jacketing types functions. A variable will only contain a particular type (or a subclass), and a function always has a particular signature. Granted, there are ways of doing heavy duty code analysis, and pinning down functions, types, and side effects in Python, and Psyco/PyPy/ShedSkin are making good strides in that regards. But due to the heavy dependency on mutable objects and side effects in Python, such analysis will never be as easy as with Lisp, and considering Python has had less time, and less investment in those areas, it's no wonder that it's only just now seeing progress on the compiler front. * Caveat: I've never seriously programmed in Lisp, and the last time I looked at it was some time ago, with not-up-to-date reference materials. I might be mistaken about the extent of mutability in current versions of Lisp. Hopefully others with more knowledge can give more accurate details of mutability/side effects in Lisp vis-a-vis ease of compilation. -- http://mail.python.org/mailman/listinfo/python-list
Re: Mutable numbers
Steve Holden wrote: fraca7 wrote: The memory allocation for integers is optimized. 'Small' integers (between -5 and 100 IIRC) are allocated once and reused. The memory for larger integers is allocated once and reused whenever possible, so the malloc() overhead is negligible. The first bit's right, the second bit isn't: id(12100) 4604168 id(121*100) 4604204 FWIW, I read whenever possible not as whenever theoretically possible but as whenever the (comparatively simple) interpreter recognizes that reuse is possible. a = 12100 b = 12100 a is b False def f(): a = 12100 b = 12100 c = 121*100 print a is b print a is c f() True False The interpreter, when compiling the function, can recognize that the two constants are identical, and makes them the same object. On the interactive interpreter, or after a computation, the interpreter doesn't bother to check to see if it already has the same value integer object. (It could, but the overhead would likely swamp any savings.) -- http://mail.python.org/mailman/listinfo/python-list
Re: That's really high-level: bits of beautiful python
Max wrote: But today we were discussing the problem of running externally-provided code (e.g. add-on modules). Neither of us knew how to do it in C, though I suggested using DLLs. However, I quickly installed python on his laptop and coded this: exec import %s as ext_mod % raw_input(Module: ) ext_mod.do() Be careful with this - its fine for developer only use, but I'd avoid it in production code. You leave the possibility for hackers to try to import the module named 'os; os.system('rm -rf /'); import', or other such deviousness. Probably a better version: ext_mod_name = raw_input(Module: ) ext_mod = __import__(ext_mod_name, globals(), locals(), ['__dict__']) ext_mod.do() But granted, it's less cool than the original. P.S. The , globals(), locals(), ['__dict__'] is there so that the proper thing is done when you provide the code with a dotted module name. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3000 deat !? Is true division ever coming ?
Steven D'Aprano wrote: Anybody using Python *should* be aware of the division issue. As soon as they see a division, it is their responsibility to *find out what it means*. That doesn't require much work: they can scroll up to the beginning of the module and look at the first few lines. That's not hard. And anyone wanting strict integer division semantics,(and not needing pre-2.2 compatability) should be using the '//' floor division operator anyway. -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you pronounce 'tuple'?
Erik Max Francis wrote: If a 4-tuple is a quadruple, a 3-tuple is a triple, a 2-tuple is an pair, then I guess a 1-tuple would be a single. Granted that's not nearly as gruesome enough a name to go with the special lopsided Pythonic creature mentioned above. I suggest we name it a hurgledink. +1 QOTW -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3000 deat !? Is true division ever coming ?
Gregory Piñero wrote: On 14 Feb 2006 06:44:02 -0800, [EMAIL PROTECTED] 5./2.=2.5 is floating point math, with all the round off errors that incorporates. Thanks Curtis, I never knew that trick. I guess for variables do have true division you have to make them floats? e.g. float(var1)/float(var2)? Or do you know a less typing approach for that? Google python true division - I'm feeling lucky: http://www.python.org/doc/2.2.3/whatsnew/node7.html From the web page: * By including a from __future__ import division in a module(*), the / operator will be changed to return the result of true division, so 1/2 is 0.5. Without the __future__ statement, / still means classic division. The default meaning of / will not change until Python 3.0. *As the first non-docstring/non-comment line. Note that that's for a module -- the interactive interpreter won't respond the same way to the from __future__ import statement. -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling
Simon Faulkner wrote: Pardon me if this has been done to death but I can't find a simple explanation. I love Python for it's ease and speed of development especially for the Programming Challenged like me but why hasn't someone written a compiler for Python? I guess it's not that simple eh? The simple explanation for the lack of a Python compiler is the massive dynamisism (sp) in Python - since you can change practically everything at any time, in order to compile a generic python program, you have to effectively include the entire interpreter. It's been done before (Python2C was the name, I think), but there wasn't much of a speed-up vs. CPython, and it hasn't been updated to work with recent versions of Python. Recently there has been work on JIT type dynamic compilation techniques, and static compilation of a reduced Python subset. If you want to know more, look up the PyPy project. http://www.codespeak.net/pypy -- http://mail.python.org/mailman/listinfo/python-list
Re: locals() and dictionaries
JerryB wrote: Hi, I have a dictionary, a string, and I'm creating another string, like this: dict = {} dict[beatles] = need str = love mystr = All you %(dict[beatles])s is %(str)s % locals() Why do I get keyerror: 'dict[one]'? Is there a way to reference the elements in a dictionary with locals() or do I need to create a temp variable, like need = dict[one] mystr = All you %(need)s is %(str)s 1) Avoid variable names like 'dict' and 'str'- they cover up the builtin names. 2) When showing error, don't retype - cut and paste: dict[beatles] = need Traceback (most recent call last): File pyshell#6, line 1, in -toplevel- dict[beatles] = need NameError: name 'beatles' is not defined dict['beatles'] = need 3) In string formating, the item in parenthesis, used as a string, is the key for the dictionary. That is: All you %(dict[beatles])s is %(str)s % ld is the same as All you %s is %s % (ld['dict[beatles]'],ld['str']) 4) Your best bet is not to use locals(), but to create a new dictionary with the appropriate keys. E.g.: d = {} d['beatles'] = need s = love d2 = d.copy() d2['str'] = s d['str'] Traceback (most recent call last): File pyshell#24, line 1, in -toplevel- d['str'] KeyError: 'str' d2['str'] 'love' mystr = All you %(beatles)s is %(str)s % d2 print mystr All you need is love -- http://mail.python.org/mailman/listinfo/python-list
Re: beta.python.org content
Paul Boddie wrote: With the nice font they've used, I don't understand why they didn't turn the p into a snake itself. I'm sure I've seen that done somewhere before. You're probably thinking of PyPy: http://codespeak.net/pypy/dist/pypy/doc/news.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
Ivan Voras wrote: It's not a far-out idea. I stumbled about a year ago on a programming language that INSISTED on unicode characters like ≤ as well as the rest of mathematical/logical symbols; I don't remember its name but the source code with characters like that looked absolutely beautiful. Could it be APL? http://en.wikipedia.org/wiki/APL_programming_language Although saying it used Unicode characters is a bit of a stretch - APL predated Unicode by some 30+ years. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
Terry Hancock wrote: One thing that I also think would be good is to open up the operator set for Python. Right now you can overload the existing operators, but you can't easily define new ones. And even if you do, you are very limited in what you can use, and understandability suffers. One of the issues that would need to be dealt with in allowing new operators to be defined is how to work out precedence rules for the new operators. Right now you can redefine the meaning of addition and multiplication, but you can't change the order of operations. (Witness %, and that it must have the same precedence in both multiplication and string replacement.) If you allow (semi)arbitrary characters to be used as operators, some scheme must be chosen for assigning a place in the precedence hierarchy. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about isinstance()
Dave Benjamin wrote: On Thu, 26 Jan 2006, Mr.Rech wrote: Suppose I'm writing a base class with an __eq__ special methods, using isinstance() I would have wrote: class foo(object): ... def __eq__(self, other): return isinstance(other, type(self)) and self.an_attribute == other.an__attribute Now, avoiding isinstace() I've written the following code: class foo(object): ... def __eq__(self, other): try: return self.an_attribute == other.an_attribute except AttributeError: return False You were better off with what you had before. Equality in this case is left completely open-ended, and as a result, there is no way that you can guarantee that a == b is the same as b == a if a is a foo and b is of unknown type. This can lead to bizarre and unpredictable behavior. Mind explaining that better? b == a *always* calls b.__eq__(a), if it exists. What a.__eq__(b) is doesn't matter at that point. So you have the same problems either way. The only difference between the two is in the case where b is of an unrelated class and b.an_attribute exists (1). In this case, the first always returns False, and the second returns (a.an_attribute == b.an_attribute). Which you prefer depends on how strictly you adhere to duck typing. (1) To be honest, they also vary when a.an_attribute is undefined. The second always returns False, and the first raises an AttributeError. -- http://mail.python.org/mailman/listinfo/python-list
Re: beta.python.org content
Peter Maas wrote: - The logo does indeed resemble a cross. How about rotating it at 45 deg to make it look like an x? Or give it a circular shape? Please note that there are no religious motives in this remark :) It looks like a plus sign to me. Do you also advocate renaming C++ to Cxx or C (circular shape) (circular shape)? Also note that if you made it more of a circular shape, it might resemble a Ying-Yang symbol, and we would offend the anti-Daoist programmers. ;-) (Not that I like the logo, mind you. I just think that looking like a cross is a poor reason to bash it.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about isinstance()
Mr.Rech wrote: All in all it seems that the implementation that uses isinstance() is better in this case... Well what's better depends on what you want to happen when you compare an unrelated class that also defines 'an_attribute'. Unlike in statically typed languages, certain things are made easier when you don't check for strict inheritance (like mock and proxy objects). Google Duck Typing for more info. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
Giovanni Bajo wrote: Robert Kern wrote: I can't find ?, ?, or ? on my keyboard. Posting code to newsgroups might get harder too. :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
Robert Kern wrote: Rocco Moretti wrote: [James Stroud wrote:] I can't find ?, ?, or ? on my keyboard. Posting code to newsgroups might get harder too. :-) His post made it through fine. Your newsreader messed it up. I'm not exactally sure what happened - I can see the three charachters just fine in your (Robert's) and the original (Christoph's) post. In Giovanni's post, they're rendered as question marks. My point still stands: _somewere_ along the way the rendering got messed up for _some_ people - something that wouldn't have happened with the =, = and != digraphs. (FWIW, my newsreader is Thunderbird 1.0.6.) -- http://mail.python.org/mailman/listinfo/python-list
Re: list(...) and list comprehensions (WAS: Arithmetic sequences in Python)
Antoon Pardon wrote: Well we could have list(a) return [a], and have a list_from_iterable. Although I would prefer a different name. Or reverse it - list() always takes a single iterable, and list_from_scalars() is defined something like follows: def list_from_scalars(*args): return list(args) print list_from_scalars(1,2,3) [1, 2, 3] print list_from_scalars('a') ['a'] -- http://mail.python.org/mailman/listinfo/python-list
Re: making objects unassignable read-only (especially when extending)
Johannes Zellner wrote: Hi, can I make an object read-only, so that x = new_value fails (and x keeps it's orginal value)? Simon gave you a way of doing it when x is an attribute access (e.g. p.x). I am unaware of a way of doing it when x is a straight global or local. Unlike other languages like C, the object pointed to by a variable is in no way involved in the assignment process. Variables are just labels (sticky notes) attached to objects. Assignment is moving of the label - this only involves the interpreter, and the object currently labeled by the variable is not consulted. If you haven't seen it before, http://starship.python.net/crew/mwh/hacks/objectthink.html is a good read. Note that Simon's trick works not because it changes the object pointed to by the variable, but because it changes the properties of the namespace where that variable lives (the p in the p.x). To do so for a local or a global variable would require changing the local global namespaces - i.e. rewriting the interpreter. -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: excellent book on information theory
Alex Martelli wrote: Terry Hancock [EMAIL PROTECTED] wrote: ... due to the Evil Conspiracy of region-coding, I couldn't watch the British DVD even if I were to import it (Well, yeah I could, but it would be painful, and probably illegal, I have a region-free DVD player here in CA -- N.B.: CA, in addition to being the postal abbreviation for the US state of California, is also the the two-letter country code for Canada. In an international forum such as this, confusion may result, especially as Legal in California and Legal in Canada are slightly different. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decimal ROUND_HALF_EVEN Default
LordLaraby wrote: If 'bankers rounding' is HALF_ROUND_EVEN, what is HALF_ROUND_UP? I confess to never having heard the terms. There was a Slashdot article on rounding a short while back: http://developers.slashdot.org/article.pl?sid=06/01/05/1838214 -- http://mail.python.org/mailman/listinfo/python-list
Re: New Python.org website ?
Roy Smith wrote: Steve Holden [EMAIL PROTECTED] wrote: http://beta.python.org All I can say is, Wow!. If nothing else, it will forever eliminate the idea that the web site doesn't look professional. It's almost *too* slick. I agree with the too slick impression. The learn why pictures particularly unnerve me. It looks like a marketing team with a focus group got ahold of the website. Great for reaching the PHB crowd. I'm not sure what J. Random Hacker will think though. -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting milliseconds to human amount of time
Max wrote: Harlin Seritt wrote: How can I take a time given in milliseconds (I am doing this for an uptime script) and convert it to human-friendly time i.e. 4 days, 2 hours, 25 minutes, 10 seonds.? Is there a function from the time module that can do this? Thanks, Harlin Seritt seconds = millis / 1000 # obviously minutes = seconds / 60 seconds %= 60 hours = minutes / 60 minutes %= 60 days = hours / 24 hours %= 24 All this using integer division, of course. This is probably much more verbose than the tersest soln, but it works (or should do - I haven't tested it). It's not strictly accurate (from a scientific/UTC perspective, as some minutes have 59 or 61 seconds rather than 60, but it's probably the best you need. You'd probably be helped by divmod: help(divmod) Help on built-in function divmod in module __builtin__: divmod(...) divmod(x, y) - (div, mod) Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x. def humanize(milli): sec, milli = divmod(milli, 1000) min, sec = divmod(sec, 60) hour, min = divmod(min, 60) day, hour = divmod(hour, 24) week, day = divmod(day, 7) print week, weeks,, day, days,, hour, hours,, \ min, minutes,, sec, seconds, and, \ milli, milliseconds return (week, day, hour, min, sec, milli) humanize(1234567890) 2 weeks, 0 days, 6 hours, 56 minutes, 7 seconds, and 890 milliseconds (2, 0, 6, 56, 7, 890) humanize(694861001.1) #Also works with floats! 1.0 weeks, 1.0 days, 1.0 hours, 1.0 minutes, 1.0 seconds, and 1.1002384 milliseconds (1.0, 1.0, 1.0, 1.0, 1.0, 1.100238418579) -- http://mail.python.org/mailman/listinfo/python-list
Re: inline function call
Riko Wichmann wrote: hi everyone, I'm googeling since some time, but can't find an answer - maybe because the answer is 'No!'. Can I call a function in python inline, so that the python byte compiler does actually call the function, but sort of inserts it where the inline call is made? Therefore avoiding the function all overhead. The cannonical answer is you probably don't need to do that. If you're still set on inlining functions, take a look at bytecodehacks: http://bytecodehacks.sourceforge.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: One-step multiples list generation?
Rocco Moretti wrote: Damien Wyart wrote: * Efrat Regev [EMAIL PROTECTED] in comp.lang.python: Suppose I have some non-numerical Foo and would like to create a list of 20 Foo-s. Is there a one-step method (not a loop) of doing so? Maybe : [ Foo ] * 20 or, more verbose, [ Foo for _ in range(20) ] If Foo is mutable, keep this in mind: a = [ [] ]*20 # A list of 20 empty lists print id(a[0]) == id(a[1]) True a[0].append(1) print a [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1]] b = [ [] for _ in range(20) ] # A list of 20 empty lists print id(b[0]) == id(b[1]) False b[0].append(1) print b [[1], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []] Oh, but also: Foo = [] c = [ Foo for _ in range(20) ] # A list of 20 empty lists print id(c[0]) == id(c[1]) True c[0].append(1) print c [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1]] (The difference with the 'b' case is that a new list is created each time around, in the other cases, the same list is reused. -- http://mail.python.org/mailman/listinfo/python-list
Re: One-step multiples list generation?
Damien Wyart wrote: * Efrat Regev [EMAIL PROTECTED] in comp.lang.python: Suppose I have some non-numerical Foo and would like to create a list of 20 Foo-s. Is there a one-step method (not a loop) of doing so? Maybe : [ Foo ] * 20 or, more verbose, [ Foo for _ in range(20) ] If Foo is mutable, keep this in mind: a = [ [] ]*20 # A list of 20 empty lists print id(a[0]) == id(a[1]) True a[0].append(1) print a [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1]] b = [ [] for _ in range(20) ] # A list of 20 empty lists print id(b[0]) == id(b[1]) False b[0].append(1) print b [[1], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []] -- http://mail.python.org/mailman/listinfo/python-list
Re: deal or no deal
rbt wrote: The TV show on NBC in the USA running this week during primetime (Deal or No Deal). I figure there are roughly 10, maybe 15 contestants. They pick a briefcase that has between 1 penny and 1 million bucks and then play this silly game where NBC tries to buy the briefcase from them while amounts of money are taken away from the list of possibilities. The contestant's hope is that they've picked a briefcase with a lot of money and that when an amount is removed from the list that it is small amount of money not a large amount (I categorize a large amount to be more than 100,000) Well, if the contestants' choices are truly random, and they stick with their first choice all the way to the end, each contestant wins, on average, $131 477.54 (sum(amounts)/len(amounts)). Assuming that the buyout offer is always less than (or equal to) the average of the still-available amounts, NBC will (on average) never have to pay out more than ~$132k per contestant. Likely they'll pay out less, because most people will get nervous before the very end, and will take the low ball offer NBC is fronting. What I would really like to know, is how they calculate the offer. Obviously, they set the upper limit at the average of the still standing offers, but I wonder if and how they take subsequent rounds into consideration. Is there a Monty Hall (http://en.wikipedia.org/wiki/Monty_Hall_problem) type consideration that needs to be taken into effect as cases are eliminated? -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido at Google
Jack Diederich wrote: On Wed, Dec 21, 2005 at 01:36:42PM -0500, rbt wrote: Alex Martelli wrote: I don't think there was any official announcement, but it's true -- he sits about 15 meters away from me;-). For Americans: 15 meters is roughly 50 feet. Right, so that is about three and a half stone? Stone is a measure of weight, not distance. (14 pounds, ~6.35 kg) 15 meters (150 decimeter, 1500 cm, etc ...) 590 inches 49 feet 16 yards 0.0093 miles 0.008 nautical miles 3 rods 0.075 furlongs 1800 barleycorns 147.63 hands 66 spans 33 cubits 13 ells 8.2 fathoms 75 links 0.75 chains 0.0027 leauges 0.03 li 0.081 stadia 4.8e-16 parsecs 1e-10 astronomical units 5e-8 lightseconds 2.8e11 Bohr radiuses 9.2e35 Plank lenghts and probably most appropriately (being dutch): 1.5 roede In other words a stone's throw away. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why and how there is only one way to do something?
[EMAIL PROTECTED] wrote: Chris Mellon wrote: Any time you want to write something in any way other than the obvious way, ask yourself why? Is it more obvious *to you*, which is a good reason as long as you're only writing code for yourself? Or is it just to be different, or because you think it'll be faster, or just because the slickness of it appeals to you? The point is again, obvious is not so obvious sometimes. You seem to be assuming that anyone that use style different from you is intentionally doing it and that your style would first come to their mind but they don't use it, for the sake of proving that they are smart. My take on it is that obvious is intended to be prescriptive, not descriptive. (Note that in the Zen it is phrased There *should* be ) It describes what Python aspires to, not what it is. If the currently preferred method is not the one obvious way, steps should be taken to make the preferred way the obvious way (i.e. the way that you reach for first, when you want to do it). Keep in mind that the Zen was written at a time when there was a certain amount of Perl vs. Python deathmatch feeling in the air. That line in the Zen was a reaction to Perl's There's more than one way to do it (TMTOWTDI). Perl took the view that flexibility was a virtue to be praised above all others, and allows and encourages (or at least used to) different ways of doing things. I don't think a syntactic construct was excluded from Perl for the sole reason well, we already can do that with this construct ... Python, in part due to a backlash to the Perl philosophy, emphasized clarity and readability. There are *many* constructs which have been excluded from Python just because they weren't any clearer than what is already in the language. (Once a language is Turing complete, anything you can program a computer to do, you can use that language to do. There is no guarantee that it's short or pretty, though.) That's what the one obvious way refers to - the clearest, most readable way of expressing what you want to accomplish. In this obviousness, there is (often) little consideration for what other languages you previously might have used, or might be trying to drag idioms from. As an absurd analogy, if you were born and grew up in a country with a crazed totalitarian leader who, under penalty of death, made you turn around three times while hopping and whistling the national anthem before you sat down for dinner, it might be obvious to you that one must turn around three times, hopping and whistling before sitting down for dinner. However, if you move out of that country to, say, the Netherlands, for instance, you no longer need to hop-whistle-turn, and your new countrymen will look at you strangely if you do. That's not to say you can't hop-whistle-turn if the fancy strikes you, but in any practical setting, people will expect you do the simple, obvious thing -- just sit. BTW. People who are quick to bring up the Zen (and I'm as guilty as others at times) should also keep in mind that the Zen is found under the *humor* section of the Python website. It's not an actual design document, it's just a surprisingly intuitive description of Python's nature. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to find the type ...
[EMAIL PROTECTED] wrote: thisisastring = 1 thisisanint = 1 type(thisisastring) type 'str' type(thisisanint) type 'int' thisisastring = int(thisisastring) thisisanint = str(thisisanint) type(thisisastring) type 'int' type(thisisanint) type 'str' print repr(thisisastring) 1 print repr(thisisanint) '1' thisisastring = 'a' thisisanint = 98 thisisastring = ord(thisisastring) #Using ASCII rep. thisisanint = chr(thisisanint) type(thisisastring) type 'int' type(thisisanint) type 'str' print repr(thisisastring) 97 print repr(thisisanint) 'b' -- http://mail.python.org/mailman/listinfo/python-list
Re: Bitching about the documentation...
Fredrik Lundh wrote: Rocco Moretti wrote: Insert punctuation capitalization to make the following a correct and coherent (if not a little tourtured). fred where guido had had had had had had had had had had had a better effect on the reader punctuation, including quote marks, I presume? Quote marks are acceptable, but no more than two words are inside each set. B A D G E R . . . E R S P O I L E R W A R N I N G The accepted way to do it is: Fred, where Guido had had had, had had had had. Had had had had a better effect on the reader. meaning approximately In the place where Guido previously put the word had, Fred had previously put the phrase had had. Fred's choice of phrasing was more appreciated by the reder. -- http://mail.python.org/mailman/listinfo/python-list
Re: Documentation suggestions
A.M. Kuchling wrote: There's another struggle within the LibRef: is it a reference or a tutorial? Does it list methods in alphabetical order so you can look them up, or does it list them in a pedagogically useful order? I think it has to be a reference; if each section were to be a tutorial, the manual would be huge. Here I think the solution is to encourage separate tutorials and HOWTOs, and link to them from the LibRef. I actually like the conversational, tutorial style the current LibRef has -- in fact I consider that style one of the Python Docs strengths. All too often I see manuals that consist of only fuction by fuction class by class breakdowns. That's fine if the module is just a collection of independant functions, but falls short whenever you want to use multiple functions classes in a module together. Function by function documentation tends to ignore the big picture, how all the functions classes work together, and the philosophy behind their use. *That's* what I feel it is important to document - if I want to know parameters, return values and side-effects, I'll just look at the doc strings. Certainly you could go for the User Manual/Reference Manual dichotomy, but in my experience, the User Manual tends to get short shrift - the experts writing it tend to think that it's just for n00bs, and leave out the complex and esoteric items, thinking that the Reference Manual suffices. Unfortunately, the background and philosophy are needed *more* for the complex/esoteric functions than for the simple ones, merely because you're less likely to understand them from a takes a,b,c, sets the froz flag, and returns x,y,z type description. And to expand on what Michael Spencer said, a lot of the time when I'm digging throught the LibRef, I'm looking for a module that'll help me do 'X'. Most of the Reference Manuals I've seen tend to assume you know what fuction you're looking for, and don't give you any direction in the forest of function descriptions. With the current tone/level and categorical grouping of the LibRef, it's easy to browse through and look for things that might help (at least easier than it would be with, say, a strict alphabetical list). -- http://mail.python.org/mailman/listinfo/python-list
Re: Bitching about the documentation...
One of my favourite examples of obfuscated English is this grammatically correct sentence: Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo. The punctuation is important. Reminds me of this old classic: Insert punctuation capitalization to make the following a correct and coherent (if not a little tourtured). fred where guido had had had had had had had had had had had a better effect on the reader -- http://mail.python.org/mailman/listinfo/python-list
Re: python university search
josh wrote: hello, i am interested in doing an undergraduate major in computer science that mainly focuses on python as a programming language.. It's your life, so you can live it as you choose, but I think you're missing the point of an undergraduate education if you focus too much on Python programming at this point. Undergraduate education is (should be) about breadth. Python has a place there, but it isn't the be-all, end-all. There are some concepts for which Python isn't well suited in teaching (functional programing, logic programing, operating system programing, etc.). I'd hope that you go to a high-quality University that understands this, and teaches *concepts*, not programing languages. In the long run, it will (likely) be better for you to go to a University where they don't even use Python, but solidly teach concepts, rather than one that's so into Python that they neglect topics that are taught poorly in Python. Even if you never use Python as an undergraduate, if you have a good grounding in the fundamental concepts, it should be (relatively) easy for you to take what you've learned in (scheme/ML/prolog/assembly/forth) and apply it to Python. You'll have plenty of time to specialize on Python as a graduate student/young professional. Just my two cents. -- http://mail.python.org/mailman/listinfo/python-list
Re: General question about Python design goals
Fredrik Lundh wrote: Rick Wotnaz wrote: I'm sure Antoon wouldn't object if lists were to be allowed as dictionary keys, which would eliminate the multiple castings for that situation. I wouldn't, either. so what algorithm do you suggest for the new dictionary im- plementation? devil's_advocate One option is to create a new frozen list type, a` la frozen sets. People who argue that frozen list is not needed because we already have the tuple type, while simultaneously arguing that tuples shouldn't grow list methods because they are conceptually different from lists will be bludgeoned to death with a paradox. :) /devil's_advocate -- http://mail.python.org/mailman/listinfo/python-list
Re: General question about Python design goals
Fredrik Lundh wrote: Rocco Moretti wrote: I'm sure Antoon wouldn't object if lists were to be allowed as dictionary keys, which would eliminate the multiple castings for that situation. I wouldn't, either. so what algorithm do you suggest for the new dictionary im- plementation? devil's_advocate One option is to create a new frozen list type, a` la frozen sets. doesn't frozenset make a copy? As does the current cast as tuple technique. (I'm certainly not advocating it, but ...) Certain implementations of frozen list could possibly do the list-frozenlist conversion without a copy. (e.g. by flipping an immutable bit) http://www.python.org/peps/pep-0351.html This PEP describes a simple protocol for requesting a frozen, immutable copy of a mutable object. Perhaps Barry has been borrowing Guido's time machine? -- http://mail.python.org/mailman/listinfo/python-list
Re: Which License Should I Use?
Steven D'Aprano wrote: On Fri, 25 Nov 2005 11:30:46 -0800, mojosam wrote: I guess I don't care too much about how other people use it. Then probably the best licence to use is just to follow the lead of Python. For that sort of small program of limited value, I put something like this in the code: Copyright (c) 2005 Steven D'Aprano. Released under the same license as used by Python 2.3.2 itself. See http://www.python.org/psf/license.html for details, and http://www.python.org/2.3.2/license.html for the full text of the license. Gaak! No! The Python license you point to contains horrible amounts of cruft due to the ownership ping-pong game. (And just using the hyperlink like you did leaves it vauge as to who is doing the liscensing - Steven D'Aprano? the PSF? BeOpen? CNRI? Stichting Mathematisch Centrum?) As I understand it, the PSF's official position is that the Python license (even just the top most one) is not appropriate for any program besides Python itself. http://wiki.python.org/moin/PythonSoftwareFoundationLicenseFaq Note that the Python license is not even appropriate for third party code that's intended to be contributed to the Python standard library or core! If you want a like Python license, try the MIT or new-BSD license instead: http://www.opensource.org/licenses/mit-license.php http://www.opensource.org/licenses/bsd-license.php -- http://mail.python.org/mailman/listinfo/python-list
Re: Which License Should I Use?
mojosam wrote: I've been watching the flame war about licenses with some interest. There are many motivations for those who participate in this sector, so disagreements over licenses reflect those agendas. One point that frequently gets ignored in licensing debates: The value of a license is directly proportional to the amount of time, effort, and money you are willing to spend enforcing it. It doesn't matter how fancy the legal wording is - it is up to you, as the copyright holder, to bring legal action against infringers (or at least send a cease-and-desist letter). If you're not going to bother, any and all clauses in the license, no matter how artfully crafted, won't do you any (legal) good. People using your program are left acting on the honor system. Which may be just fine - but you don't need a fancy, legalistic license to accomplish that. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Fwd: Re: hex string to hex value]
tim wrote: ok, but if i do n=66 m=hex(n) m '0x42' h=int(m,16) h 66 I end up with 66 again, back where I started, a decimal, right? I want to end up with 0x42 as being a hex value, not a string, so i can pas it as an argument to a function that needs a hex value. (i am trying to replace the 0x42 in the line midi.note_off(channel=0, note=0x42) with a variable) note = 0x42 print note 66 note is 66 True There is no such thing as a hex value- only hex *representations* of a value. midi.note_off() doesn't take a hex value, it takes an integer, and, for whatever reason, it happens to be listed in your example in a hexidecimal representation. -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for adding symbols within Python
Pierre Barbier de Reuille wrote: Rocco Moretti a écrit : [...] I did, but I still don't see why it is an argument against using strings. The point you may not appreciate is that (C)Python already uses strings to represent names, as an important part of its introspective abilities. Well, I'm well aware of that, but I'm also well aware that's (as you said yourself) specific to C-Python, so can just *cannot* rely on strings being used as symbols in the language. It's true that a different implementation of Python may use a different internal storage system for names, but as long as the semantics are the same as CPython, it really doesn't doesn't matter what the internal storage is. That is to say, as long as the other implementation of Python has __getattr__ and __dict__, you can use strings to represent names, regardless of how the interpreter stores them internally. The point is, why don't provide the programmer to express just what he needs (that is, some symbolic value like opened, blocked, ...) and let the interpreter use whatever he think is more efficient for him ? It's just that, for the current interpreters and usage of symbol-like construct, the efficiency gained by the interpreter choosing how to represent symbols is probably *far* outweighed by the inefficiency and hassle of implementing and maintaining the symbol syntax in the existing interpreters. Besides, have the programmer specify intent, and allow the interpreter to substitute a more efficient implementation on the off chance that interpreter can or wants to doesn't have much cache in the Python community.(1) The interpreter could get more efficiency if it knew a list was fixed length, or contained only ints, or knew that a for loop was looping over consecutive integers, instead of a random list. But despite the possibility that there might exist, at some time in the future, a Python interpreter which *might* optimize such things, we haven't thrown in variable declarations or integer loop syntaxes yet. As I've mentioned before, the key to getting feature put into the language is compelling use cases. Find a (non-hypothetical) Python program or library which would be improved by addition of insert your chosen feature here, and where the existing alternatives are inadequate. Lacking that, any attempt to get a feature into the language is an uphill battle. But why say a name is a *string* when it is just an implementation detail ??? Isn't Python mainly about allowing the programmer to concentrate on important stuff ? One could flip it around and say that names *not* being strings are an implementation detail - after all, what is a name in your source code, besides just a string of ASCII characters? Having just names and strings simplifies things as well - you have only two items to convert between, as opposed to three items (names, symbols and strings). - (1) The future of Python seems to be towards the PyPy way, where the interpreter will analyze your code, and automagically determine the most efficient implementation for your particular use case. -- http://mail.python.org/mailman/listinfo/python-list
Re: is parameter an iterable?
marduk wrote: On Tue, 2005-11-15 at 11:01 -0800, py wrote: I have function which takes an argument. My code needs that argument to be an iterable (something i can loop over)...so I dont care if its a list, tuple, etc. So I need a way to make sure that the argument is an iterable before using it. I know I could do... def foo(inputVal): if isinstance(inputVal, (list, tuple)): for val in inputVal: # do stuff ...however I want to cover any iterable since i just need to loop over it. any suggestions? You could probably get away with if hasattr(inputVal, '__getitem__') No, you probably couldn't. ## def g(s): for i in xrange(s): yield i+s m = g(5) hasattr(m, '__getitem__') False ### I'd do something like: # def foo(inputVal): try: iter(inputVal) # Can you change it into an interator? except TypeError: # Return Error Code else: for val in inputVal: # do stuff ### Again, you'll have to be careful about strings. -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for adding symbols within Python
Björn Lindström wrote: Steven D'Aprano [EMAIL PROTECTED] writes: Why does the byte string \x6f\x70\x65\x6e\x65\x64 have intrinsic meaning when the int 0 doesn't? It certainly doesn't mean anything to non-English speakers. If all you want is human readable byte strings, then just use them: class MyFile: def open(self): self.state = opened def close(self): self.state = closed So, I guess no one read my explanation of why this an issue about more than implementing enums (which is fairly trivial, as we have seen). I did, but I still don't see why it is an argument against using strings. The point you may not appreciate is that (C)Python already uses strings to represent names, as an important part of its introspective abilities. ## import dis def f(): module.klass.method() dis.dis(f) 2 0 LOAD_GLOBAL 0 (module) 3 LOAD_ATTR1 (klass) 6 LOAD_ATTR2 (method) 9 CALL_FUNCTION0 12 POP_TOP 13 LOAD_CONST 0 (None) 16 RETURN_VALUE f.func_code.co_names ('module', 'klass', 'method') type(f.func_code.co_names[1]) is type('a') True ## I'll let you dig through the interpreter source to convince yourself that, indeed, the names module, klass, and method are stored internally as true python strings. The same holds for other namespaces - the names are stored as real python strings, in a real python dictionary. class c: def foo(self): pass def bar(self): pass def baz(self): pass type(c.__dict__) is type({}) True c.__dict__.keys() ['baz', '__module__', 'foo', 'bar', '__doc__'] type(c.__dict__.keys()[0]) is type('a') True ## P.S. This may change for other implementations of Python, but the fact remains - there is less difference between names and strings than you may first think. -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for adding symbols within Python
Pierre Barbier de Reuille wrote: Please, note that I am entirely open for every points on this proposal (which I do not dare yet to call PEP). I still don't see why you can't just use strings. The only two issues I see you might have with them are a) two identical strings might not be identical by id(), b) they aren't local in scope. The objection a) is minor. One, all of your examples use equality for testing already, and two, short strings are interned and identical in most cases anyway (they only differ if you go to lengths to create them, or they aren't sufficiently variable like) - at most you would have to standardize the rules. The objection b) is a little harder to dismiss. But I'm not sure if you've completely thought what it means for a symbol to be local to a module. What happens when you assign a variable containing a symbol to a variable in another module? For that matter, what does it mean to be in a module. Which module is a class instance (and associated sybols) in if the class is defined in one module, instantiated in another, and then passed as a return value to a third? What about from ... imports? If you need a symbol from another class what's the mechanism of obtaining it? Can you import symbols? Since you advocate storing symbols internally as integers, I suppose you would have a program-global table to keep symbols from different modules from having the same internal representation. How do you pickle a symbol and have it go to a different Python program, which may have a massive symbol table of it's own? It's been said before, and I'll say it again - the key to successful Python language changes is compelling use cases. Find an existing Python program or library (the stdlib is best) which would be markedly improved by your language change. Not only will Guido be more likely to be convinced, but what you're proposing will likely be clearer to everyone else, if it's grounded in practical use cases. -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] Map of email origins to Python list
Paul McGuire wrote: Claire McLister [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] We've been working with Google Maps, and have created a web service to map origins of emails to a group. As a trial, we've developed a map of emails to this group at: http://www.zeesource.net/maps/map.do?group=668 This represents emails sent to the group since October 27. Would like to hear what you think of it. -- sigh Another sleepless camera pointed at the fishbowl that is my online life. It's also a testament to the limited value of physically locating people by internet addresses - If you zoom in on the San Fransico bay area, and click on the southern most bubble (south of San Jose), you'll see the entry for the Mountain View postal code (94043) - a massive list which contains mostly gmail.com accounts, but also contains accounts with .de .ca .uk .pl .it .tw and .za domains. I doubt all of the people in that list live in sunny California, let alone in Mountain View proper. -- http://mail.python.org/mailman/listinfo/python-list
Re: Map of email origins to Python list
[EMAIL PROTECTED] wrote: Rocco Moretti wrote: It's also a testament to the limited value of physically locating people by internet addresses - If you zoom in on the San Fransico bay area, and click on the southern most bubble (south of San Jose), you'll see the entry for the Mountain View postal code (94043) - a massive list which contains mostly gmail.com accounts, but also contains accounts with .de .ca .uk .pl .it .tw and .za domains. I doubt all of the people in that list live in sunny California, let alone in Mountain View proper. North of that bubble is a second massive list also labeled Mountain View 94043. I found my name on that list and I live in the Chicago area. Moutain View is, perhaps, where aol.com is located? These bubbles are showing the location of the server that's registered under the domain name? Actually, it looks like they are the *same* list. I haven't gone through all of the names, but I spot checked a few, and it looks like yours, among others, are listed in both spots. (The southern one looks like it is a mislocated duplicate, as it is nowhere close to Mountain View, and is stuck in the middle of a golf course.) -- http://mail.python.org/mailman/listinfo/python-list
Re: I Need Motivation Part 2
[EMAIL PROTECTED] wrote: i m losing my motivation with python because there are sooo many modules, that i cant just learn them all, As other's have said, don't bother. If you ever need to use a module that you don't know, just go to http://docs.python.org/lib/lib.html (easily accessable from the Documentation link on the Python Home page), or a local copy, and scrounge around. I might suggest skimming it once, to see what is possible, but it isn't nessasary to learn it. -- Knowing that there is a Python module in the standard library to do CSV/Date manipulation/MD5/etc is sufficient. You don't even need to know what the module is called - a minute skimming the TOC will point you in the right direction. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's website does a great disservice to the language
Alex Martelli wrote: The Eternal Squire [EMAIL PROTECTED] wrote: ... 2) Consider what he really wants for a supervisor of software engineers. Ideally such a person should be a software engineer with at least 3 times the experience of the most junior member. Such a I like the general idea but not your formula. If the most junior team member was 1 month out of school, would it really be OK for the supervisor to be somebody who graduated 3 months ago?-) FWIW, when I read it, I took experience as a semi-qualitative measure, more than just time since graduation. Hence someone out of school only three months could have more experience, than someone who has worked for ten years, if the recent grad has been heavily involved in pre-graduation projects (e.g. open source), or if the ten-year veteran has done nothing constructive with his time, besides raking in a paycheck. -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggestion for (re)try statement
Sori Schwimmer wrote: 0) Sorry, I don't know how to post a reply in the same thread. Usually it is simply hitting the Reply button/link/key combination on your mail/news reader when the post you want to reply to in view. (If you want reply to multiple people, you can always reply to the original post, or reply to one, and just treat the topics from all of them.) 2) Rocco Morreti wrote: First off, let me say that my message wasn't meant to scare you off - it was constructive criticism, appraising you of what would be necessary if you actually want the construct in the language. If you're just shooting the breeze/navel gazing, I apologize for harshing your cool. What is so repugnant about the equivalent, currently valid way of writing it? Nothing repugnant. Repugnant was probably too strong a word. The point I was trying to make was: If you want such a construct added to the language, you need to justify all the hassle effort of introducing the new syntax. Given that there is a way to accomplish the same thing now, you would need to show that your way is not just as good, but better than the current way. It's all about convenience, not about getting to bare bone equivalents. Nothing wrong with convenience - you just have to show that the convenience would be used often enough to justify the hassle. It'd be awfully convenient to have a passenger jet parked in your garage - but you probably wouldn't use it frequently enough to justify the expense of maintaining, fueling, and licensing it. And remember - your goal isn't ultimately to convince me or someother person on comp.lang.python, it's to convince Guido I'm not trying to convince anybody. In the democratic state-of-mind in which I live, the idea will be taken in consideration if it is found useful by many, not by one, even if the one is the almighty Guido. My comment made with the assumption that you were trying to actively promote the construct, rather than floating it as a trial balloon. I was aiming at keeping you from getting annoyed later on when your petition with hundreds of signatures gets shot down by Guido. Despite your state-of-mind, in practicality, Python is not a democracy - language constructs live or die by the will of Guido. If you actually want the construct in the language, a comp.lang.python plebiscite isn't going to do it - you'll need to convince the BDFL that it's a good idea. Now, Guido isn't totally ambivalent to the masses - if a large number of people are for it, there's a good chance Guido will be for it too. But you're not aiming for a popularity contest - what'll convince people (including Guido) is good arguments as to *why this construct is better than what we have now,* and *why it will be worth the hassle of implementing and maintaining it*. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's website does a great disservice to the language
[EMAIL PROTECTED] wrote: So the first thing you do when you go to a web page is to google if they are going to redesign it? I think the implication was The first thing to do before *suggesting that a redesign is nessasary* is to Google to see if such a redesign is taking place. -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggestion for (re)try statement
Sori Schwimmer wrote: Hi, I think that would be useful to have an improved version of the try statement, as follows: try(retrys=0,timeout=0): # things to try except: # what to do if failed and having the following semantic: for i in range(retrys): try: # things to try except: if i retrys: i += 1 sleep(timeout) else: # what to do if failed else: break The gold standard for language syntax changes is compelling use cases - if introduced, how often will the construct be used? Is there a python program out there (preferably in the standard library) which would be *markedly* improved by the change? What is so repugnant about the equivalent, currently valid way of writing it? -- Hypothetical and theoretical arguments don't carry much weight in the Python community (Practicality beats purity and all that.) And remember - your goal isn't ultimately to convince me or someother person on comp.lang.python, it's to convince Guido. -- http://mail.python.org/mailman/listinfo/python-list
Re: Yes, this is a python question, and a serious one at that (moving to Win XP)
James Stroud wrote: I propose that any time anyone suggests switching to Windows, the reasons for such should be explicitly described, and not left to interpretation. I propose that any time anyone suggests switching to Linux ... I propose that any time anyone suggests switching to Mac ... I propose that any time anyone suggests switching to Ruby ... I propose that any time anyone suggests switching to Firefox ... I propose that any time anyone suggests switching to Waxed Dental Floss ... People should not feel *required* to justify their decisions to c.l.py, especially if they are not trying to evangelize that choice. (FWIW, even from the original post it's very apparent that he's dissuading people from joining him.) It is true that giving the reasons for a choice will help responders put some perspective on it, and perhaps prompt a few alternatives, but c.l.py is not your mother, and shouldn't require you to justify the validity of your lifestyle to it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Very dumb question
Laszlo Zsolt Nagy wrote: Laszlo Zsolt Nagy wrote: I have a program with this code fragment: print len(data) print data[:50] raise SystemExit This prints: 20381 !DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.1//EN But if I change 50 to 51 print len(data) print data[:51] raise SystemExit then it prints 20381 !DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.1//EN After all, only the last 50 bytes are printed. The string is the same (length 20381) in both cases. Hmm, I checked on Windows now and it is working. But it is bad on FreeBSD/Python 2.4.1 Very strange. len(data[:100]) returns 100, but if I try to print it, only the first 50 characters printed. Les Is 'data' a Unicode string, or do you have some terminal control charachters in the string? Most printable ASCII charachters are between 32 and 126. What does this print?: print [i for (i,c) in enumerate(data) if not (32 = ord(c) = 126)] -- http://mail.python.org/mailman/listinfo/python-list
Re: When someone from Britain speaks, Americans hear a Britishaccent...
Duncan Smith wrote: Steve Holden wrote: There are special rules for the monarchs, who are expected to refer to themselves in the first person plural. Yes, although I'm not actually sure where the 'royal we' comes from; I was under the (probably misinformed) impression that since the King/Queen is the representative of the entire nation, they use the first person plural, because when they speak they speak for the all the (multiple) people in the land. I'm unaware of what term a monarch uses in a private, rather than public, context. (Never having had the opportunity to drink a pint with Lizzie, Chuck, and Cammie. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: When someone from Britain speaks, Americans hear a British accent...
Steve Holden wrote: On Fri, 07 Oct 2005 00:33:43 -, Grant Edwards [EMAIL PROTECTED] wrote: For example: In British English one uses a plural verb when the subject consists of more than one person. Sports teams, government departments, states, corporations etc. are grammatically plural. In American, the verb agrees with the word that is the subject, not how many people are denoted by that word. There aren't any universal rules, except possibly British people speak English while Americans don't. I believe you overgeneralize. :) A Welshman would likely be offended if you implied he spoke English, and the Scots are notorious for only speaking English when they have too. (I remember a news story some years back about a Scottish lad who was fined/imprisoned for replying to an official court representative with Aye rather than Yes.) For that matter there are plenty of people in Cornwall and even in London (Cockney) who speak something that is only called English for lack of a better term. -- http://mail.python.org/mailman/listinfo/python-list
Re: Reply-To header
Roel Schroeven wrote: Peter Decker wrote: On 10/3/05, Roel Schroeven [EMAIL PROTECTED] wrote: On lists like this, where everyone benefits by sharing information, it seems pretty lame to hide behind purist arguments about Reply-To: headers. The default behavior should be the one most useful to the list. Think for a moment how many useful bits of information you've missed because the default for this list it to make conversations private. The default of this list is not to make conversations private; in fact the list doesn't have any default. It's you who chooses to send replies to the original author, to the list, or both, by choosing which button to press in your mail client. It's a sad but unavoidable fact that most people, in the regular course of emailing, never use (nor have reason to use) the reply to all button. In any normal email exchange, hitting the reply button does what you want it to. As a consequence of this, a large portion of the e-mail using public never thinks to do more than hit the reply button. It's great that *you* and *I* are technically savvy enough to hit the reply all/list button when needed, but the other people on the list might not be. I've seen mailing lists reduced to near uselessness because of it: you get people posting questions to the list, but no replies, because all of the people replying are responding by pressing reply and sending private messages. FWIW, I use the newsgroup version of this list, and the reply button on my mail/newsreader does what I want it too - reply to the list only. (I hate getting an additional personal email for a publicly posted response) -- http://mail.python.org/mailman/listinfo/python-list
Re: Will python never intend to support private, protected and public?
Antoon Pardon wrote: What if the class author removes a non-private variable or changes a method's documented parameters in the next version of the class, because he think it'll work better, or just because he can? Changing an interface is different from changing the implementation. A (documented) interface is like a contract. The implementation is just one way to follow that contract. Agreed. However, there is also a difference between an interface and non-private variables. E.g. you have a library, and playing with the code, you notice that by passing an empty string as a filename, you get the last file accessed. Cool. You write your program using this feature. Problem is, it's a quirk of the implementation, and in the next version, the library author fixes this bug. Preventing access to private variables wouldn't help - the only thing you touched was the public parameter to a public function. Of course, you could have avoided this by only using the documented interface, but if we go that route, you wouldn't have to worry about people accessing private variables, as they wouldn't be documented. There is little in the way of technical problems that are solved by language level enforcement of private variables. The issues in question are mostly social ones, and if you're not reading and following the documented interface, stopping private variable access is not going to prevent most of your problems. People who think that forbidding access to private variables/methods will save themselves from upgrade woes are deluding themselves. It helps, just as locks wont save you from burglars if they really want to rob you, but the locks do help. Right, but like doors that automatically lock when they close, items which are there to protect you can be a nusaince, especially when you've left your keys on the dining room table. -- http://mail.python.org/mailman/listinfo/python-list
Re: Will python never intend to support private, protected and public?
Paul Rubin wrote: I don't know of a single program that's actually relying on the non-enforcement. I've asked for examples but have only gotten theoretical ones. As far as I can tell, the feature is useless. I'd like to turn the question around on you - can you come up with an instance where the non-enforcement has tripped someone up? Is there a bug you can point to that would have been prevented if Python enforced private member semantics? -- http://mail.python.org/mailman/listinfo/python-list
Re: [Info] PEP 308 accepted - new conditional expressions
Reinhold Birkenfeld wrote: Hi, after Guido's pronouncement yesterday, in one of the next versions of Python there will be a conditional expression with the following syntax: X if C else Y Any word on chaining? That is, what would happen with the following constructs: A if B else C if D else F A if B if C else D else F The first one is the tricky bit - it could be either (A if B else C) if D else F or A if B else (C if D else F) I'd expect the former from left- right semantics, but reading the unparenthesized form, I'd see A if B else ... note that B is true, and conclude the expression evaluated to A (which would be wrong if D is false). -- http://mail.python.org/mailman/listinfo/python-list
Re: Will python never intend to support private, protected and public?
[EMAIL PROTECTED] wrote: On Fri, 30 Sep 2005 00:16:02 +1000 Steven D'Aprano wrote: Say you have written a class, with a private variable. I decide that I need access to that variable, for reasons you never foresaw. What if the access to that variable was forbidden for reasons you never foresaw? What if the class author decide to remove the variable in the next version of the class, because it's not an interface, but only a part of the class implementation? What if the class author removes a non-private variable or changes a method's documented parameters in the next version of the class, because he think it'll work better, or just because he can? People who think that forbidding access to private variables/methods will save themselves from upgrade woes are deluding themselves. -- http://mail.python.org/mailman/listinfo/python-list
Re: A rather unpythonic way of doing things
fraca7 wrote: Richie Hindle a écrit : [Peter] http://www.pick.ucam.org/~ptc24/yvfc.html [Jeff] Yuma Valley Agricultural Center? Yaak Valley Forest Council? I went through the same process. My guess is Yes, Very F'ing Clever. Peter? print ''.join(map(lambda x: chrord(x) - ord('a')) + 13) % 26) + ord('a')), 'yvfc')) Less pythonic: __import__('sys').stdout.write(''.join(map(lambda x: chrord(x) - ord('a')) + 13) % 26) + ord('a')), 'yvfc')) More Pythonic: print 'yvfc'.decode('rot13') -- http://mail.python.org/mailman/listinfo/python-list
Re: How to tell if an exception has been caught ( from inside the exception )?
Paul Dale wrote: Hi everyone, I'm writing an exception that will open a trouble ticket for certain events. Things like network failure. I thought I would like to have it only open a ticket if the exception is not caught. Is there a way to do this inside the Exception? As far as I can see there are only two events called on the exception, __init__ and __del__, both of which will be called wether or not an exception is caught (right?) Am I missing something, or is there a way to do this with exceptions? Is there some reason you can't wrap your entry point with a try:except? e.g. if __name__ == __main__: try: main() except OpenTicket, e: process_open_ticket(e) -- http://mail.python.org/mailman/listinfo/python-list
Re: Indexed variables
[EMAIL PROTECTED] wrote: So how do I define the function such as to discrimate wheter I call it by f(a1) or f(a2) ? I don't want to sound rude, but I think you'll be better served by telling us why you would want to do such a thing - ten to one someone can suggest a better way to acomplish you end goal, rather than discriminating on which variable is passed to a function. -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing duplicates from a list
Rubinho wrote: I can't imagine one being much faster than the other except in the case of a huge list and mine's going to typically have less than 1000 elements. To add to what others said, I'd imagine that the technique that's going to be fastest is going to depend not only on the length of the list, but also the estimated redundancy. (i.e. a technique that gives good performance with a list that has only one or two elements duplicated might be painfully slow when there is 10-100 copies of each element.) There really is no substitute for profiling with representitive data sets. -- http://mail.python.org/mailman/listinfo/python-list
Re: Software bugs aren't inevitable
Terry Reedy wrote: But that, I admit, would be an invalid conclusion. And that, I claim, is also invalid when 'iteration' and 'recursion' are reversed, no matter how often repeated in texts and articles. The difference is between the algorithms, not the differing syntactic expressions thereof. There is a comparison in there about iteration vs. recursion, but it's probably not the one intended. The algorithm one uses sometimes depends quite heavily on which mindset you're using. Some algorithms require much more mental effort to understand when in their recursive form versus the iterative form, and vice versa. If you're stuck thinking in only one form, you might miss the better algorithm because it is not as simple in that form. The ideal case would be a programming language that allows you to write the algorithm in whatever form is simplest/most comfortable, and then automagically transforms it to the form that works the fastest under the hood. -- http://mail.python.org/mailman/listinfo/python-list
Re: Replacement for lambda - 'def' as an expression?
[EMAIL PROTECTED] wrote: On Tue, 06 Sep 2005 12:19:21 +0200 Torsten Bronger wrote: talin at acm dot org [EMAIL PROTECTED] writes: Anyway, here's an example, then, of how 'def' could be used: add = def( a, b ): return a + b I'm really not an expert in functional programming, so I wonder what's the difference between add = def (assumed that it worked) and def add? In the former case one could write self.add[0] = def(a, b) # etc. If that's the issue, it might make more sense to extend def to take any lvalue. def self.add[0](a, b): return a + b -- http://mail.python.org/mailman/listinfo/python-list
Re: 'isa' keyword
Colin J. Williams wrote: Rocco Moretti wrote: Terry Hancock wrote: On Thursday 01 September 2005 07:28 am, Fuzzyman wrote: What's the difference between this and ``isinstance`` ? I must confess that an isa operator sounds like it would have been slightly nicer syntax than the isinstance() built-in function. But not enough nicer to change, IMHO. Especially conidering that checking parameters with isinstance is considered bad form with Python's duck typing. Could you elaborate on that please? I'm not sure if you're familiar with duck typing or not, so I'll summarize it briefly. (More detail can be found by others in the c.l.py archive.) Duck typing takes its name from the expression If it looks like a duck, walks like a duck, and quacks like a duck, it's a duck. That is, the essence of an object is not its provenance, but its behaviour. This arises in part from Python being dynamically typed - you don't have to match the type of an object in order to pass it as a parameter. For example, say you had a function: def fun(alist): for item in alist: doworkon(item) The intended use of the function is for it to be passed a list, but you don't have to pass a list - it works just fine with a tuple, an iterator, a generator, a file object, a dictionary, or in fact any user defined class - all that's needed is for an appropriately defined __iter__ or __getitem__ member. Now if you use isinstance, you mess that up: def boring(alist): if isinstance(alist, list): for item in alist: doworkon(item) else: raise TypeError This will only work with a bona fide list, and choke on the other objects - even objects intended by the programmer to act like a list. Python functions are much more flexible if you don't go checking if an object is of a particular type. It makes things like using proxies, wrappers and mock objects much easier. Best practices in Python call for using a parameter and catching when it doesn't behave properly, not prophylactically checking types. Python programmers can go months to years without using isinstance. It doesn't make sense to make it any easier. P.S. In the OP's case, where it was desired to distinguish between being passed a string and being passed a list of strings, the approach used is probably sub-optimal. It would likely be better to have the function always take a list, and convert all the fun('string') calls to fun(['string']) calls. -- http://mail.python.org/mailman/listinfo/python-list
Re: 'isa' keyword
Terry Hancock wrote: On Thursday 01 September 2005 07:28 am, Fuzzyman wrote: What's the difference between this and ``isinstance`` ? I must confess that an isa operator sounds like it would have been slightly nicer syntax than the isinstance() built-in function. But not enough nicer to change, IMHO. Especially conidering that checking parameters with isinstance is considered bad form with Python's duck typing. -- http://mail.python.org/mailman/listinfo/python-list
Re: OpenSource documentation problems
Steve Holden wrote: Every page of the docs links to About this document, which contains the following: If you are able to provide suggested text, either to replace existing incorrect or unclear material, or additional text to supplement what's already available, we'd appreciate the contribution. There's no need to worry about text markup; our documentation team will gladly take care of that. There is just one giant roadblock to that suggestion - Sourceforge requires a login to post bugs/patches. It doesn't seem like much, but as Paul Rubin mentioned, most people who find bugs/unclear passages in the docs aren't scanning the docs explicitly to edit them - they've uncovered the bug after working on some other project, and likely only after banging their head against the wall a few times trying to get it to work. If they have to go through the song and dance of signing up for another website to report the problem, they might just say forget it. Sure, it's not hard to sign up for Sourceforge, but even a little barrier can stop you from contributing if you're not enthusiastic about it in the first place. Something a simple as allowing doc bugs to be submitted from a webform w/o login would reduce the barrier to contribute. - Increasing the size of the About text wouldn't hurt either. (To be honest, I've never noticed that text before, and it never occurred to me look at the About page for information on error reports.) That said, I think the Python manuals are great. But saying that they are perfect, or that the editing process couldn't be improved is just deluding yourself. -- http://mail.python.org/mailman/listinfo/python-list
Re: Well, Python is hard to learn...
wen wrote: due to the work reason, i have to learn python since last month. i have spent 1 week on learning python tutorial and felt good. but i still don't understand most part of sourcecode of PYMOL(http://pymol.sourceforge.net/) as before. Well, last time I checked, a good chunk of PyMol was written in C. Knowing Python may help you to learn C, but I doubt that one week is going to be sufficient. But I agree that Python is deceptive. It's so easy to learn and use, you can easily convince yourself you're a better programmer than you actually are. -- http://mail.python.org/mailman/listinfo/python-list
Re: Module Name Conflicts
[EMAIL PROTECTED] wrote: I have a java program in a package called 'cmd'. This of course conflicts with the builtin python package of the same name. The thing is, I need to be able to import from both of these packages in the same script. I can import either one first, but any future attempt to import from cmd.* will look up the first cmd that was imported, so the second package is essentially eclipsed. I've tried fiddling with sys.path and sys.packageManager.searchPath, to no avail. To answer the obvious first suggestion, no I can't rename the java package to 'Cmd' or anything like that. Any ideas? -Smurf Never used it myself, but you can try to use the builtin 'imp' module. Python Library Reference 3.21 imp -- Access the import internals This module provides an interface to the mechanisms used to implement the import statement. It defines the following constants and functions: ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Library vs Framework (was Dr. Dobb's Python-URL!)
Simon Brunning wrote: On 8/15/05, Terry Hancock [EMAIL PROTECTED] wrote: On Monday 15 August 2005 09:54 am, Simon Brunning wrote: If you call its code, it's a library. If it calls yours, it's a framework. Such concision deserves applause. ;-) Thank you. ;-) As others have pointed out, this is a *drastic* simplification, perhaps an oversimplification. You will inevitably need to call a framework's code in addition to it calling yours, and a callback argument or two won't turn a library into a framework. But I think it captures the essence of the difference. The point that passed me by the first time, and which Magnus et al. helped me realize, is that it's referring not to an instantaneous, mechanical view of calling, but to a more general, philosophical view of calling. With a library, the user's code is in charge of the program structure, and calls the library to fill in the details and help out. With a framework, the framework is in charge, and the user code is filling in with a supporting role. With this in mind, it's easy to see why Andy Smith feels frameworks are restricting - after all, it's the framework, not the user, who is in charge of program structure. But I'm not sure if library vs. framework a fair comparison - the two are doing different things. With a framework, you're not really writing your own program, you're customizing someone else's. Sort of a vastly more flexible version of command line options. Saying you can't reuse code written for a framework is kind of like saying that it's difficult to use an Apache config file with the Gimp. -- http://mail.python.org/mailman/listinfo/python-list