Re: how can I clear a dictionary in python
On 2007-04-04, Aahz [EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], Antoon Pardon [EMAIL PROTECTED] wrote: On 2007-04-03, Aahz [EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], Larry Bates [EMAIL PROTECTED] wrote: Aahz wrote: In article [EMAIL PROTECTED], Larry Bates [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: I create a dictionary like this myDict = {} and I add entry like this: myDict['a'] = 1 but how can I empty the whole dictionary? just point myDict to an empty dictionary again myDict={} Go back and read Christian's post, then post a followup explaning why his solution is better than yours. Your explanation should use id(). I believe he (as many new to Python do) are mired in old programming thinking that variables contain things. As I'm sure you kno, variables point to things in Python. I don't believe that there are lots of other objects pointing to this dictionary. Perhaps the OP can clarify for us. If there aren't other objects pointing to this dictionary it would make NO sense to iterate over a dictionary and delete all the keys/values so I tried to read between the lines and answer what I believe the OP thought he was asking. Then you should explain why you didn't answer the question that was asked. Answering a different question without explanation makes your answer irrelevant at best, wrong at worst. This is not true. If this different question was in fact the intended question instead of the one actually asked. Anwering this different question can be more usefull than answering the one actually asked. Note carefully that I did not say, Don't answer the question you think should have been asked. What I said was, If you answer a different question, EXPLAIN WHY. Is that so difficult to understand? You are mixing up two things: On the one hand you are trying to get some moral behaviour accrosss: People should explain when answering a different question. On the second hand you are bringing an opinion: If they don't their answer is irrelevant at best. If someone disagrees with the second, repeating the first seems a bit beside the point. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
setup() and C extensions
Hi, I can't find any documentation on the setup() function in the distutils.core module; specifically I want to know what the 'name' argument does. In some examples in the python docs, they use the name argument like this: from distutils.core import setup, Extension module1 = Extension('demo', sources = ['demo.c']) setup (name = 'PackageName', version = '1.0', description = 'This is a demo package', ext_modules = [module1]) http://python.org/doc/current/ext/building.html#building So it looks like the 'name' argument should be a package name. However, when I compile an extension module using that format, I can import the module using the syntax: import module1 I don't have to use PackageName.module1. On the other hand, in another example in the python docs, they do this: --- from distutils.core import setup, Extension setup(name='foo', version='1.0', ext_modules=[Extension('foo', ['foo.c'])], ) http://python.org/doc/current/dist/describing-extensions.html In that example, the name argument matches the module name in the Extension constructor. A similar example by Alex Martelli can be found at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66509 So what is the name argument in setup() used for? -- http://mail.python.org/mailman/listinfo/python-list
Re: TASK KILL
Will TASKKILL kills a thread when thread id is given ?? Or does it kill only a process?? How to ensure that a thread is killed? Hi! Sorry, TASKKILL is only for process. For help on TASKKILL :TASKKILL /? Other infos with TASKLIST (TASKLIST /?) If the object who use process is a service (kif-kif daemon), you can use SC (see SC /?) For thread, the concept is fuzzy. Thread can be manage by OS, by software (e.g. by Python, for Python's threads), or by middlewares. There are no universal way. -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: setup() and C extensions
Also: 1) When you create a C array to map python names to the C functions that you defined: static PyMethodDef MyFunctions[] = { {my_calc, (PyCFunction)my_func, METH_VARARGS, my very speedy c function}, {NULL, NULL, 0, NULL} }; Why do you need to cast my_func to PyCFunction? 2) When returning None, why use the idiom: Py_INCREF(Py_None); return Py_None; instead of: return Py_BuildValue(); -- http://mail.python.org/mailman/listinfo/python-list
Re: Queue get timeout parameter question
On Apr 10, 2:20 pm, Paul Rubin http://[EMAIL PROTECTED] wrote: Godzilla [EMAIL PROTECTED] writes: After the time sync, say 15 seconds backward, the thread is sitting on that get() method for a total of 17 seconds. We can only sync the device once per day and the time can drift up to 15 seconds per day!! Try to avoid syncing lke that. System clocks drift but the drift rates tend to be constant, so there are schemes for gradually slowing down or speeding up the system clock in order to keep it synchronized with an external reference. Anyone knows a solution to this problem or an alternative method? http://www.ntp.org Hi Paul, Ok... But I'm afraid no syncing is not an option for the device... -- http://mail.python.org/mailman/listinfo/python-list
how to get char ASCII value.
for an example: 'a' value 0x61 '1' value 0x31. -- http://mail.python.org/mailman/listinfo/python-list
Re: Database in memory
Jeremy Sanders [EMAIL PROTECTED] wrote: Dictionaries are one of the most useful things in Python. Make sure you know how to take adavantage of them... +1 for QOTW - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: [offtopic?] problem with UDP broadcast on Windows XP
Irmen de Jong [EMAIL PROTECTED] wrote: Gabriel Genellina wrote: Try running the service impersonating another user (not LOCAL_SERVICE, the default). You can change that from the service control panel. Alas, that didn't change anything. I made it run as a user account that has admin privileges even, and it still doesn't respond to the broadcasts. :-( I am not sure if this is at all relevant - but I seem to recall seeing something once that had a list of socket numbers, splitting them between UDP TCP - can the socket actually rx UDP? - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get char ASCII value.
On Apr 10, 12:57 am, [EMAIL PROTECTED] wrote: for an example: 'a' value 0x61 '1' value 0x31. How about: import string for char in string.lowercase: print hex(ord(char) ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Exec Statement Question
Thanks for the responses everyone. That does make sense to me now. -Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Queue get timeout parameter question
Godzilla schrieb: I have been using the queue module for a multithreaded environment and things seem to work well... until we had a requirement for the application to be able to time sync to the server. With the time sync, it actually disorientated the timeout in the queue's get() method... e.g. get(item, 2.0) After the time sync, say 15 seconds backward, the thread is sitting on that get() method for a total of 17 seconds. We can only sync the device once per day and the time can drift up to 15 seconds per day!! I had tried to get around this problem by having a sleep(2) (sleep is not local system time dependant) just before the get(), but that will slow down the application too much. Anyone knows a solution to this problem or an alternative method? I was fixing a serious time drift problem on Linux lately. If your server runs on Linux I can give you some hints: - set the system clock - delete /etc/adjtime and resync system time and hardware time hwclock --systohc - on some distributions you may have to reboot - give it some time to see if it is still drifting - if only the system clocks drifts (see output of hwclock; date) you may have a timer related kernel problem. This may help: * deactivate ACPI via kernel boot parameter * change timer frequency * try different setting for all timer related stuff like CONFIG_HPET_TIMER or CONFIG_X86_PM_TIMER Thomas -- sinature: http://nospam.nowire.org/signature_usenet.png -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 2007-04-06, Carsten Haese [EMAIL PROTECTED] wrote: On Fri, 2007-04-06 at 11:33 -0700, 7stud wrote: On Apr 6, 7:56 am, Paul Boddie [EMAIL PROTECTED] wrote: The problem with 7stud's quote from GvR is that it's out of date: I would argue that it shows the very guy who invented the language stated publicly there was no good reason for tuples not to have an index method---except for consistency; tuples had no other methods. Now that tuples have other methods, the only justification he stated no longer exists. Except that that wasn't the only justification. GvR also said: For tuples, I suspect such a function would rarely be used; I think that is most cases where x.index() would be useful, x is generally a list, whose contents varies in time, rather than a tuple (which cannot change easily). The lack of convincing use cases is still a pertinent reason today. Note that the original poster on this thread did not present a use case for tuple.index, they were only asking out of curiosity. If you have a use case for tuple.index, please show it to me, and I'll show you what you should be using instead of a tuple. No wonder no convincing use cases for tuples have shown up. You just defined use cases of tuples as unconvincing. My personal opinion is that lack of use cases are used too much as an excuse. Limiting the development of your language to use cases makes your language less consistent and so makes your language less easy to learn. Of course it also limits the language to what the developers can think off. I once thought it would be usefull to have something like a slice but with extended functionality. So I first tried this: class Islice(slice): ... and I got: type 'slice' is not an acceptable base type then I just tried: class Islice: ... But an instance of such a class can't be used as an index, despited the propoganda that is made for duck typing in this news group. I guess the developers just couldn't see the use case of this. But you do have to wonder when the developers started to unify classes and types, why they just didn't go the whole wayr?. Making all types subclassable, means you have only one case to code and the user doesn't has to wonder whether a particular type is subclassable or not. I think that is a bigger gain, than the potential loss one may experience because some type that now are subclassable will never actually be subclassed. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
exec statement Syntax Error on string pulled from MySQL
It's the strangest thing, I'm pulling some text out of a MySQL table and trying to run exec on it, and it keeps giving me a syntax error, always at the end of the first line. Thanks in advance for any help. I'm really stuck on this one! -Greg I'm not sure what information would be most useful but here's a start: The last code I stored in the table and pulled out was simply: print 'greg' print 'greg2' To which my error log says: Traceback (most recent call last): File /home/public/web/webapi.py, line 303, in wsgifunc result = func() File /home/public/web/request.py, line 125, in lambda func = lambda: handle(inp, fvars) File /home/public/web/request.py, line 61, in handle return tocall(*([urllib.unquote(x) for x in args] + fna)) File /home/public/EZsession.py, line 119, in proxyfunc return func(self, *args, **kw) File /home/htdocs/code.py, line 94, in POST print utility.run(name,revision,inp) File /home/public/utility.py, line 177, in run exec code+'\n' in context File string, line 1 print 'greg' ^ SyntaxError: invalid syntax (Note the ^ actually appears under after the ' ) To really get a picture of what is coming out of the DB I had the program print out everything about this string using this code: print code print repr(code) print type(code) for char in code: print ord(char),char To which I got: print 'greg' print 'greg2' print 'greg'\r\nprint 'greg2' type 'str' 112 p 114 r 105 i 110 n 116 t 32 39 ' 103 g 114 r 101 e 103 g 39 ' 13 10 112 p 114 r 105 i 110 n 116 t 32 39 ' 103 g 114 r 101 e 103 g 50 2 39 ' -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 2007-04-08, Carsten Haese [EMAIL PROTECTED] wrote: On Sun, 2007-04-08 at 07:51 -0700, Paul Rubin wrote: Carsten Haese [EMAIL PROTECTED] writes: Maybe we can add such methods to the PyPy tuples for some time, to experimentally see if they make the language worse :-) Adding useless features always makes a product worse. What's your use case for tuple.index? Do you not see the gratuituous inconsistency between tuples and lists as a useless feature? What is the use case for keeping it? When a new feature is requested, the burden of proof is on the requester to show that it has uses. I don't agree. Good or bad design is not dependant on what is implemented and what is not. The use case for not having tuple.index is that there are no use cases for having it. If that answer sounds absurd, it is because your question is absurd. You mean that those who are against tuple.index won't find any use case convincing enough. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 2007-04-09, Georg Brandl [EMAIL PROTECTED] wrote: Paul Rubin schrieb: Carsten Haese [EMAIL PROTECTED] writes: Will tuples also get a sort method? What about append and extend? pop? __iadd__? __delslice__? They are immutable so they won't get .sort() etc. sorted(...) already works on them. How many brain cells are actually freed up by not having to remember that *one* method that you'd never use doesn't exist? I dunno but I do know that Ruby is attracting a lot of potential Python users because it apparently has fewer of these inconsistencies. It remains to be proven that it is an inconsistency, rather than a design decision. The two don't contradict. A design decision can introduce an inconsistency. AFAICS having an index method on tuples seems rather natural. Looking for the index of a particular item in your sequence seems just as usefull independant of the nature of your sequence. So unless there is some rather forcefull argument it seems inconsistent to have some sequences lacking this method. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: exec statement Syntax Error on string pulled from MySQL
[EMAIL PROTECTED] [EMAIL PROTECTED] wrote: To really get a picture of what is coming out of the DB I had the program print out everything about this string using this code: print code print repr(code) print type(code) for char in code: print ord(char),char To which I got: print 'greg' print 'greg2' print 'greg'\r\nprint 'greg2' exec 1\n2 exec 1\r\n2 Traceback (most recent call last): File pyshell#1, line 1, in module exec 1\r\n2 File string, line 1 1 ^ SyntaxError: invalid syntax Get rid of the carriage return. -- http://mail.python.org/mailman/listinfo/python-list
Re: Queue get timeout parameter question
On Apr 10, 5:38 pm, Thomas Krüger [EMAIL PROTECTED] wrote: Godzilla schrieb: I have been using the queue module for a multithreaded environment and things seem to work well... until we had a requirement for the application to be able to time sync to the server. With the time sync, it actually disorientated the timeout in the queue's get() method... e.g. get(item, 2.0) After the time sync, say 15 seconds backward, the thread is sitting on that get() method for a total of 17 seconds. We can only sync the device once per day and the time can drift up to 15 seconds per day!! I had tried to get around this problem by having a sleep(2) (sleep is not local system time dependant) just before the get(), but that will slow down the application too much. Anyone knows a solution to this problem or an alternative method? I was fixing a serious time drift problem on Linux lately. If your server runs on Linux I can give you some hints: - set the system clock - delete /etc/adjtime and resync system time and hardware time hwclock --systohc - on some distributions you may have to reboot - give it some time to see if it is still drifting - if only the system clocks drifts (see output of hwclock; date) you may have a timer related kernel problem. This may help: * deactivate ACPI via kernel boot parameter * change timer frequency * try different setting for all timer related stuff like CONFIG_HPET_TIMER or CONFIG_X86_PM_TIMER Thomas -- sinature:http://nospam.nowire.org/signature_usenet.png- Hide quoted text - - Show quoted text - Thanks Thomas, I'm not running Linux but I will take some of your pointers as a guide. Cheers mate. -- http://mail.python.org/mailman/listinfo/python-list
Re: pluie documentation in english
Bonjour ! Avec Internet-Explorer 6 : Dans Internet-explorer, par le menu, faire : Outils + Options_internet Aller sur le dernier onglet (Avancé), et cocher : autoriser le contenu actif (désolé pour le français, mais mon anglais est vraiment trop mauvais). Et, merci pour l'info, ça m'a permis d'ajouter un item à la F.A.Q. @-salutations -- Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: RFC: Assignment as expression (pre-PEP)
Alex Martelli schrieb: Adam Atlas [EMAIL PROTECTED] wrote: Hasn't this been discussed many many times before? I think Guido has been favourable to the idea of allowing :=, but that was a long time ago, and I don't think anything ever came of it. Personally, if anything, I'd like to see more use of the 'as' keyword as in Python 2.5's new 'with' statement. Assignment is basically what it adds to the statement, so if anything we should reuse it in other statements for consistency. if my_re1.match(exp) as temp: # do something with temp elif my_re2.match(exp) as temp: # do something with temp elif my_re3.match(exp) as temp: # do something with temp elif my_re4.match(exp) as temp: # do something with temp As others have mentioned, your particular instance is probably evidence that you need to restructure your code a little bit, but I do agree that x = y; if x: ... is a common enough idiom that it warrants a shortcut. And reusing as, I think, is nice and readable, and it's an advantage that it doesn't require adding any new keywords or symbols. Actually, I agree with you. Unfortunately, I doubt python-dev will, but the chance is good enough that it's probably worth proposing there (ideally together with a patch to implement it, just to avoid any [otherwise likely] whines about this being difficult to implement:-). The patch is already done -- I have it lying around here :) Georg -- Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out. -- http://mail.python.org/mailman/listinfo/python-list
NLTK, Random Sentence Generators?
Has any created or not of examples of random sentence generators using n-gram models (or other models might be interesting). I know of one example from a course at MIT, but besides that nothing. Any help would be great. -- http://mail.python.org/mailman/listinfo/python-list
Re: exec statement Syntax Error on string pulled from MySQL
[EMAIL PROTECTED] schrieb: It's the strangest thing, I'm pulling some text out of a MySQL table and trying to run exec on it, and it keeps giving me a syntax error, always at the end of the first line. Thanks in advance for any help. I'm really stuck on this one! -Greg I'm not sure what information would be most useful but here's a start: The last code I stored in the table and pulled out was simply: print 'greg' print 'greg2' To which my error log says: Traceback (most recent call last): File /home/public/web/webapi.py, line 303, in wsgifunc result = func() File /home/public/web/request.py, line 125, in lambda func = lambda: handle(inp, fvars) File /home/public/web/request.py, line 61, in handle return tocall(*([urllib.unquote(x) for x in args] + fna)) File /home/public/EZsession.py, line 119, in proxyfunc return func(self, *args, **kw) File /home/htdocs/code.py, line 94, in POST print utility.run(name,revision,inp) File /home/public/utility.py, line 177, in run exec code+'\n' in context File string, line 1 print 'greg' ^ SyntaxError: invalid syntax (Note the ^ actually appears under after the ' ) You have Windows line endings (\r\n) in the string, which Python doesn't like. Don't store it like that, or if you must, do a .replace('\r', '') before exec'ing it. Georg -- Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out. -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
Antoon Pardon [EMAIL PROTECTED] wrote: When a new feature is requested, the burden of proof is on the requester to show that it has uses. I don't agree. Good or bad design is not dependant on what is implemented and what is not. There is a cost to every new language feature: it has to be implemented, documented, maintained, and above all learned by the users. Good design involves, in part, not adding to these burdens except where there is a benefit at least equal to the cost. The use case for not having tuple.index is that there are no use cases for having it. If that answer sounds absurd, it is because your question is absurd. You mean that those who are against tuple.index won't find any use case convincing enough. Why not try them? Pose a few useful cases where the existence of tuple.index() would actually give a benefit and see what response you get. You would have to meet a few obvious conditions: the use case would need to be one where a tuple was preferable to a list (the obvious one being where you need to hash it), the tuple would have to be sufficiently long or the calls to 'index' sufficiently frequent to make casting to a list so you can call 'list(obj).index(...)' unattractive, and you actually need a reason to be using 'index' rather than just the 'in' operator. -- http://mail.python.org/mailman/listinfo/python-list
Why is __getslice__ still implemented?
Hallöchen! According to http://docs.python.org/ref/sequence-methods.html, __getslice__ is deprecated. At the moment, I derive an own class from unicode and want to implement my own slicing. I found that I have to override __getslice__ since __getitem__ isn't called when I have something like my_instance[a:b] in my code. According to news:[EMAIL PROTECTED], this may have efficiency reasons, however, I agree with news:[EMAIL PROTECTED] that this is quite confusing. It forces people to implement a deprecated function after all. I think the docs should say that you still have to override __getslice__ when subclassing from a built-in type, unless I really don't understand the issue correctly. Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: [EMAIL PROTECTED] (See http://ime.webhop.org for ICQ, MSN, etc.) -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 2007-04-10, Duncan Booth [EMAIL PROTECTED] wrote: Antoon Pardon [EMAIL PROTECTED] wrote: When a new feature is requested, the burden of proof is on the requester to show that it has uses. I don't agree. Good or bad design is not dependant on what is implemented and what is not. There is a cost to every new language feature: it has to be implemented, documented, maintained, and above all learned by the users. Good design involves, in part, not adding to these burdens except where there is a benefit at least equal to the cost. So what is the easiest to learn: All sequences have an index method or Such and so sequences have an index method and others don't Which of the above is the easiest to document? Now with implementation and maintaining. If you would start with a class of sequence which classes like tuple and list would inherit from, then there also would be a single function to be implemented and maintained. It would just be usable in more types. The use case for not having tuple.index is that there are no use cases for having it. If that answer sounds absurd, it is because your question is absurd. You mean that those who are against tuple.index won't find any use case convincing enough. Why not try them? Pose a few useful cases where the existence of tuple.index() would actually give a benefit and see what response you get. You would have to meet a few obvious conditions: the use case would need to be one where a tuple was preferable to a list (the obvious one being where you need to hash it), the tuple would have to be sufficiently long or the calls to 'index' sufficiently frequent to make casting to a list so you can call 'list(obj).index(...)' unattractive, and you actually need a reason to be using 'index' rather than just the 'in' operator. If someone states: Show me your use case for using tuple.index and I will show you how to avoid it. or words to that effect I think there is little use trying. Besides I have seen how such things evolve here before. Every use case that will be presented, will be rewritten in a way that doesn't need tuple.index and these rewritals will be used as an argument for not having tuple.index. If you need to hash it, you can simply subclass list and provide a hash with your class or you can simply use tuples and write an index function yourself. The same happened with the ternary operator. Every use case someone could come up with was rejected by rewriting the code without using a ternary operator. AFAICS the only reason the ternary operator finaly got introduced was because a python developer was bitten by an illusive bug, introduced by one of the idioms that was often used as a way to simulate a ternary operator. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: confirm password for logged in user
André Wyrwa schrieb: I'm wondering, though, if there isn't ANY way to have the password confirmed for the user that is already logged in. Please note the difference, i don't want to write some kind of login functionality. The user is already authenticated, i just want to have a typed in password checked agains the already logged in users password. It is not possible to check a password against the shadow file without having root privileges. Neither with nor without PAM. Whyt you can do is install (or write yourself) a small program that checks the password for you. That program must run as root (be installed with suid root), but your daemon does not need to. The daemon calls the external program to do the password check. http://unixpapa.com/pwauth should work for your purposes. -- René -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 10 Apr, 11:48, Antoon Pardon [EMAIL PROTECTED] wrote: On 2007-04-10, Duncan Booth [EMAIL PROTECTED] wrote: There is a cost to every new language feature: it has to be implemented, documented, maintained, and above all learned by the users. Good design involves, in part, not adding to these burdens except where there is a benefit at least equal to the cost. So what is the easiest to learn: All sequences have an index method or Such and so sequences have an index method and others don't I think this observation leads to insights both at the end-user level and at the implementer level. Tuples and lists are sequences; the index method can be defined generically for all sequences; adding such a method to the tuple type can be done with barely any changes to the implementation taken from the list type. This leads to the observation that a generic index method (defined as a function in the implementation) could be made to work with both lists and tuples, and that various other methods might also be defined similarly, although things like append, extend and other mutating methods wouldn't be appropriate for a tuple. Which of the above is the easiest to document? Now with implementation and maintaining. If you would start with a class of sequence which classes like tuple and list would inherit from, then there also would be a single function to be implemented and maintained. It would just be usable in more types. There isn't a big win in this case: the intersection of useful methods between mutable and immutable sequence types is rather small. Nevertheless, providing a slightly deeper abstract class hierarchy might be appropriate, and this is being considered for Python 3000. [...] The same happened with the ternary operator. Every use case someone could come up with was rejected by rewriting the code without using a ternary operator. AFAICS the only reason the ternary operator finaly got introduced was because a python developer was bitten by an illusive bug, introduced by one of the idioms that was often used as a way to simulate a ternary operator. The ternary operator, whilst providing new and occasionally useful functionality, is rather badly phrased in my opinion: when used, it's a bit like reading one natural language and suddenly having the grammar of another in use for the rest of the sentence. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is __getslice__ still implemented?
Torsten Bronger wrote: Hallöchen! According to http://docs.python.org/ref/sequence-methods.html, __getslice__ is deprecated. At the moment, I derive an own class from unicode and want to implement my own slicing. I found that I have to override __getslice__ since __getitem__ isn't called when I have something like my_instance[a:b] in my code. According to news:[EMAIL PROTECTED], this may have efficiency reasons, however, I agree with news:[EMAIL PROTECTED] that this is quite confusing. It forces people to implement a deprecated function after all. I think the docs should say that you still have to override __getslice__ when subclassing from a built-in type, unless I really don't understand the issue correctly. Tschö, Torsten. Which version of python are you using? chernev 20% /sw/bin/python Python 2.5 (r25:51908, Oct 10 2006, 03:45:47) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type help, copyright, credits or license for more information. py class Bob(object): ... def __getitem__(self, *args): ... print args ... py b = Bob() py b[4:21:2] (slice(4, 21, 2),) py b[5:18:21,2:9:2,8,14:4] ((slice(5, 18, 21), slice(2, 9, 2), 8, slice(14, 4, None)),) -- http://mail.python.org/mailman/listinfo/python-list
Re: NLTK, Random Sentence Generators?
Passer By wrote: Has any created or not of examples of random sentence generators using n-gram models (or other models might be interesting). I know of one example from a course at MIT, but besides that nothing. Any help would be great. Best is to just cull text from your spam folder as these are often generated by similar means--but somehow I think you knew that. James -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 2007-04-10, Paul Boddie [EMAIL PROTECTED] wrote: Now with implementation and maintaining. If you would start with a class of sequence which classes like tuple and list would inherit from, then there also would be a single function to be implemented and maintained. It would just be usable in more types. There isn't a big win in this case: the intersection of useful methods between mutable and immutable sequence types is rather small. Nevertheless, providing a slightly deeper abstract class hierarchy might be appropriate, and this is being considered for Python 3000. Well I wasn't trying to show this aspect as a big win. Just illustrating it doesn't have to be a big cost in this case. The same happened with the ternary operator. Every use case someone could come up with was rejected by rewriting the code without using a ternary operator. AFAICS the only reason the ternary operator finaly got introduced was because a python developer was bitten by an illusive bug, introduced by one of the idioms that was often used as a way to simulate a ternary operator. The ternary operator, whilst providing new and occasionally useful functionality, is rather badly phrased in my opinion: when used, it's a bit like reading one natural language and suddenly having the grammar of another in use for the rest of the sentence. I agree. The structure of the if-expression doesn't resemble the structure of the if-statement. I think it was a bad choice to have the two so dissimilar. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is __getslice__ still implemented?
Hallöchen! James Stroud writes: [...] Which version of python are you using? 2.4 chernev 20% /sw/bin/python Python 2.5 (r25:51908, Oct 10 2006, 03:45:47) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type help, copyright, credits or license for more information. py class Bob(object): This should be Bob(unicode). ... def __getitem__(self, *args): ... print args ... py b = Bob() py b[4:21:2] (slice(4, 21, 2),) py b[5:18:21,2:9:2,8,14:4] ((slice(5, 18, 21), slice(2, 9, 2), 8, slice(14, 4, None)),) Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: [EMAIL PROTECTED] (See http://ime.webhop.org for ICQ, MSN, etc.) -- http://mail.python.org/mailman/listinfo/python-list
RE: Breaking up Strings correctly:
-Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Adam Atlas Sent: Monday, April 09, 2007 11:28 PM To: python-list@python.org Subject: Re: Breaking up Strings correctly: On Apr 9, 8:19 am, Michael Yanowitz [EMAIL PROTECTED] wrote: Hello: I have been searching for an easy solution, and hopefully one has already been written, so I don't want to reinvent the wheel: Pyparsing is indeed a fine package, but if Paul gets to plug his module, then so do I! :) I have a package called ZestyParser... a lot of it is inspired by Pyparsing, actually, but I'm going in a different direction in many areas. (One major goal is to be crazily dynamic and flexible on the inside. And it hasn't failed me thus far; I've used it to easily parse grammars that would make lex and yacc scream in horror.) Here's how I'd do it... from ZestyParser import * from ZestyParser.Helpers import * varName = Token(r'\$(\w+)', group=1) varVal = QuoteHelper() | Int sp = Skip(Token(r'\s*')) comparison = sp.pad(varName + CompositeToken([RawToken(sym) for sym in ('=','','','=','=','!=')]) + varVal) #Maybe I should borrow PyParsing's OneOf idea :) expr = ExpressionHelper(( comparison, (RawToken('(') + Only(_top_) + RawToken(')')), oper('NOT', ops=UNARY), oper('AND'), oper('OR'), )) Now you can scan for `expr` and get a return value like [[['IP', '=', '127.1.2.3'], ['AX', '', 15]], [['IP', '=', '127.1.2.4'], ['AY', '! =', 0]]] (for the example you gave). Note that this example uses several features that won't be available until the next release, but it's coming soon. So Michael, though you'd still be able to parse this with the current version, the code wouldn't look as nice as this or the Pyparsing version. Maybe just add it to your watchlist. :) - Adam -- Thanks for your and Gerard's and Gabriel's responses. I guess what I was looking for was something simpler than parsing. I may actually use some of what you posted. But I am hoping that if given a string such as: '((($IP = 127.1.2.3) AND ($AX 15)) OR (($IP = 127.1.2.4) AND ($AY != 0)))' something like split(), where I can pass it something like [' AND ', ' OR ', ' XOR '] will split the string by AND, OR, or XOR. BUT split it up in such a way to preserve the parentheses order, so that it will split on the outermost parenthesis. So that the above string becomes: ['OR', '(($IP = 127.1.2.3) AND ($AX 15))', '(($IP = 127.1.2.4) AND ($AY != 0))'] No need to do this recursively, I can repeat the process, however if I wish on each string in the list and get: ['OR', ['AND', '($IP = 127.1.2.3)', '($AX 15)'], ['AND', '($IP = 127.1.2.4)', '($AY != 0)']] Can this be done without parsers? Perhaps with some variation of re or split. Has something like this already been written? Thanks in advance: -- http://mail.python.org/mailman/listinfo/python-list
Re: Custom Python Runtime
En Tue, 10 Apr 2007 00:17:33 -0300, Jack [EMAIL PROTECTED] escribió: 1. One Windows, it's possible to zip all files in a Python24.zip. I'm not very clear if it's used in the stardard distribution. What can, and what can not be put into this file? I suppose zip file will help reduce the distribution size. (Not just on Windows) pythonXX.zip is always on sys.path, and is searched like any other path (using zipimport). You might in principle put all the standard library there, if you wish. py2exe, by example, searches for all dependent modules and puts then all in a .zip file. But zips can only contain .py/.pyc files, not dynamic libraries like .dll/.so. 3. Some files go to the Windows\system32 directory, including some win32all files. Can they be in the current directory as python.exe? .dll files? Sure. 4. Are the registry entries necessary? No, but if you have added entries into the PythonPath key, you may need to configure your Python search path (using a PYTHONPATH environment variable or .pth files). -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 10 Apr 2007 07:31:13 GMT, Antoon Pardon wrote On 2007-04-06, Carsten Haese [EMAIL PROTECTED] wrote: If you have a use case for tuple.index, please show it to me, and I'll show you what you should be using instead of a tuple. No wonder no convincing use cases for tuples have shown up. You just defined use cases of tuples as unconvincing. It's not a definition, it's an observation. I'm simply saying that all use cases I've seen for tuple.index could be written in a clearer fashion by using something else. Please prove me wrong by supplying a use case of tuple.index that can not be improved by rewriting. Note that I have proved elsewhere on this thread that any real use case for tuple.index will involve an operation to explicitly use an index different from the one obtained by the call to tuple.index(). I'd like to hear your opinion on this. My personal opinion is that lack of use cases are used too much as an excuse. Limiting the development of your language to use cases makes your language less consistent and so makes your language less easy to learn. That is your opinion, and you are entitled to your opinion. My opinion is that adding features that don't have any uses just weigh the language down unnecessarily, and they distract programmers from finding the best solution to their problem. Of course it also limits the language to what the developers can think off. Initially, yes, but if enough use cases exist for a feature that the developers didn't think of, it will be implemented. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 10 Apr 2007 09:48:41 GMT, Antoon Pardon wrote If someone states: Show me your use case for using tuple.index and I will show you how to avoid it. or words to that effect I think there is little use trying. Or maybe you just can't think of any good use cases, and that's annoying you because it proves my point. Please, prove me wrong by showing use cases for tuple.index that can't be rewritten. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: setup() and C extensions
En Tue, 10 Apr 2007 03:02:22 -0300, 7stud [EMAIL PROTECTED] escribió: I can't find any documentation on the setup() function in the distutils.core module; specifically I want to know what the 'name' argument does. In some examples in the python docs, they use the name argument like this: http://docs.python.org/dist/module-distutils.core.html So it looks like the 'name' argument should be a package name. Exactly. However, when I compile an extension module using that format, I can import the module using the syntax: import module1 I don't have to use PackageName.module1. name should be the full dotted name - but I've never tried it actually. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: NLTK, Random Sentence Generators?
James Stroud [EMAIL PROTECTED] writes: Passer By wrote: Has any created or not of examples of random sentence generators using n-gram models (or other models might be interesting). I know of one example from a course at MIT, but besides that nothing. Any help would be great. Best is to just cull text from your spam folder as these are often generated by similar means--but somehow I think you knew that. Emotive on Usenet? Thats original. -- http://mail.python.org/mailman/listinfo/python-list
Re: setup() and C extensions
En Tue, 10 Apr 2007 03:35:35 -0300, 7stud [EMAIL PROTECTED] escribió: 1) When you create a C array to map python names to the C functions that you defined: static PyMethodDef MyFunctions[] = { {my_calc, (PyCFunction)my_func, METH_VARARGS, my very speedy c function}, {NULL, NULL, 0, NULL} }; Why do you need to cast my_func to PyCFunction? Because it does not *have* to be a PyCFunction; the ml_flags field is used to indicate exactly what kind of function it is (METH_KEYWORDS indicating a PyCFunctionWithKeywords, by example). But the C struct declaration (PyMethodDef) has a fixed type. See http://docs.python.org/api/common-structs.html 2) When returning None, why use the idiom: Py_INCREF(Py_None); return Py_None; instead of: return Py_BuildValue(); Because it's a lot faster and clear? -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Database in memory
Jim wrote: I have an application that will maintain an in-memory database in the form of a list of lists. Does anyone know of a way to search for and retreive records from such a structure? The answer very much depends on the manner in which you want to do the look-up. If you only need to do exact-match look-up for items with unique keys (e.g. find the single record where SSN=1234567890) then using a dictionary is by far the best solution. It's fast and it's easy. If you expect to do exact-match look-up where the keys are not unique then build a dictionary containing 'set' objects which are the sets of records which have the given key. This lets you neatly find the intersection of selections on multiple criteria (e.g. matches = zipcode_index[94101] hometype_index[condo] ). If you need to do range matching (e.g. 2 = salary 5) then your best bet is to keep a list of the records sorted in the ordering of the key, do a binary search to find where the lower and upper bounds lie within the sorted list and then take a slice. If you also have some index dictionaries containing sets then you can combine these two methods with something like 'matches = set(salary_index[lo_sal:hi_sal]) zipcode_index[81435] ' Having said all that, if you think that there is any possibility that you might ever want to expand the functionality of your program to require either (a) more complex and flexible searching and/or (b) putting the database somewhere else, then I would strongly suggest that you use PySQLite. SQLite is an efficient in-memory database with an SQL engine and the Python interface conforms to the DB-API spec, so you won't need to change your code (much) if you want to move the database to some MySQL, Oracle, Sybase or DB2 server at a later date. Furthermore SQLite is included in Python 2.5 as standard. -- http://mail.python.org/mailman/listinfo/python-list
Re: Plugin architecture - how to do?
Take a look at Trac. This might give you some ideas. http://trac.edgewall.org/wiki/TracDev/ComponentArchitecture -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 2007-04-10, Carsten Haese [EMAIL PROTECTED] wrote: On 10 Apr 2007 07:31:13 GMT, Antoon Pardon wrote On 2007-04-06, Carsten Haese [EMAIL PROTECTED] wrote: If you have a use case for tuple.index, please show it to me, and I'll show you what you should be using instead of a tuple. No wonder no convincing use cases for tuples have shown up. You just defined use cases of tuples as unconvincing. It's not a definition, it's an observation. I'm simply saying that all use cases I've seen for tuple.index could be written in a clearer fashion by using something else. Please prove me wrong by supplying a use case of tuple.index that can not be improved by rewriting. No it is a defintion because it states this can be done for every possible case, even cases you have no idea about. Note that I have proved elsewhere on this thread that any real use case for tuple.index will involve an operation to explicitly use an index different from the one obtained by the call to tuple.index(). I'd like to hear your opinion on this. And what relevance would such a proof have? My personal opinion is that lack of use cases are used too much as an excuse. Limiting the development of your language to use cases makes your language less consistent and so makes your language less easy to learn. That is your opinion, and you are entitled to your opinion. My opinion is that adding features that don't have any uses just weigh the language down unnecessarily, and they distract programmers from finding the best solution to their problem. Adding the index method to tuples is not adding a feature. It is removing a limitation. Writing an index function in python that works with whatever sequence is dead easy. So if the python core implementation only works with a specific sequence that is putting on unnecessary limitations. Of course it also limits the language to what the developers can think off. Initially, yes, but if enough use cases exist for a feature that the developers didn't think of, it will be implemented. Which means your language will not be that usefull for a number of things until you have frustrated enough people. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: pluie documentation in english
On Apr 10, 3:14 am, Méta-MCI [EMAIL PROTECTED] wrote: Bonjour ! Avec Internet-Explorer 6 : Dans Internet-explorer, par le menu, faire : Outils + Options_internet Aller sur le dernier onglet (Avancé), et cocher : autoriser le contenu actif (désolé pour le français, mais mon anglais est vraiment trop mauvais). Et, merci pour l'info, ça m'a permis d'ajouter un item à la F.A.Q. @-salutations -- Michel Claveau with windows the .py files are executable as a link so that it doesn't have to comunicate with the program it can just hang out and be a web page.. I like the grid I was looking at is there a way to add lines after the web page has been created??? avec des fenêtres les dossiers de py sont exécutables comme lien de sorte qu'il pas ait dû comunicate avec le programme que ce peut juste traîner et être une page Web. J'aime la grille que je regardais est là une manière d'ajouter des lignes après que la page Web ait été créée ? ? ? .. -- http://mail.python.org/mailman/listinfo/python-list
Re: pluie documentation in english
On Apr 10, 3:14 am, Méta-MCI [EMAIL PROTECTED] wrote: Bonjour ! Avec Internet-Explorer 6 : Dans Internet-explorer, par le menu, faire : Outils + Options_internet Aller sur le dernier onglet (Avancé), et cocher : autoriser le contenu actif (désolé pour le français, mais mon anglais est vraiment trop mauvais). Et, merci pour l'info, ça m'a permis d'ajouter un item à la F.A.Q. @-salutations -- Michel Claveau with windows the .py files are executable as a link so that it doesn't have to comunicate with the program it can just hang out and be a web page.. I like the grid I was looking at is there a way to add lines after the web page has been created??? avec des fenêtres les dossiers de py sont exécutables comme lien de sorte qu'il pas ait dû comunicate avec le programme que ce peut juste traîner et être une page Web. J'aime la grille que je regardais est là une manière d'ajouter des lignes après que la page Web ait été créée ? ? ? .. -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
Antoon Pardon [EMAIL PROTECTED] wrote: On 2007-04-10, Duncan Booth [EMAIL PROTECTED] wrote: There is a cost to every new language feature: it has to be implemented, documented, maintained, and above all learned by the users. Good design involves, in part, not adding to these burdens except where there is a benefit at least equal to the cost. So what is the easiest to learn: All sequences have an index method or Such and so sequences have an index method and others don't Which of the above is the easiest to document? The second would be if it were true. However it would mean you would have to add an index method to *all* sequences. FWIW, The current documentation says that 's.index' is a method defined on all *mutable* sequence types: almost as simple as your second wording but unfortunately misleading since strings also have index. If someone states: Show me your use case for using tuple.index and I will show you how to avoid it. or words to that effect I think there is little use trying. I genuinely cannot think of a use case. I didn't ask you to suggest one so I could show you how to avoid it, I asked you to suggest one so that we could take the discussion from the purely hypothetical to a more concrete discussion of whether it would be a worthwhile enhancement. Fair enough though. I'll assume you cannot think of a suitable use case either. -- http://mail.python.org/mailman/listinfo/python-list
Re: Hosting Companies: Help for Python Users?
Neil Hodgson wrote: Steve Holden: Dennis Lee Beiber: Too many 3rd-party modules still aren't available in 2.5 versions for my tastes... This applies particularly (though not exclusively) to the Windows platform, for various reasons -- the most common one is that Linux developers frequently don't have a Windows machine available to help them test their builds and ensure that distributions are available. I am trying to address this problem, initially by making hosted Windows machines available for use as buildbots. I'd like to see this integrated in the Cheese Shop. I recently released a small extension class and provided a source distribution and a single binary for Python 2.5 on Windows. While I have the compilers needed for building back to 1.5, most people don't and even when you do it is complex to set up an environment for each version to compile successfully. Well, that's a great idea but it's ambitious. I'm not sure how we could give access to all the developers of Cheese Shop packages who would like to define a Windows build. Your skills and knowledge could clearly be valuable here. It would be great if you could upload a source distribution and mark it as containing files that need compilation for each version - or a subset of versions if you know it requires particular features. Then the compilation is farmed out to machines set up for each Python version and when the compilation is finished, a status display shows the set that are available and which failed along with a link to see the compilation log. A unit test could be optionally included in an upload that would contribute to whether the build is marked good. It would indeed be great, and this was my original grand conception. Given that it will all have to be supported by volunteer effort, though, I can't commit to providing these features much as I would like to see them available - much more is needed in the way of community support before we can advertise what's effectively a compile farm for each Python version (and then we would need to take the various different Windows-supported hardware architectures into account). Please don't think I am trying to pour cold water on your enthusiasm, I really do believe that what you describe would be a great facility. I am just trying to temper the enthusiasm with a modest dose of reality. If we could get enough offers of hosted machines and buildbot management I would love to see this come to fruition. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On Tue, 2007-04-10 at 12:29 +, Antoon Pardon wrote: On 2007-04-10, Carsten Haese [EMAIL PROTECTED] wrote: On 10 Apr 2007 07:31:13 GMT, Antoon Pardon wrote On 2007-04-06, Carsten Haese [EMAIL PROTECTED] wrote: If you have a use case for tuple.index, please show it to me, and I'll show you what you should be using instead of a tuple. No wonder no convincing use cases for tuples have shown up. You just defined use cases of tuples as unconvincing. It's not a definition, it's an observation. I'm simply saying that all use cases I've seen for tuple.index could be written in a clearer fashion by using something else. Please prove me wrong by supplying a use case of tuple.index that can not be improved by rewriting. No it is a defintion because it states this can be done for every possible case, even cases you have no idea about. That would be a theorem or conjecture, not a definition. You can call it definition or banana or screwdriver if you like, but that's not going to disprove it. Note that I have proved elsewhere on this thread that any real use case for tuple.index will involve an operation to explicitly use an index different from the one obtained by the call to tuple.index(). I'd like to hear your opinion on this. And what relevance would such a proof have? It proves at that every conceivable use case for tuple.index, including the ones I am not thinking of, will never directly use the index obtained from calling tuple.index(). Such a use case will be poorly self-documented, and a clearer implementation can be found by avoiding tuple.index(). I'll illustrate this on the one concrete use case that was suggested on this thread: In a game where the sequence of players is given by the tuple p, find the opponents of the current player. One hypothetical solution is to find the index if the current player and then slice and reassemble the tuple: i = p.index(current_player) opponents = p[:i-1] + p[i+1:] An alternative is this: opponents = tuple(x for x in p if x is not current_player) You may disagree, but in my opinion, the alternative is better because it is a more natural translation of the concept that the opponents of the current player are all players that are not the current player. Adding the index method to tuples is not adding a feature. It is removing a limitation. The non-existence of tuple.index is only a limitation if there is a need for the method to exist. Please prove that this need exists. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: [offtopic?] problem with UDP broadcast on Windows XP
Hendrik van Rooyen wrote: Irmen de Jong [EMAIL PROTECTED] wrote: Gabriel Genellina wrote: Try running the service impersonating another user (not LOCAL_SERVICE, the default). You can change that from the service control panel. Alas, that didn't change anything. I made it run as a user account that has admin privileges even, and it still doesn't respond to the broadcasts. :-( I am not sure if this is at all relevant - but I seem to recall seeing something once that had a list of socket numbers, splitting them between UDP TCP - can the socket actually rx UDP? That's probably a red herring, Hendrik. Both UDP and TCP define ports from 1 through 65535, and so a port number doesn't belong to one protocol or the other. It's most likely, I suspect without knowing to much about it, that the service is stalling because of a failure to pump Windows messages. Irmen, are you taking any action in your service to ignore Windows messages that your service process receives? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: setup() and C extensions
On Mon, 2007-04-09 at 23:35 -0700, 7stud wrote: 2) When returning None, why use the idiom: Py_INCREF(Py_None); return Py_None; instead of: return Py_BuildValue(); As Gabriel said, the preferred idiom is faster and clearer. Sufficiently recent Pythons define the macro Py_RETURN_NONE for the preferred idiom. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 2007-04-10, Duncan Booth [EMAIL PROTECTED] wrote: Antoon Pardon [EMAIL PROTECTED] wrote: On 2007-04-10, Duncan Booth [EMAIL PROTECTED] wrote: There is a cost to every new language feature: it has to be implemented, documented, maintained, and above all learned by the users. Good design involves, in part, not adding to these burdens except where there is a benefit at least equal to the cost. So what is the easiest to learn: All sequences have an index method or Such and so sequences have an index method and others don't Which of the above is the easiest to document? The second would be if it were true. However it would mean you would have to add an index method to *all* sequences. FWIW, The current documentation says that 's.index' is a method defined on all *mutable* sequence types: almost as simple as your second wording but unfortunately misleading since strings also have index. Which illustrate that the mutable unmutable distinction is not very usefull to decide whether a sequence could use index or not. If someone states: Show me your use case for using tuple.index and I will show you how to avoid it. or words to that effect I think there is little use trying. I genuinely cannot think of a use case. I didn't ask you to suggest one so I could show you how to avoid it, I asked you to suggest one so that we could take the discussion from the purely hypothetical to a more concrete discussion of whether it would be a worthwhile enhancement. I have given a use case in an other article in this thread. Feel free to comment. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 2007-04-10, Carsten Haese [EMAIL PROTECTED] wrote: Adding the index method to tuples is not adding a feature. It is removing a limitation. The non-existence of tuple.index is only a limitation if there is a need for the method to exist. Please prove that this need exists. It doesn't because need is such a strong word, that just the fact that you can write your own index function means the method isn't needed. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 2007-04-10, Carsten Haese [EMAIL PROTECTED] wrote: On 10 Apr 2007 09:48:41 GMT, Antoon Pardon wrote If someone states: Show me your use case for using tuple.index and I will show you how to avoid it. or words to that effect I think there is little use trying. Or maybe you just can't think of any good use cases, and that's annoying you because it proves my point. Please, prove me wrong by showing use cases for tuple.index that can't be rewritten. No you just have proven my point. I predicted that whatever use case would be given, people would stand ready to rewrite is and use those rewritals as argument againt the use case. Here you are ready to do just that. Since you can just write an index function that works with any sequence or you could simply write something like list(tup).index('...'), any code that would use tupple.index can be rewritten to do without. But that is not such a strong argument. Should the case be reversed and tuples have an index method and lists not, you would be able to rewrite any code that would use list.index into code that wouldn't. But if you are so eager to rewrite, how about the following: I am using the struct module to get binary data from a file. Sometimes I want to skip until I find a particular binary number. Somewhat simplified it looks like this: class Itemfile: def __init__(self, fn): self.fl = open(fn) self.ix = 80 def nextitem(self): if self.ix == 80: self.buf = struct.unpack(80i, self.fl.read(320)) self.ix = 0 result = self.buf[self.ix] self.ix += 1 return result def skipuntil(self, val): done = False while not done: try: self.ix = self.buf.index(val, self.ix) done = True except ValueError: self.ix = 0 self.buf = struct.unpack(80i, self.fl.read(320)) Now I'm sure you can rewrite this without the need of tuple.index. It just seems odd that I have to go through extra hoops here to get the effect of tuple.index because struct.unpack returns its result in a tuple and a tuple doesn't provide index. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Broken pipe with os.popen3()
Hello everybody, I try to use an external OCR tool to convert some binary image data to text. The image is in one variable, the text should be converted to another. I use the following code: (si, so, se) = os.popen3('ocrad') si.write(frame) si.close() messagetext += so.read() This code leads to a broken pipe error. I think this is because of the command already writing data to stdout after getting the first part of the input. But when I change the order of the code lines, i.e. opening the reading pipe so before writing to si, the program hangs, because no data is written to stdout before the first bytes are written to stdin. Any idea how to solve this issue? How do I read and write simultaneously? Thanks in advance, Christoph -- http://mail.python.org/mailman/listinfo/python-list
Python Speech tools
Hi list I intend to design a Speech Recognition system.Can I have some pointers to the available Python speech tools? Till date I am aware of only Python bindings for a speech tool called Snack (http://www.speech.kth.se/snack/) Any help will be appreciated. -- Amit K Saha [EMAIL PROTECTED] Send instant messages to your online friends http://in.messenger.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
Paul Boddie wrote: On 10 Apr, 11:48, Antoon Pardon [EMAIL PROTECTED] wrote: On 2007-04-10, Duncan Booth [EMAIL PROTECTED] wrote: There is a cost to every new language feature: it has to be implemented, documented, maintained, and above all learned by the users. Good design involves, in part, not adding to these burdens except where there is a benefit at least equal to the cost. So what is the easiest to learn: All sequences have an index method or Such and so sequences have an index method and others don't I think this observation leads to insights both at the end-user level and at the implementer level. Tuples and lists are sequences; the index method can be defined generically for all sequences; adding such a method to the tuple type can be done with barely any changes to the implementation taken from the list type. This leads to the observation that a generic index method (defined as a function in the implementation) could be made to work with both lists and tuples, and that various other methods might also be defined similarly, although things like append, extend and other mutating methods wouldn't be appropriate for a tuple. A generic definition of index would be tricky, though, if you wanted to include strings as sequences. In that case you aren't testing for the presence of a single element but a sub-sequence - I think this change was introduced in 2.4 to allow checks like men in three good men to succeed where formerly only single characters could be checked for. One might perversely allow extension to lists and tuples to allow [3, 4] in [1, 2, 3, 4, 5, 6] to succeed, but that's forcing the use case beyond normal limits. The point I am trying to make is that circumstances alter cases, and that we can't always rely on our intuition to determine how specific methods work, let alone whether they are available. I hear the screams of just add the index() method to tuples and have done with it and, to an extent, can sympathize with them. But that way lies creeping featurism and the next thing you know we'll have a ternary operator in the language - oh wait, we do now! Which of the above is the easiest to document? Now with implementation and maintaining. If you would start with a class of sequence which classes like tuple and list would inherit from, then there also would be a single function to be implemented and maintained. It would just be usable in more types. There isn't a big win in this case: the intersection of useful methods between mutable and immutable sequence types is rather small. Nevertheless, providing a slightly deeper abstract class hierarchy might be appropriate, and this is being considered for Python 3000. [...] The same happened with the ternary operator. Every use case someone could come up with was rejected by rewriting the code without using a ternary operator. AFAICS the only reason the ternary operator finaly got introduced was because a python developer was bitten by an illusive bug, introduced by one of the idioms that was often used as a way to simulate a ternary operator. The ternary operator, whilst providing new and occasionally useful functionality, is rather badly phrased in my opinion: when used, it's a bit like reading one natural language and suddenly having the grammar of another in use for the rest of the sentence. Indeed the syntax is deliberately crippled - Guido's reasoning being, I believe, that if it were too easy and natural to use then people would use it inappropriately and too frequently. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On Tue, 2007-04-10 at 13:21 +, Antoon Pardon wrote: But if you are so eager to rewrite, how about the following: I am using the struct module to get binary data from a file. Sometimes I want to skip until I find a particular binary number. Somewhat simplified it looks like this: class Itemfile: def __init__(self, fn): self.fl = open(fn) self.ix = 80 def nextitem(self): if self.ix == 80: self.buf = struct.unpack(80i, self.fl.read(320)) self.ix = 0 result = self.buf[self.ix] self.ix += 1 return result def skipuntil(self, val): done = False while not done: try: self.ix = self.buf.index(val, self.ix) done = True except ValueError: self.ix = 0 self.buf = struct.unpack(80i, self.fl.read(320)) Now I'm sure you can rewrite this without the need of tuple.index. It just seems odd that I have to go through extra hoops here to get the effect of tuple.index because struct.unpack returns its result in a tuple and a tuple doesn't provide index. Your data is an array. Choosing a data structure that doesn't fit your data is always going to cause pain. Instead of using struct.unpack, you should use array.array, and voila!, you get an index method. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Speech tools
On Apr 10, 2:15 pm, Amit K Saha [EMAIL PROTECTED] wrote: Hi list I intend to design a Speech Recognition system.Can I have some pointers to the available Python speech tools? Till date I am aware of only Python bindings for a speech tool called Snack (http://www.speech.kth.se/snack/) Any help will be appreciated. -- Amit K Saha [EMAIL PROTECTED] Send instant messages to your online friendshttp://in.messenger.yahoo.com I've played with the win32 module's text-to-speech abilities a little. You may be able to get ideas from that. Here's a link to more info: http://surguy.net/articles/speechrecognition.xml http://www.cs.unc.edu/~parente/tech/tr02.shtml This isn't pure Python, but it may be helpful as well: http://sourceforge.net/projects/VoiceCode/ Good luck! Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Broken pipe with os.popen3()
Christoph Krammer wrote: Hello everybody, I try to use an external OCR tool to convert some binary image data to text. The image is in one variable, the text should be converted to another. I use the following code: (si, so, se) = os.popen3('ocrad') si.write(frame) si.close() messagetext += so.read() If you use popen you should use *one* filehandle. The app hangs because the buffer is full. See http://docs.python.org/lib/popen2-flow-control.html -- Thomas Güttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On Tue, 2007-04-10 at 09:57 -0400, Steve Holden wrote: I hear the screams of just add the index() method to tuples and have done with it and, to an extent, can sympathize with them. But that way lies creeping featurism and the next thing you know we'll have a ternary operator in the language - oh wait, we do now! It would indeed be much easier to just give up. However, the resistance to tuple.index is more than a generic resistance to feature creep. As I have demonstrated elsewhere on this thread, any use case for tuple.index will be inherently obfuscated. Code clarity is a major design goal of Python, and adding tuple.index would be contrary to this goal. I'm just a user with no influence on the development of Python itself, but in my humble opinion, the non-existence of tuple.index is more pythonic than its existence would be. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with getting an option value
Peter Otten wrote: Lucas Malor wrote: The problem is options is an instance, so options.delete, for example, is wrong; I should pass options.delete . How can I do? Use getattr(): Thank you. Do you know also if I can do a similar operation with functions? I want to select with a string a certain get() function of ConfigParser: if type == int : funcname = getint elif type == bool : funcname = getboolean etc. How can I invoke the funcion with its name in a string? PS: your answers had not arrived to my mail account. Is because I'm using a disposal address? Or simply it's because I'm not registered to the list? -- Protect yourself from spam, use http://sneakemail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 10 Apr, 15:57, Steve Holden [EMAIL PROTECTED] wrote: The point I am trying to make is that circumstances alter cases, and that we can't always rely on our intuition to determine how specific methods work, let alone whether they are available. But it's telling that by adopting precisely the implementation that we currently have for lists, we can have a tuple method which does what most people would reasonably expect. Why are we suddenly getting single characters instead of whole strings? people have presumably exclaimed often enough, illustrating that the sequence nature of strings is a controversial topic. Lists and tuples, however, don't have such controversial baggage. I hear the screams of just add the index() method to tuples and have done with it and, to an extent, can sympathize with them. But that way lies creeping featurism and the next thing you know we'll have a ternary operator in the language - oh wait, we do now! Yes, but the cost of adding index to tuples is minimal, and the mental cost to programmers is arguably negative. Meanwhile, we now have to put up with the syntactic bodge that is the ternary operator until the time comes when it gets deprecated as something that didn't work out or wasn't really necessary (in Python 4000, perhaps), meaning that we now have to read third-party code more carefully, the people writing editors and tools have to change their lexers/parsers again, and so on. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Breaking up Strings correctly:
En Tue, 10 Apr 2007 08:12:53 -0300, Michael Yanowitz [EMAIL PROTECTED] escribió: I guess what I was looking for was something simpler than parsing. I may actually use some of what you posted. But I am hoping that if given a string such as: '((($IP = 127.1.2.3) AND ($AX 15)) OR (($IP = 127.1.2.4) AND ($AY != 0)))' something like split(), where I can pass it something like [' AND ', ' OR ', ' XOR '] will split the string by AND, OR, or XOR. BUT split it up in such a way to preserve the parentheses order, so that it will split on the outermost parenthesis. So that the above string becomes: ['OR', '(($IP = 127.1.2.3) AND ($AX 15))', '(($IP = 127.1.2.4) AND ($AY != 0))'] No need to do this recursively, I can repeat the process, however if I wish on each string in the list and get: ['OR', ['AND', '($IP = 127.1.2.3)', '($AX 15)'], ['AND', '($IP = 127.1.2.4)', '($AY != 0)']] Can this be done without parsers? This is exactly what parsers do. Sure, it can be done without using a preexistent general parser, but you'll be writing your own specialized one by hand. Perhaps with some variation of re or split. Regular expressions cannot represent arbitrary expressions like yours (simply because they're not regular). If you know beforehand that all input has some fixed form, like condition AND condition OR condition AND condition, or at least a finite set of fixed forms, it could be done with many re's. But I think it's much more work than using PyParsing or similar tools. If you have some bizarre constraints (parserphobia?) or for whatever reason don't want to use such tools, the infix evaluator posted yesterday by Gerard Flanagan could be an alternative (it only uses standard modules). Has something like this already been written? Yes, hundreds of times since programmable computers exist: they're known as lexers and parsers :) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is __getslice__ still implemented?
Torsten Bronger wrote: Hallöchen! According to http://docs.python.org/ref/sequence-methods.html, __getslice__ is deprecated. At the moment, I derive an own class from unicode and want to implement my own slicing. I found that I have to override __getslice__ since __getitem__ isn't called when I have something like my_instance[a:b] in my code. According to news:[EMAIL PROTECTED], this may have efficiency reasons, however, I agree with news:[EMAIL PROTECTED] that this is quite confusing. It forces people to implement a deprecated function after all. I think the docs should say that you still have to override __getslice__ when subclassing from a built-in type, unless I really don't understand the issue correctly. Yes, you do still need to implement __getslice__ if you're subclassing a class (like unicode or list) which provides it. The __getslice__ method can't be removed entirely for backwards compatibility reasons (though it is being removed in Python 3000). If you have a specific suggestion for what doc should be updated and how, that would be helpful. Please post it to: http://sourceforge.net/tracker/?group_id=5470atid=105470 (It doesn't need to be a real patch. Plain text is fine as long as you indicate where in the documentation it needs to go.) Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is __getslice__ still implemented?
On Tue, 10 Apr 2007 08:35:56 -0600, Steven Bethard [EMAIL PROTECTED] wrote: Torsten Bronger wrote: Hallöchen! According to http://docs.python.org/ref/sequence-methods.html, __getslice__ is deprecated. At the moment, I derive an own class from unicode and want to implement my own slicing. I found that I have to override __getslice__ since __getitem__ isn't called when I have something like my_instance[a:b] in my code. According to news:[EMAIL PROTECTED], this may have efficiency reasons, however, I agree with news:[EMAIL PROTECTED] that this is quite confusing. It forces people to implement a deprecated function after all. I think the docs should say that you still have to override __getslice__ when subclassing from a built-in type, unless I really don't understand the issue correctly. Yes, you do still need to implement __getslice__ if you're subclassing a class (like unicode or list) which provides it. The __getslice__ method can't be removed entirely for backwards compatibility reasons (though it is being removed in Python 3000). If you have a specific suggestion for what doc should be updated and how, that would be helpful. Please post it to: Why does this mean that the unicode type has to implement __getslice__? Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
Carsten Haese wrote: On Tue, 2007-04-10 at 09:57 -0400, Steve Holden wrote: I hear the screams of just add the index() method to tuples and have done with it and, to an extent, can sympathize with them. But that way lies creeping featurism and the next thing you know we'll have a ternary operator in the language - oh wait, we do now! It would indeed be much easier to just give up. However, the resistance to tuple.index is more than a generic resistance to feature creep. As I have demonstrated elsewhere on this thread, any use case for tuple.index will be inherently obfuscated. Code clarity is a major design goal of Python, and adding tuple.index would be contrary to this goal. I'm just a user with no influence on the development of Python itself, but in my humble opinion, the non-existence of tuple.index is more pythonic than its existence would be. I quite agree. I was not advocating it as a serious course of action, more admiring its noise-reduction potential. I'm no great fan of the if ... else expression either, come to that. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
convert html entities into real chars
Hi, I would like to have a function that can convert 'gt;' into '', 'amp;' into '' etc. I could not find how to do it easily (I have a code snippet for the opposite). Thanks, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: Check for keypress on Linux xterm ?
Grant Edwards wrote: On 2007-04-09, hlubenow [EMAIL PROTECTED] wrote: My problem is, I don't want my program to wait for the keypress. I just want to check, if a key is currently pressed and if not, I'd like to continue with my program (like INKEY$ in some BASIC-dialects). The answer to this frequently asked question is actually in the FAQ: http://www.python.org/doc/faq/library.html#how-do-i-get-a-single-keypress-at-a-time Google finds us further examples: http://mail.python.org/pipermail/pythonmac-sig/2004-February/010140.html http://mail.python.org/pipermail/python-list/2000-June/041251.html You're answer is only less than half correct: Most of the given examples use something like c = sys.stdin.read(1) like my example does. This blocks input. At the end of your last link the author there says it. He also shows some ways into my direction. I'll test them. H. -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 4/10/07, Carsten Haese [EMAIL PROTECTED] wrote: i = p.index(current_player) opponents = p[:i-1] + p[i+1:] An alternative is this: opponents = tuple(x for x in p if x is not current_player) You may disagree, but in my opinion, the alternative is better because it is a more natural translation of the concept that the opponents of the current player are all players that are not the current player. Your alternative is wrong because it wont raise ValueError if current_player is not present in the tuple. Please revise your solution. -- mvh Björn -- http://mail.python.org/mailman/listinfo/python-list
Re: convert html entities into real chars
I would like to have a function that can convert 'gt;' into '', 'amp;' into '' etc. I could not find how to do it easily (I have a code snippet for the opposite). Found it, sorry def convertentity(m): Convert a HTML entity into normal string (ISO-8859-1) if m.group(1)=='#': try: return chr(int(m.group(2))) except ValueError: return '#%s;' % m.group(2) try: return htmlentitydefs.entitydefs[m.group(2)] except KeyError: return '%s;' % m.group(2) def unquotehtml(s): Convert a HTML quoted string into normal string (ISO-8859-1). Works with #XX; and with nbsp; gt; etc. return re.sub(r'(#?)(.+?);',convertentity,s) -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 4/10/07, Steve Holden [EMAIL PROTECTED] wrote: Paul Boddie wrote: On 10 Apr, 11:48, Antoon Pardon [EMAIL PROTECTED] wrote: On 2007-04-10, Duncan Booth [EMAIL PROTECTED] wrote: There is a cost to every new language feature: it has to be implemented, documented, maintained, and above all learned by the users. Good design involves, in part, not adding to these burdens except where there is a benefit at least equal to the cost. So what is the easiest to learn: All sequences have an index method or Such and so sequences have an index method and others don't I think this observation leads to insights both at the end-user level and at the implementer level. Tuples and lists are sequences; the index method can be defined generically for all sequences; adding such a method to the tuple type can be done with barely any changes to the implementation taken from the list type. This leads to the observation that a generic index method (defined as a function in the implementation) could be made to work with both lists and tuples, and that various other methods might also be defined similarly, although things like append, extend and other mutating methods wouldn't be appropriate for a tuple. A generic definition of index would be tricky, though, if you wanted to include strings as sequences. In that case you aren't testing for the presence of a single element but a sub-sequence - I think this change was introduced in 2.4 to allow checks like men in three good men to succeed where formerly only single characters could be checked for. One might perversely allow extension to lists and tuples to allow [3, 4] in [1, 2, 3, 4, 5, 6] to succeed, but that's forcing the use case beyond normal limits. The point I am trying to make is that circumstances alter cases, and that we can't always rely on our intuition to determine how specific methods work, let alone whether they are available. I'd love to have that! There are at least one million use cases for finding a sequence in a sequence and implementing it yourself is non-trivial. Plus then both list and tuple's index methods would work *exactly* like string's. It would be easier to document and more useful. A big win. Indeed the syntax is deliberately crippled - Guido's reasoning being, I believe, that if it were too easy and natural to use then people would use it inappropriately and too frequently. There are no appropriate use cases for that feature. Maybe not for tuple.index either, but increasing consistency and being able to say ALL sequences have an index method that works like THIS would be a big win. Unfortunately, it really is the string type that screws up the symmetry. -- mvh Björn -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with getting an option value
Lucas Malor a écrit : Peter Otten wrote: Lucas Malor wrote: The problem is options is an instance, so options.delete, for example, is wrong; I should pass options.delete . How can I do? Use getattr(): Thank you. Do you know also if I can do a similar operation with functions? I want to select with a string a certain get() function of ConfigParser: if type == int : funcname = getint elif type == bool : funcname = getboolean etc. You should use a dict to do the dispatch: funcs = {'int':getint, 'bool', getboolean, ...} Then you just have to: result = funcs[type](args...) How can I invoke the funcion with its name in a string? If you used the full import, ie: import ConfigParser you can use getattr() on the ConfigParser module object (yes, modules are objects). If you directly imported the functions in your own module/script namespace, using either from ConfigParser import some_func or import ConfigParser.some_func as some_func then there's the globals() function that returns a dict of all names=objects defined in the namespace, so you can use: globals()['some_func'](args) HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with getting an option value
Lucas Malor wrote: Peter Otten wrote: Lucas Malor wrote: The problem is options is an instance, so options.delete, for example, is wrong; I should pass options.delete . How can I do? Use getattr(): Thank you. Do you know also if I can do a similar operation with functions? I want to select with a string a certain get() function of ConfigParser: if type == int : funcname = getint elif type == bool : funcname = getboolean etc. How can I invoke the funcion with its name in a string? PS: your answers had not arrived to my mail account. Is because I'm using a disposal address? Or simply it's because I'm not registered to the list? -- Protect yourself from spam, use http://sneakemail.com Use a dispatch dictionary: dispatch={'int': getint, 'bool': getboolean} then call it: dispatch(t)(*args) Note: You should NOT use type as a variable name because it will shadow the built-in type function. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
Paul Boddie wrote: On 10 Apr, 15:57, Steve Holden [EMAIL PROTECTED] wrote: The point I am trying to make is that circumstances alter cases, and that we can't always rely on our intuition to determine how specific methods work, let alone whether they are available. But it's telling that by adopting precisely the implementation that we currently have for lists, we can have a tuple method which does what most people would reasonably expect. Why are we suddenly getting single characters instead of whole strings? people have presumably exclaimed often enough, illustrating that the sequence nature of strings is a controversial topic. Lists and tuples, however, don't have such controversial baggage. You can call something non-controversial when it generates a thread like this? :-) It's really a storm in a teacup. The acid test would be to generate a patch that added the method and then see if you could get a committer to commit it. All else (including my own contributions) is mere hot air. I hear the screams of just add the index() method to tuples and have done with it and, to an extent, can sympathize with them. But that way lies creeping featurism and the next thing you know we'll have a ternary operator in the language - oh wait, we do now! Yes, but the cost of adding index to tuples is minimal, and the mental cost to programmers is arguably negative. Meanwhile, we now have to put up with the syntactic bodge that is the ternary operator until the time comes when it gets deprecated as something that didn't work out or wasn't really necessary (in Python 4000, perhaps), meaning that we now have to read third-party code more carefully, the people writing editors and tools have to change their lexers/parsers again, and so on. What can I say? Every language has warts. Some people were as anxious to see if ... else (which I regard as a wart) put in as others are to see tuple.index(). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: convert html entities into real chars
Laszlo Nagy wrote: Hi, I would like to have a function that can convert 'gt;' into '', 'amp;' into '' etc. I could not find how to do it easily (I have a code snippet for the opposite). Thanks, Laszlo You can use htmlentitydefs module to help with this. import htmlentitydefs chr(htmlentitydefs.name2codepoint['gt']) and (to go the other way) htmlentitydefs.codepoint2name[ord('')] -Larry -- http://mail.python.org/mailman/listinfo/python-list
installing pyqt4 on ubuntu 6.06
Hello, I have a newly installed ubuntu 6.06 system. I am trying to install pyqt4 on it, but without success. The contents of the /etc/apt/sources.list file are: deb http://in.archive.ubuntu.com/ubuntu/ dapper main restricted universe deb http://in.archive.ubuntu.com/ubuntu/ dapper-backports main restricted universe multiverse deb http://security.ubuntu.com/ubuntu dapper-security main universe deb http://in.archive.ubuntu.com/ubuntu/ dapper-updates main restricted I've tried installing everything related to python2.4 and qt4, including sip, pyqt-tools, etc. However, on running a pyqt script, it gives me the following error: Traceback (most recent call last): File findFiles.py, line 16, in ? from PyQt4 import QtCore, QtGui ImportError: No module named PyQt4 Any pointers regarding what packages should i install to get the system into working condition would be very helpful Thanks a lot -- warm regards, Pradnyesh Sawant -- Be yourself..everyone else is taken. --Anon -- http://mail.python.org/mailman/listinfo/python-list
Parsing log in SQL DB to change IPs to hostnames
Hi, I am brand new to Python. In learning anything, I find it useful to actually try to write a useful program to try to tackle an actual problem. I have a syslog server and I would like to parse the syslog messages and try to change any ips to resolved hostnames. Unfortunately, I am not getting any matches on my regular expression. A message will look something like this: Apr 10 2007 00:30:58 DEVICE : %DEVICEINFO: 1.1.1.1 Accessed URL 10.10.10.10:/folder/folder/page.html I would like to change the message to have the hostnames, or even better actually, have it appear as hostname-ip address. So a changed message would look like: Apr 10 2007 00:30:58 DEVICE : %DEVICEINFO: pcname-1.1.1.1 Accessed URL www.asite.com-10.10.10.10:/folder/folder/page.html or some equivalent. Here is what i have so far. Please be kind as it is my first python program :) #! /usr/bin/python import socket import re import string import MySQLdb ipRegExC = r\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} ipRegEx = re.compile(ipRegExC) try: conn = MySQLdb.connect(host=REMOVED, user=REMOVED, passwd=REMOVED, db=REMOVED) except MySQLdb.Error, e: print Error connecting to the database: %d - %s % (e.args[0], e.args[1]) sys.exit(1) cursor = conn.cursor() cursor.execute(SELECT msg, seq FROM `logs` WHERE seq = 507702) # one specific message so that it doesn't parse the whole DB during testing... while(1): row = cursor.fetchone() if row == None: break if ipRegEx.match(row[0]): print regex match! + ipRegEx.match(row[0]) # does not make it here. newMsg = ipRegEx.sub(query(ipRegEx.match(row[0])), row[0]) if newMsg != 0: cursor.execute( UPDATE logs SET msg = %s WHERE seq = d, (newMsg,row[1])) def query(ipAddress): try: return socket.gethostbyaddr(ipAddress)[0] except: return 0 This is built to sub the name... I would like to change it to the hsotname-ipaddress instead since ip's can resolve to many hostnames it runs but does not pass the if statements so it quietly does absolutely nothing :) Thanks so much for any advice -- http://mail.python.org/mailman/listinfo/python-list
Re: installing pyqt4 on ubuntu 6.06
On Tue, 10 Apr 2007 21:05:37 +0530, Pradnyesh Sawant [EMAIL PROTECTED] wrote: Hello, I have a newly installed ubuntu 6.06 system. I am trying to install pyqt4 on it, but without success. The contents of the /etc/apt/sources.list file are: deb http://in.archive.ubuntu.com/ubuntu/ dapper main restricted universe deb http://in.archive.ubuntu.com/ubuntu/ dapper-backports main restricted universe multiverse deb http://security.ubuntu.com/ubuntu dapper-security main universe deb http://in.archive.ubuntu.com/ubuntu/ dapper-updates main restricted I've tried installing everything related to python2.4 and qt4, including sip, pyqt-tools, etc. However, on running a pyqt script, it gives me the following error: Traceback (most recent call last): File findFiles.py, line 16, in ? from PyQt4 import QtCore, QtGui ImportError: No module named PyQt4 Any pointers regarding what packages should i install to get the system into working condition would be very helpful Thanks a lot Qt4 Python bindings aren't available in 6.06, afaik. I don't think they were even available at the time it was released. 6.10 has them, though. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On Tue, 2007-04-10 at 17:10 +0200, BJörn Lindqvist wrote: On 4/10/07, Carsten Haese [EMAIL PROTECTED] wrote: i = p.index(current_player) opponents = p[:i-1] + p[i+1:] An alternative is this: opponents = tuple(x for x in p if x is not current_player) You may disagree, but in my opinion, the alternative is better because it is a more natural translation of the concept that the opponents of the current player are all players that are not the current player. Your alternative is wrong because it wont raise ValueError if current_player is not present in the tuple. Please revise your solution. You have a point. Here is my revised solution: assert current_player in p opponents = tuple(x for x in p if x is not current_player) The added advantage is that AssertionError is better than IndexError for conveying that a severe program bug has occurred. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On Tue, 2007-04-10 at 11:44 -0400, Carsten Haese wrote: On Tue, 2007-04-10 at 17:10 +0200, BJörn Lindqvist wrote: On 4/10/07, Carsten Haese [EMAIL PROTECTED] wrote: i = p.index(current_player) opponents = p[:i-1] + p[i+1:] An alternative is this: opponents = tuple(x for x in p if x is not current_player) You may disagree, but in my opinion, the alternative is better because it is a more natural translation of the concept that the opponents of the current player are all players that are not the current player. Your alternative is wrong because it wont raise ValueError if current_player is not present in the tuple. Please revise your solution. You have a point. Here is my revised solution: assert current_player in p opponents = tuple(x for x in p if x is not current_player) The added advantage is that AssertionError is better than IndexError for conveying that a severe program bug has occurred. _.replace(IndexError, ValueError), of course. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Check for keypress on Linux xterm ?
Grant Edwards wrote: On 2007-04-09, hlubenow [EMAIL PROTECTED] wrote: My problem is, I don't want my program to wait for the keypress. I just want to check, if a key is currently pressed and if not, I'd like to continue with my program (like INKEY$ in some BASIC-dialects). The answer to this frequently asked question is actually in the FAQ: http://www.python.org/doc/faq/library.html#how-do-i-get-a-single-keypress-at-a-time Google finds us further examples: http://mail.python.org/pipermail/pythonmac-sig/2004-February/010140.html http://mail.python.org/pipermail/python-list/2000-June/041251.html I see now, you're right. Sorry. -- http://mail.python.org/mailman/listinfo/python-list
Re: install wxPython
On Apr 9, 3:20 pm, Marco [EMAIL PROTECTED] wrote: Hi, I have a problem to install wxPython on my MacBook (Pythonversion 2.5). If would install the wxPython (python setup.py install), then I got this error: Traceback (most recent call last): File /Users/marco/Desktop/flexo1/wxpython/wxPython-src-2.8.3.0/ wxPython/setup.py, line 49, in module copy_file('config.py', 'wx/build', update=1, verbose=1) File /Users/marco/python//lib/python2.5/distutils/file_util.py, line 119, in copy_file can't copy '%s': doesn't exist or not a regular file % src distutils.errors.DistutilsFileError: can't copy 'config.py': doesn't exist or not a regular file Where is the problem and how could i fix it? Thx for your answers. marco You need to post this problem to the wxPython user's group at: http://wxpython.org/maillist.php There are a number of Mac users there that should be able to help you. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is __getslice__ still implemented?
Jean-Paul Calderone wrote: On Tue, 10 Apr 2007 08:35:56 -0600, Steven Bethard [EMAIL PROTECTED] wrote: Yes, you do still need to implement __getslice__ if you're subclassing a class (like unicode or list) which provides it. The __getslice__ method can't be removed entirely for backwards compatibility reasons (though it is being removed in Python 3000). Why does this mean that the unicode type has to implement __getslice__? Because code could exist like:: class C(list): ... def __getslice__(self, start, stop): ... return C(list.__getslice__(self, start, stop)) ... type(C([1, 2, 3, 4])[:2]) class '__main__.C' For similar examples, see: http://www.google.com/codesearch?q=list.__getslice__ I couldn't find any real instances of unicode.__getslice__: http://www.google.com/codesearch?q=unicode.__getslice__ But I suspect python-dev wouldn't think it was worth it to remove just unicode.__getslice__ and not all the other ones... STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is __getslice__ still implemented?
On Tue, 10 Apr 2007 09:51:45 -0600, Steven Bethard [EMAIL PROTECTED] wrote: Jean-Paul Calderone wrote: On Tue, 10 Apr 2007 08:35:56 -0600, Steven Bethard [EMAIL PROTECTED] wrote: Yes, you do still need to implement __getslice__ if you're subclassing a class (like unicode or list) which provides it. The __getslice__ method can't be removed entirely for backwards compatibility reasons (though it is being removed in Python 3000). Why does this mean that the unicode type has to implement __getslice__? Because code could exist like:: class C(list): ... def __getslice__(self, start, stop): ... return C(list.__getslice__(self, start, stop)) ... type(C([1, 2, 3, 4])[:2]) class '__main__.C' Ah, excellent point. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 10 Apr, 17:29, Steve Holden [EMAIL PROTECTED] wrote: You can call something non-controversial when it generates a thread like this? :-) It's really a storm in a teacup. The acid test would be to generate a patch that added the method and then see if you could get a committer to commit it. All else (including my own contributions) is mere hot air. The patch is already submitted: http://sourceforge.net/tracker/index.php?func=detailaid=1696444group_id=5470atid=305470 I won't miss tuple.index very often if it never gets in, but it's always enlightening/entertaining to see the rationales given for the rejection of this and other features, in contrast to things like y if x else z which just seem to mysteriously acquire momentum and then power their way in regardless. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing log in SQL DB to change IPs to hostnames
On Apr 10, 8:37 pm, KDawg44 [EMAIL PROTECTED] wrote: Hi, I am brand new to Python. In learning anything, I find it useful to actually try to write a useful program to try to tackle an actual problem. I have a syslog server and I would like to parse the syslog messages and try to change any ips to resolved hostnames. Unfortunately, I am not getting any matches on my regular expression. A message will look something like this: Apr 10 2007 00:30:58 DEVICE : %DEVICEINFO: 1.1.1.1 Accessed URL 10.10.10.10:/folder/folder/page.html I would like to change the message to have the hostnames, or even better actually, have it appear as hostname-ip address. So a changed message would look like: Apr 10 2007 00:30:58 DEVICE : %DEVICEINFO: pcname-1.1.1.1 Accessed URLwww.asite.com-10.10.10.10:/folder/folder/page.html or some equivalent. Here is what i have so far. Please be kind as it is my first python program :) #! /usr/bin/python import socket import re import string import MySQLdb ipRegExC = r\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} ipRegEx = re.compile(ipRegExC) try: conn = MySQLdb.connect(host=REMOVED, user=REMOVED, passwd=REMOVED, db=REMOVED) except MySQLdb.Error, e: print Error connecting to the database: %d - %s % (e.args[0], e.args[1]) sys.exit(1) cursor = conn.cursor() cursor.execute(SELECT msg, seq FROM `logs` WHERE seq = 507702) # one specific message so that it doesn't parse the whole DB during testing... while(1): row = cursor.fetchone() if row == None: break if ipRegEx.match(row[0]): snipped rest of the code See the documentation of the re module for the difference between matching and searching. -- Kushal -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 10 Apr, 17:44, Carsten Haese [EMAIL PROTECTED] wrote: You have a point. Here is my revised solution: assert current_player in p opponents = tuple(x for x in p if x is not current_player) The added advantage is that AssertionError is better than IndexError for conveying that a severe program bug has occurred. Unless you're running python with the -O flag. So, instead of the unpythonic... i = p.index(current_player) opponents = p[:i] + p[i+1:] ...we now have... if current_player not in p: raise ValueError, current_player opponents = tuple(x for x in p if x is not current_player) Sure, p would probably be a list for a lot of games, and as I've noted previously, since you have to specify all of the elements at once to initialise the tuple, you should know where the player is. But this only applies to situations where you have control over the code needing to know the index *and* the code making the tuple in the first place. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Queue get timeout parameter question
Godzilla Ok... But I'm afraid no syncing is not an option for the Godzilla device... Then you'll either need to use something like ntp or sync much more frequently so you don't yank the time by so much. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Check for keypress on Linux xterm ?
On 2007-04-10, hlubenow [EMAIL PROTECTED] wrote: My problem is, I don't want my program to wait for the keypress. I just want to check, if a key is currently pressed and if not, I'd like to continue with my program (like INKEY$ in some BASIC-dialects). The answer to this frequently asked question is actually in the FAQ: http://www.python.org/doc/faq/library.html#how-do-i-get-a-single-keypress-at-a-time You're answer is only less than half correct: Most of the given examples use something like c = sys.stdin.read(1) like my example does. This blocks input. read() will not block if the file has been set to non-blocking mode. That's what these two lines in the FAQ answer do: oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) I do make mistakes, but before telling somebody he's wrong, it might be a good idea to actually try what he's suggested. ;) -- Grant Edwards grante Yow! Edwin Meese made me at wear CORDOVANS!! visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 2007-04-10, Carsten Haese [EMAIL PROTECTED] wrote: On Tue, 2007-04-10 at 13:21 +, Antoon Pardon wrote: But if you are so eager to rewrite, how about the following: I am using the struct module to get binary data from a file. Sometimes I want to skip until I find a particular binary number. Somewhat simplified it looks like this: class Itemfile: def __init__(self, fn): self.fl = open(fn) self.ix = 80 def nextitem(self): if self.ix == 80: self.buf = struct.unpack(80i, self.fl.read(320)) self.ix = 0 result = self.buf[self.ix] self.ix += 1 return result def skipuntil(self, val): done = False while not done: try: self.ix = self.buf.index(val, self.ix) done = True except ValueError: self.ix = 0 self.buf = struct.unpack(80i, self.fl.read(320)) Now I'm sure you can rewrite this without the need of tuple.index. It just seems odd that I have to go through extra hoops here to get the effect of tuple.index because struct.unpack returns its result in a tuple and a tuple doesn't provide index. Your data is an array. Choosing a data structure that doesn't fit your data is always going to cause pain. Instead of using struct.unpack, you should use array.array, and voila!, you get an index method. No it is not. This is exactly what I thought was going to happen. One simplifies a problem so that the code is not too big to discuss here and people will use characteristics of the simplified code to suggest how one should have solved the problem differently. I'm not interrested in going through such a merry around again. As I said, writing an index function that works with any kind of sequence is easy enough and once written can be used as often as one whishes. So although I prefer more consistency from a language that python currently provides the language has enough going for it to stick with it dispite these kind of warts. So having that function is a practical enough solution for me. And curiously, having that function makes using tuples no longer painfull in situations where other would argue that tuples don't fit my data. If tuples don't fit my data, I sure find it strange that one little function causes you to no longer experience it as such. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Check for keypress on Linux xterm ?
Grant Edwards wrote: I do make mistakes, but before telling somebody he's wrong, it might be a good idea to actually try what he's suggested. ;) I completely agree. The script waited at first for key-input, so I thought, I was right. But I was not. I apologize ! H. -- http://mail.python.org/mailman/listinfo/python-list
Re: NLTK, Random Sentence Generators?
On Apr 10, 1:36 am, Passer By [EMAIL PROTECTED] wrote: Has any created or not of examples of random sentence generators using n-gram models (or other models might be interesting). I know of one example from a course at MIT, but besides that nothing. Any help would be great. Markov chains e.g. http://rubyquiz.com/quiz74.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is __getslice__ still implemented?
Hallöchen! Steven Bethard writes: Torsten Bronger wrote: [...] [...] It forces people to implement a deprecated function after all. I think the docs should say that you still have to override __getslice__ when subclassing from a built-in type, unless I really don't understand the issue correctly. [...] If you have a specific suggestion for what doc should be updated and how, that would be helpful. Please post it to: http://sourceforge.net/tracker/?group_id=5470atid=105470 Done. Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: [EMAIL PROTECTED] (See http://ime.webhop.org for ICQ, MSN, etc.) -- http://mail.python.org/mailman/listinfo/python-list
grabbing Pictures from the web
I am new to python (2 weeks old) and I would like to write a script that grabs pictures from the web (specifically flickr) and put them on a Tk Canvas for a slide show/editing program. my 2 questions are 1) How do I grab a picture from the web 2) is the use of the Tk canvas for working with the picture the best approach? Any help or references to resources that point me in the right direction would be greatly appreciated. Thanks in Advance. -Juan -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
BJörn Lindqvist: One might perversely allow extension to lists and tuples to allow [3, 4] in [1, 2, 3, 4, 5, 6] to succeed, but that's forcing the use case beyond normal limits. The point I am trying to make is that circumstances alter cases, and that we can't always rely on our intuition to determine how specific methods work, let alone whether they are available. I'd love to have that! There are at least one million use cases for finding a sequence in a sequence and implementing it yourself is non-trivial. Plus then both list and tuple's index methods would work *exactly* like string's. It would be easier to document and more useful. A big win. Sublist search (and generally adding a bit of pattern matching features to Python) looks far from being perverse, it may even become pythonic ;-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On 4/10/07, Carsten Haese [EMAIL PROTECTED] wrote: opponents = tuple(x for x in p if x is not current_player) Your alternative is wrong because it wont raise ValueError if current_player is not present in the tuple. Please revise your solution. You have a point. Here is my revised solution: assert current_player in p opponents = tuple(x for x in p if x is not current_player) The added advantage is that AssertionError is better than IndexError for conveying that a severe program bug has occurred. Assertions are not checked when you run scripts with -O. Furthermore, changing the exception type and the message it produces, is quite a big deviation from list.index. -- mvh Björn -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is __getslice__ still implemented?
Torsten Bronger wrote: Hallöchen! Steven Bethard writes: Torsten Bronger wrote: [...] [...] It forces people to implement a deprecated function after all. I think the docs should say that you still have to override __getslice__ when subclassing from a built-in type, unless I really don't understand the issue correctly. [...] If you have a specific suggestion for what doc should be updated and how, that would be helpful. Please post it to: http://sourceforge.net/tracker/?group_id=5470atid=105470 Done. Thanks! STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Database in memory
On Apr 10, 1:10 pm, Nicko [EMAIL PROTECTED] wrote: If you expect to do exact-match look-up where the keys are not unique then build a dictionary containing 'set' objects which are the sets of records which have the given key. This lets you neatly find the intersection of selections on multiple criteria (e.g. matches = zipcode_index[94101] hometype_index[condo] ). Just FYI, if you're going to go this route then the items that you are indexing have to be hashable, which the built in 'list' type is not. Tuples are, or you can make some custom class (or your own subtype of list) which implements the __hash__ method based on some 'primary key' value from your data. Or you could just go for SQLite... -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On Tue, 2007-04-10 at 19:21 +0200, BJörn Lindqvist wrote: On 4/10/07, Carsten Haese [EMAIL PROTECTED] wrote: opponents = tuple(x for x in p if x is not current_player) Your alternative is wrong because it wont raise ValueError if current_player is not present in the tuple. Please revise your solution. You have a point. Here is my revised solution: assert current_player in p opponents = tuple(x for x in p if x is not current_player) The added advantage is that AssertionError is better than IndexError for conveying that a severe program bug has occurred. Assertions are not checked when you run scripts with -O. Right. Which is why you use assert to guard against situations that should never happen, and you determine in unit tests that they, in fact, don't happen. Realistically, in a game loop such as while not game_has_ended: for current_player in p: player_does_something(current_player) it's obvious that the assertion current_player in p will never fail. Furthermore, changing the exception type and the message it produces, is quite a big deviation from list.index. What's your point? I wasn't talking about coding a drop-in replacement for list.index. I was suggesting one possible solution to a problem that may or may not be solved by using tuple.index. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
ANN: pywinauto 0.3.7 now released
Hi, 0.3.7 release of pywinauto is now available. pywinauto is an open-source (LGPL) package for using Python as a GUI automation 'driver' for Windows NT based Operating Systems (NT/W2K/XP/Vista?). SourceForge project page: http://sourceforge.net/projects/pywinauto Download from SourceForge http://sourceforge.net/project/showfiles.php?group_id=157379 Here is the list of changes from the previous release (0.3.6): 0.3.7 Merge of Wait changes and various bug fixes/improvements -- 10-April-2007 * Added Timings.WaitUntil() and Timings.WaitUntilPasses() which handle the various wait until something in the code. Also refactored existing waits to use these two methods. * Fixed a major Handle leak in RemoteMemorBlock class (which is used extensively for 'Common' controls. I was using OpenHandle to open the process handle, but was not calling CloseHandle() for each corresponding OpenHandle(). * Added an active_() method to Application class to return the active window of the application. * Added an 'active' option to WindowSpecification.Wait() and WaitNot(). * Some cleanup of the clipboard module. GetFormatName() was improved and GetData() made a little more robust. * Added an option to findwindows.find_windows() to find only active windows (e.g. active_only = True). Default is False. * Fixed a bug in the timings.Timings class - timing values are Now accessed through the class (Timings) and not through the intance (self). * Updated ElementTree import in XMLHelpers so that it would work on Python 2.5 (where elementtree is a standard module) as well as other versions where ElementTree is a separate module. * Enhanced Item selection for ListViews, TreeViews - it is now possible to pass strings and they will be searched for. More documentation is required though. * Greatly enhanced Toolbar button clicking, selection, etc. Though more documentation is required. * Added option to ClickInput() to allow mouse wheel movements to be made. * menuwrapper.Menu.GetProperties() now returns a dict like all other GetProperties() methods. This dict for now only has one key 'MenuItems' which contains the list of menuitems (which had been the previous return value). Thanks Mark Mark Mc Mahon Manchester, NH 03110, USA PA HREF=http://sourceforge.net/projects/pywinauto;pywinauto 0.3.7/A Simple Windows GUI automation with Python. (10-Apr-07) -- http://mail.python.org/mailman/listinfo/python-list
Re: Having trouble with relative imports
On 4/9/07, Echo [EMAIL PROTECTED] wrote: Here is my setup: rpg -objects --__init__.py --gameobject.py --material.py -__init__.py -run_tests.py -stats.py the contents of run_test.py is: import objects as o the contents of objects/__init__.py is: from material import * in objects/material.py I have: from .gameobject import GameObject from ..stats import stats When I try to run run_tests.py, I get this traceback: (1:30:59 PM) OshEcho: [EMAIL PROTECTED] ~/projects/rpg $ python run_tests.py Traceback (most recent call last): File run_tests.py, line 4, in module import objects as o File /home/echo/projects/rpg/objects/__init__.py, line 3, in module from material import * File /home/echo/projects/rpg/objects/material.py, line 4, in module from ..stats import stats ValueError: Attempted relative import beyond toplevel package Could someone point out to me what I am doing wrong? I'm running Python 2.5 on Gentoo -- -Echo Well, since I've gotten no answer and since that Python 2.5 doesn't play well with some programs on Gentoo, I will be switch back to 2.4 for now. -- -Echo -- http://mail.python.org/mailman/listinfo/python-list
writing my own extension
hi, i use a lot the enumerate in my scripts and got really interested in possibly writing my own enumerate as an extension, for which i would want to extend it to be able to pass a start and step attribute. can anyone point me on my way with good examples for that and how to write extensions ? thank you in advance -- http://mail.python.org/mailman/listinfo/python-list
Universal Feed Parser issue
I have a sample Atom feed like this: ?xml version='1.0' encoding='utf-8'? feed xmlns='http://www.w3.org/2005/Atom' xmlns:foo='http:// app.example.com/app/2007' idhttp://app.example.com/fjie4id939xdl3io23/id title type='text'foo/title author namebar/name email[EMAIL PROTECTED]/email /author updated2007-04-09T22:14:15.000Z/updated link rel='http://app.example.com/#event' type='application/atom +xml' href='http://www.foo.com/app/feeds/#app1'/link foo:timezone value='America/Mountain'/foo:timezone foo:status value='confirmed'/foo:status /feed After parsed by feedparser, the timezone element does not get the attribute America/Mountain. Same thing on status element. This does not sound an expected result. I am wondering if it should be considered a bug... -- http://mail.python.org/mailman/listinfo/python-list