Re: name capitalization of built-in types, True, and False
En Fri, 11 May 2007 17:37:48 -0300, [EMAIL PROTECTED] escribió: I see that naming conventions are such that classes usually get named CamelCase. So why are the built-in types named all lowercase (like list, dict, set, bool, etc.)? Because most of them originally were types and factory functions, not classes - and a naming convention is not a strong reason to make backwards incompatible changes. A different example: the new builtin type `set` is based on (altough not exactly equal to) the Set class from the sets module -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: matplotlib: howto set title of whole window?
No, it's just another one title it produces a figure with name Figure 1 but I should somehow replace the string. It is possible in MATLAB via set(figureHandler, 'Name', 'my_string_here') D. On May 12, 2:52 am, [EMAIL PROTECTED] wrote: On May 11, 3:44 pm, dmitrey [EMAIL PROTECTED] wrote: hi all, does anyone know howto set title of whole window? (I mean not just area above plot but string in the same line where buttons 'close', 'iconify', 'fullscreen' are situated) Use coordinates to set a title for the current figure. E.g., from pylab import * from matplotlib.font_manager import FontProperties figtitle = 'This is my title above all subplots' t = gcf().text(0.5, 0.95, figtitle, horizontalalignment='center', fontproperties=FontProperties(size=16)) subplot(121) subplot(122) show() -- Hope this helps, Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: logging module and threading
On May 12, 1:53 am, Ross Boylan [EMAIL PROTECTED] wrote: I'm also puzzled by how the logger hierarchy works. The docs say that everything that is logged by the kids is also logged by the parent. That would seem to defeat what I'm trying to do above, since the parent would get each logged event right away. However,logging.getLogger(a).error(test) produces only a single log message indicating an associated object of a. The docs lead me to expect that I'd see one message from a and another from root. When I add handlers (e.g., FileHandlers) I do get the message recorded by each. Can anyone explain what's going on? The Logger hierarchy works, in a nutshell, as follows: events passed to a logger propagate up the hierarchy until either the root, or a logger whose propagate attribute is set to a false value, is reached. At each step (i.e. logger) in the propagation, any handlers attached to that logger are offered the chance to handle the message - which means different things depending on the handler. If you add e.g. a FileHandler to the root logger and another to a logger named a.b.c and then log something to a.b.c, then two handlers will each handle the message, leading to multiple output of the same event. You also don't need to buffer up messages in different threads - if your messages contain both the log event time and the thread id (which can be achieved by having %(asctime)s or %(relativeCreated)d and % (thread)d or %(threadName)s in your format string), then you can simply sort the output to group your messages together. (And since threads sometimes interact, it's often useful to see the raw output in time order.) If you do want to buffer events, MemoryHandler will do the trick. And it takes a target handler rather than logger, because it's acting as a buffer for another handler, for events which have already been entered into the system. If you're new to logging, you need to separate the ideas behind loggers and handlers in the scheme of things. Loggers are things which application developers use to register events of interest in their application, with an indication of importance (level) and an ability to filter on that. Handlers are things used by developers or admins to send information about the events to different audiences - e.g. critical errors might be emailed to someone while less critical errors are sent to console or log files. Best regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Binding
You are completely right wihtin this. It's some time i didn't reply, but i've taken a look on pyrex and swig now which did cost me some time, and they really make it easier. SWIG provides more possibilities and bindings for other languages too, though - i must say i've been faster with pyrex, for some reason it fits me better. I'd like to use swig, but for some reason i've troubles defining a completely new type, so a type which is not a wrapper type, but a type provided to python. Kind regards, Georg Stefan Behnel wrote: STiAT wrote: Why do you all suggest other things than the way suggested by python? Because going to Paris is not the only way to get french bread? Why would you want to write all that ugly glue code by hand that Pyrex generates for free? Module descriptors? Class descriptors? Method descriptors? Reference counting? That's what Pyrex saves you from. Honestly. From what I read in your mail, that's exactly the kind of thing you're having trouble with. Wouldn't you prefer concentrating on your real code instead? I havn't got a real problem writing the code in C, actually, it looked as if it would give me several possibilities i wouldn't have with pyrex (like binding more library functions to one provided python function and so on). No idea what you mean in your parentheses, but I don't think there are many possibilities you wouldn't have with Pyrex. We used Pyrex to write lxml, a wrapper around the huge API of libxml2 and libxslt. It's some 11000 lines of Pyrex code by now, but the generated C code is some 67000 lines in total. Even if it's somewhat verbose and generic in places, I wouldn't have wanted to write that by hand. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread-safe dictionary
- in __getitem__, does it release the lock after returning the item? Yes, it does. - wouldn't it be better to use threading.RLock, mutex, ... instead? Better in what sense? Performance-wise? Semantically? Performance-wise, the best thing would be to do safe_dict = dict because the builtin dict is already thread-safe unless user-defined __hash__ or __eq__ methods get invoked (in which case the dictionary still works correctly - it's only that it may get modified while __hash__ or __eq__ is running). Semantically, it would be better to use a threading.RLock, if you expect that __hash__ or __eq__ may access the dictionary recursively. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: stealth screen scraping with python?
[EMAIL PROTECTED] schrieb: I am screen scraping a large volume of data from Yahoo Finance each evening, and parsing with Beautiful Soup. I was wondering if anyone could give me some pointers on how to make it less obvious to Yahoo that this is what I am doing, as I fear that they probably monitor for this type of activity, and will soon ban my IP. Use anonymizing proxies: http://www.google.com/search?q=proxies+OR+proxy+anonymous+OR+anonymizing -- Thomas Wittek http://gedankenkonstrukt.de/ Jabber: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Popen and wget, problems
Hi all, I have a problem using wget and Popen. I hope someone can help. -- Problem -- I want to use the command: wget -nv -O dir/cpan.txt http://search.cpan.org; and capture all it's stdout+stderr. (Note that option -O requires 'dir' to be existing before wget is executed) Popen doesn't work, while os.system and shell do. Popen will give the error: dir/cpan.txt: No such file or directory While os.system and shell will give the correct result: 06:52:40 URL:http://search.cpan.org/ [3657/3657] - dir1/cpan.txt [1] -- Background info about wget -- -Option -nv: -nv, --no-verbose turn off verboseness, without being quiet. -Option -O: -O, --output-document=FILEwrite documents to FILE. Note that wget requires any directories in the file-path of option -O to be existing before the wget command is executed. -- Python Code using Popen with cmd arg list -- # imports import os from subprocess import Popen, PIPE # vars and create dir cmd_set = ['wget', '-nv', '-O dir/cpan.txt', 'http://search.span.org'] cmd = ' '.join(cmd_set) print cmd: + cmd try: os.makedirs('dir') except: print 'dir already exists' # execute using Popen (does NOT work) proc = Popen(cmd_set, stdout=PIPE, stderr=PIPE) return_code = proc.wait() if return_code == 0: print Success:\n%s % (proc.stdout.read() + proc.stderr.read()) else: print Failure %s:\n%s % (return_code, proc.stderr.read() + proc.stdout.read()) # execute using os.system (does work) os.system(cmd) -- Python code output of Popen -- Failure 1: dir/cpan.txt: No such file or directory -- Question -- Why is Popen unable to correctly execute the wget, while os.system can? -- http://mail.python.org/mailman/listinfo/python-list
Re: Simulating simple electric circuits
On May 11, 10:02 pm, Bjoern Schliessmann usenet- [EMAIL PROTECTED] wrote: [...] P.S.: If anyone happens to be interested in details, just ask, I'll post some code. I'm interested! I was tempted to have a go at it after your initial post, it sounded like a nice little project :) -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Dynamic subclassing ?
I've got an instance of a class, ex : b=gtk.Button() I'd like to add methods and attributes to my instance b. I know it's possible by hacking b with setattr() methods. But i'd like to do it with inheritance, a kind of dynamic subclassing, without subclassing the class, only this instance b ! In fact, i've got my instance b, and another class MoreMethods class MoreMethods: def sayHello(self): print hello How could i write ... b = b + MoreMethods so b will continue to be a gtk.Button, + methods/attributs of MoreMethods (it's what i call dynamic inheritance) ...so, things like this should work : - b.set_label(k) - b.sayHello() I can't find the trick, but i'm pretty sure it's possible in an easy way. Help is welcome thanx -- http://mail.python.org/mailman/listinfo/python-list
Re: find out all threads?
On 11/05/07, Sven Rech [EMAIL PROTECTED] wrote: Hi, I have a written a C program which makes use of python embedding. I want to find out all threads that a loaded module has started. But I can't find anything about this in the docs. Is it possible? Without details of your module, its dificult to say, maybe t_count = threading.activeCount() or t_count = threading.enumerate() will do what you need -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic subclassing ?
manatlan a écrit : I've got an instance of a class, ex : b=gtk.Button() I'd like to add methods and attributes to my instance b. I know it's possible by hacking b with setattr() methods. You don't even need setattr() here, you can set the attributes directly. But i'd like to do it with inheritance, a kind of dynamic subclassing, without subclassing the class, only this instance b ! In fact, i've got my instance b, and another class MoreMethods class MoreMethods: def sayHello(self): print hello How could i write ... b = b + MoreMethods so b will continue to be a gtk.Button, + methods/attributs of MoreMethods (it's what i call dynamic inheritance) ...so, things like this should work : - b.set_label(k) - b.sayHello() I can't find the trick, but i'm pretty sure it's possible in an easy way. You don't necessarily need subclassing here. What you want is a typical use case of the Decorator pattern: class MoreMethods(object): def __init__(self, button): self._button = button def sayHello(self): print hello def __getattr__(self, name): return getattr(self._button, name) def __setattr__(self, name, value): if name in dir(self._button): setattr(self._button, name, value) else: object.__setattr__(self, name, value) b = MoreMethods(gtk.Button()) b.set_label(k) b.say_hello() -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic subclassing ?
On 12 mai, 17:00, Bruno Desthuilliers [EMAIL PROTECTED] wrote: manatlan a écrit : I've got an instance of a class, ex : b=gtk.Button() I'd like to add methods and attributes to my instance b. I know it's possible by hacking b with setattr() methods. You don't even need setattr() here, you can set the attributes directly. But i'd like to do it with inheritance, a kind of dynamic subclassing, without subclassing the class, only this instance b ! In fact, i've got my instance b, and another class MoreMethods class MoreMethods: def sayHello(self): print hello You don't necessarily need subclassing here. What you want is a typical use case of the Decorator pattern: class MoreMethods(object): def __init__(self, button): self._button = button def sayHello(self): print hello def __getattr__(self, name): return getattr(self._button, name) def __setattr__(self, name, value): if name in dir(self._button): setattr(self._button, name, value) else: object.__setattr__(self, name, value) b = MoreMethods(gtk.Button()) b.set_label(k) b.say_hello() except that b is not anymore a gtk.Button, but a MoreMethods instance ... i'd like that b stay a gtk.Button ... -- http://mail.python.org/mailman/listinfo/python-list
Re: path stuff
On May 9, 1:11 pm, fscked [EMAIL PROTECTED] wrote: I am walking some directories looking for a certain filename pattern. This part works fine, but what if I want to exclude results from a certain directory being printed? You might find this thread helpful http://tinyurl.com/2guk3l Note how the backup dirs are excluded. Highly recommend Python Cookbook, too. rd -- http://mail.python.org/mailman/listinfo/python-list
Basic question
I've been studying python for 2 weeks now and got stucked in the following problem: for j in range(10): print j if(True): j=j+2 print 'interno',j What happens is that j=j+2 inside IF does not change the loop counter (j) as it would in C or Java, for example. Am I missing something? []'s Cesar -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic subclassing ?
I've got an instance of a class, ex : b=gtk.Button() I'd like to add methods and attributes to my instance b. I know it's possible by hacking b with setattr() methods. But i'd like to do it with inheritance, a kind of dynamic subclassing, without subclassing the class, only this instance b ! In fact, i've got my instance b, and another class MoreMethods class MoreMethods: def sayHello(self): print hello How could i write ... b = b + MoreMethods so b will continue to be a gtk.Button, + methods/attributs of MoreMethods (it's what i call dynamic inheritance) ...so, things like this should work : - b.set_label(k) - b.sayHello() I can't find the trick, but i'm pretty sure it's possible in an easy way. How about: class MoreMethods: def sayHello(self): print hello class myButton( gtk.Button, MoreMethods ): pass b = myButton( ) isinstance( b, gtk.Button ) # True b.sayHello( ) # hello Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
Cesar G. Miguel wrote: I've been studying python for 2 weeks now and got stucked in the following problem: for j in range(10): print j if(True): j=j+2 print 'interno',j What happens is that j=j+2 inside IF does not change the loop counter (j) as it would in C or Java, for example. Am I missing something? []'s Cesar Nope. The loop counter will be assigned successively through the list of integers produced by range(10). Inside the loop, if you change j, then from that point on for that pass through the body, j will have that value. But such an action will not change the fact that next pass through the loop, j will be assigned the next value in the list. -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
Cesar G. Miguel wrote: for j in range(10): print j if(True): j=j+2 print 'interno',j What happens is that j=j+2 inside IF does not change the loop counter (j) as it would in C or Java, for example. Am I missing something? If you want that kind of behaviour then use a `while` construct: j = 0 while j 5: print j if True: j = j + 3 print '-- ', j If you use a for loop, for each pass through the foor loop Python assigns next item in sequence to the `j` variable. HTH, Karlo. -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
On May 12, 5:18 pm, Cesar G. Miguel [EMAIL PROTECTED] wrote: I've been studying python for 2 weeks now and got stucked in the following problem: for j in range(10): print j if(True): j=j+2 print 'interno',j What happens is that j=j+2 inside IF does not change the loop counter (j) as it would in C or Java, for example. Am I missing something? Yes you are :) for j in range(10):... means: 1. Build a list [0,1,2,3,4,5,6,7,8,9] 2. For element in this list (0, then 1, then 2,...), set j to that value then execute the code inside the loop body To simulate for(initialisation; condition; increment) body you have to use while in Python: initialisation while condition: body increment Of course in most case it would not be the pythonic way of doing it :) -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic subclassing ?
On 12 mai, 18:38, Daniel Nogradi [EMAIL PROTECTED] wrote: I've got an instance of a class, ex : b=gtk.Button() I'd like to add methods and attributes to my instance b. I know it's possible by hacking b with setattr() methods. But i'd like to do it with inheritance, a kind of dynamic subclassing, without subclassing the class, only this instance b ! In fact, i've got my instance b, and another class MoreMethods class MoreMethods: def sayHello(self): print hello How could i write ... b = b + MoreMethods so b will continue to be a gtk.Button, + methods/attributs of MoreMethods (it's what i call dynamic inheritance) ...so, things like this should work : - b.set_label(k) - b.sayHello() I can't find the trick, but i'm pretty sure it's possible in an easy way. How about: class MoreMethods: def sayHello(self): print hello class myButton( gtk.Button, MoreMethods ): pass b = myButton( ) isinstance( b, gtk.Button ) # True b.sayHello( ) # hello yes, but it needs to recreate an instance (of mybutton) ... i can't do that, in my context. The only things i've got is my instance b (which can be whatever object). i'd like to add methods/attributes to this instance, by adding a heritage of another class. Daniel thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: need help with python
I'm not sure how you installed Python, or how you are using it, but I made something last year to help Windows XP users who are brand new to Python and can't get things to run, etc. You might try either jumping into somewhere midway, or if you keep having trouble, uninstall whatever you installed and start over using this: http://www.richarddooling.com/index.php/2006/03/14/python-on-xp-7-minutes-to-hello-world/ If that link breaks, use this: http://tinyurl.com/w7wgp Good luck. rd -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic subclassing ?
manatlan wrote: I can't find the trick, but i'm pretty sure it's possible in an easy way. It's somewhat easy, boot looks ugly to me. Maybe someone has a more elegant solution: In [6]: import new In [13]: class Button: : def buttonFunc(self): : pass In [14]: class ExtensionClass: : def extendedMethod(self): : pass In [15]: hybrid = new.instance(Button, Button.__dict__.update(ExtensionClass.__dict__)) In [17]: dir(hybrid) Out[17]: ['__doc__', '__module__', 'buttonFunc', 'extendedMethod'] Seems to do what you want it to do. HTH, Karlo. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic subclassing ?
I've got an instance of a class, ex : b=gtk.Button() I'd like to add methods and attributes to my instance b. I know it's possible by hacking b with setattr() methods. But i'd like to do it with inheritance, a kind of dynamic subclassing, without subclassing the class, only this instance b ! In fact, i've got my instance b, and another class MoreMethods class MoreMethods: def sayHello(self): print hello How could i write ... b = b + MoreMethods so b will continue to be a gtk.Button, + methods/attributs of MoreMethods (it's what i call dynamic inheritance) ...so, things like this should work : - b.set_label(k) - b.sayHello() I can't find the trick, but i'm pretty sure it's possible in an easy way. How about: class MoreMethods: def sayHello(self): print hello class myButton( gtk.Button, MoreMethods ): pass b = myButton( ) isinstance( b, gtk.Button ) # True b.sayHello( ) # hello yes, but it needs to recreate an instance (of mybutton) ... i can't do that, in my context. The only things i've got is my instance b (which can be whatever object). i'd like to add methods/attributes to this instance, by adding a heritage of another class. I think that is not possible, at least in a simple way (there might be a complicated way of messing with the MRO). Please anyone correct me if I was wrong. Daniel -- http://mail.python.org/mailman/listinfo/python-list
Finally started on python..
Hi, Having known about python since around the turn of the century , I finally found a (actually two) reason to learn it. Python seems to have moved on a little since the 1.5.2 release covered in the reference book (Essential Python) I bought way back when so I could learn it when the time came but it seems to be mainly backward compatible - is there anything that likely to catch me out - I use linux, so heavy use of an upto date pydoc has filled the gaps so far. I do however have a couple of questions:- 1) A nice simple language query : I found myself using this sort of code a bit in one of my recent scripts class Something: def Entries(self): sort=self._data.keys() sort.sort() for i in sort: yield i IS this preferable to just returning the sort array from the function or not? Which is more runtime efficent. Does it change if the last line was yield self._data[i] instead as that would require a map() in the function ? 2) I've ended up coding a new wrapper for reading in data structures from XML files (it wraps xml.sax) so that ctor are call on each end tag with the XML Objects contents. Does the python communitity have something like Perl's CPAN and is there already something there taht does this or would it be something that I could give back? Is there a naming convention for such modules in python - I couldn't easly detect one looking at the library which whip with python in Debian. Sorry, for asking so much in a first post but I thought both queries were link with by relative newby status. TTFN -- Roger. Home| http://www.sandman.uklinux.net/ Master of Peng Shui. (Ancient oriental art of Penguin Arranging) Work|Independent Sys Consultant | http://www.computer-surgery.co.uk/ So what are the eigenvalues and eigenvectors of 'The Matrix'? --anon -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
j=j+2 inside IF does not change the loop counter (j) You might be not truly catching the idea of Python `for` statements sequence nature. It seems that http://docs.python.org/ref/for.html will make things quite clear. The suite may assign to the variable(s) in the target list; this does not affect the next item assigned to it. In C you do not specify all the values the looping variable will be assigned to, unlike (in the simplest case) you do in Python. -- Happy Hacking. Dmitry Sphinx Dzhus http://sphinx.net.ru -- http://mail.python.org/mailman/listinfo/python-list
Drawing Text on a Path
Hi everyone, I need to draw some curved text on an image. I've digged both PIL and aggdraw documentation for this kind of feature, but found nothing. However, AGG itself does support rendering text along a path, but I can't seem to figure out how to deal with the API/Wrapper differences... Could someone give me an hand here? Thanks in advance! Hugo Ferreira -- http://mail.python.org/mailman/listinfo/python-list
Re: Finally started on python..
In [EMAIL PROTECTED], Roger Gammans wrote: I found myself using this sort of code a bit in one of my recent scripts class Something: def Entries(self): sort=self._data.keys() sort.sort() for i in sort: yield i IS this preferable to just returning the sort array from the function or not? Which is more runtime efficent. I see no benefit for a generator here as the whole list mus be build for sorting anyway. If you still want return an iterable here it could be written this way: class Something(object): def iter_entries(self): return iter(sorted(self._data.keys())) Just leave out the `iter()` call to return a sorted list. If you want to make `Something` objects iterable over the sorted keys, change the method name to `__iter__()`. Then you can use `Something` objects like this: something = Something() # Puts some entries into `something`. for entry in something: print entry Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
On May 12, 12:18 pm, Cesar G. Miguel [EMAIL PROTECTED] wrote: I've been studying python for 2 weeks now and got stucked in the following problem: for j in range(10): print j if(True): j=j+2 print 'interno',j What happens is that j=j+2 inside IF does not change the loop counter (j) as it would in C or Java, for example. Am I missing something? []'s Cesar What is your real intent here? This is how I understand it after reading your post: you want to create a loop that steps by an increment of 2. If that's the case, then: for j in range(0,10,2): ... print j ... 0 2 4 6 8 would be a simple result. Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems with grid() layout under tkinter
I found the error - some of the widgets belonged to master and some to frame. So glad I found that Error - that took forever! :D Kind regards Thomas Jansson On 11 Maj, 23:06, Thomas Jansson [EMAIL PROTECTED] wrote: Dear all I am trying to make a small wrapper program for textbased program and it is going well but I have one problem. Namely that I simply do not understand how this grid thing work. I have assigned every widget a specific placement in a grid but when I am running the program it looks very strange. I hope you can help me. A example of the programhttp://tjansson.dyndns.dk/apache2-default/strange-grid.jpg and the codehttp://tjansson.dyndns.dk/tjansson/gui.py Kind regards Thomas Jansson -- http://mail.python.org/mailman/listinfo/python-list
Re: Interesting list Validity (True/False)
On Fri, 2007-05-11 at 14:26 -0700, [EMAIL PROTECTED] wrote: if arg==True: tests the type property (whether a list is a boolean). That sounds nonsensical and incorrect. Please explain what you mean. if arg==True tests whether the object known as arg is equal to the object known as True. Regards, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: searching algorithm
On May 10, 1:26 pm, Gigs_ [EMAIL PROTECTED] wrote: Hi all! I have text file (english-croatian dictionary) with words in it in alphabetical order. This file contains 17 words in this format: english word: croatian word Let's assume it's okay to have all the data in memory. In my experience the very fastest way to do what you want is to store the strings in a sorted list and use the binary search library module bisect. I once compared this with doing something similar with tries and it was much faster. It's also the most simple way to do it, which is nice too :). -- Aaron Watters === never eat anything bigger than your head -- kliban -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
On May 12, 2:45 pm, Basilisk96 [EMAIL PROTECTED] wrote: On May 12, 12:18 pm, Cesar G. Miguel [EMAIL PROTECTED] wrote: I've been studying python for 2 weeks now and got stucked in the following problem: for j in range(10): print j if(True): j=j+2 print 'interno',j What happens is that j=j+2 inside IF does not change the loop counter (j) as it would in C or Java, for example. Am I missing something? []'s Cesar What is your real intent here? This is how I understand it after reading your post: you want to create a loop that steps by an increment of 2. If that's the case, then: for j in range(0,10,2): ... print j ... 0 2 4 6 8 would be a simple result. Cheers, -Basilisk96 Actually I'm trying to convert a string to a list of float numbers: str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0] As some of you suggested, using while it works: - L = [] file = ['5,1378,1,9', '2,1,4,5'] str='' for item in file: j=0 while(jlen(item)): while(item[j] != ','): str+=item[j] j=j+1 if(j= len(item)): break if(str != ''): L.append(float(str)) str = '' j=j+1 print L - But I'm not sure this is an elegant pythonic way of coding :-) Thanks for all suggestions! -- http://mail.python.org/mailman/listinfo/python-list
[Newbie] design question
Hi all Suppose I have class ShoppingCart which has one method called buy(), and class Buyer who has one reference to ShoppingCart... Can I also have method buy() in class Buyer, which will then called ShoppingCard.buy(), and also do some other stuff? Is this legal design pattern, have methods with same name? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Creating a function to make checkbutton with information from a list?
Dear all I am writing a program with tkinter where I have to create a lot of checkbuttons. They should have the same format but should have different names. My intention is to run the functions and the create all the buttons with the names from the list. I now the lines below doesn't work, but this is what I have so far. I don't really know how call the element in the dict use in the for loop. I tried to call +'item'+ but this doesn't work. def create_checkbox(self): self.checkbutton = [LNCOL, LFORM, LPOT, LGRID, LERR, LCOMP] for item in self.checkbutton: self.+'item'+Checkbutton = Chekcbutton(frame, onvalue='t', offvalue='f', variable=self.+'item'+) self.+'item'+Checkbutton.grid() How should I do this? Kind regards Thomas Jansson -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
Cesar G. Miguel wrote: - L = [] file = ['5,1378,1,9', '2,1,4,5'] str='' for item in file: j=0 while(jlen(item)): while(item[j] != ','): str+=item[j] j=j+1 if(j= len(item)): break if(str != ''): L.append(float(str)) str = '' j=j+1 print L But I'm not sure this is an elegant pythonic way of coding :-) Example: In [21]: '5,1378,1,9'.split(',') Out[21]: ['5', '1378', '1', '9'] So, instead of doing that while-based traversal and parsing of `item`, just split it like above, and use a for loop on it. It's much more elegant and pythonic. HTH, Karlo. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Newbie] design question
Suppose I have class ShoppingCart which has one method called buy(), and class Buyer who has one reference to ShoppingCart... Can I also have method buy() in class Buyer, which will then called ShoppingCard.buy(), and also do some other stuff? Is this legal design pattern, have methods with same name? Yes, something like this is perfectly fine. class ShoppingCart( object ): def buy( self ): print 'buy in shoppingcart' class Buyer( object ): def __init__( self, cart ): self.cart = cart def buy( self ): print 'buy in buyer' self.cart.buy( ) print 'some extra stuff' acart = ShoppingCart( ) abuyer = Buyer( cart=acart ) abuyer.buy( ) HTH, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: preferred windows text editor?
T. Crane wrote: Right now I'm using Notepad++. What are other people using? If you are looking for editors written in Python (that are generally multiplatform using wxPython), there are a few listed: http://wiki.wxpython.org/wxPythonPit_Apps . If you are looking for editors with Python support, there is a listing on the Python wiki: http://wiki.python.org/moin/PythonEditors I use PyPE (http://pype.sf.net) for most of my editing needs. - Josiah -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
On May 12, 3:09 pm, Karlo Lozovina [EMAIL PROTECTED] wrote: Cesar G. Miguel wrote: - L = [] file = ['5,1378,1,9', '2,1,4,5'] str='' for item in file: j=0 while(jlen(item)): while(item[j] != ','): str+=item[j] j=j+1 if(j= len(item)): break if(str != ''): L.append(float(str)) str = '' j=j+1 print L But I'm not sure this is an elegant pythonic way of coding :-) Example: In [21]: '5,1378,1,9'.split(',') Out[21]: ['5', '1378', '1', '9'] So, instead of doing that while-based traversal and parsing of `item`, just split it like above, and use a for loop on it. It's much more elegant and pythonic. HTH, Karlo. Great! Now it looks better :-) -- http://mail.python.org/mailman/listinfo/python-list
Read from Windows Address Book (.wab file format) ?
Hi all! I wonder if there's any Python module that could read from .wab file. I googled but found nothing useful. Any idea? Thanks :) Rio -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
Actually I'm trying to convert a string to a list of float numbers: str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0] str=53,20,4,2 map(lambda s: float(s), str.split(',')) Last expression returns: [53.0, 20.0, 4.0, 2.0] -- Happy Hacking. Dmitry Sphinx Dzhus http://sphinx.net.ru -- http://mail.python.org/mailman/listinfo/python-list
package rating system for the Cheese Shop
Is there a package rating system for the Cheese Shop, like how Perl has cpanratings (http://cpanratings.perl.org/)? Do you think it would be useful? I see that we already have Cheesecake (http://pycheesecake.org/) for rating a package's kwalitee (like Perl's CPANTS). But browsing the Cheese Shop, I don't see a way to view or sort by Cheesecake rating... How can I see the kwalitee ratings of the packages at the Cheese Shop? -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
On 2007-05-12, Cesar G. Miguel [EMAIL PROTECTED] wrote: Actually I'm trying to convert a string to a list of float numbers: str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0] str = '53,20,4,2' [float(w) for w in str.split(',')] [53.0, 20.0, 4.0, 2.0] map(float,str.split(',')) [53.0, 20.0, 4.0, 2.0] -- Grant Edwards grante Yow! I want you to at MEMORIZE the collected visi.compoems of EDNA ST VINCENT MILLAY... BACKWARDS!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
On 2007-05-12, Dmitry Dzhus [EMAIL PROTECTED] wrote: str=53,20,4,2 map(lambda s: float(s), str.split(',')) There's no need for the lambda. map(float,str.split(',')) Does exactly the same thing. -- Grant Edwards grante Yow! I feel like I am at sharing a CORN-DOG with visi.comNIKITA KHRUSCHEV... -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic subclassing ?
manatlan wrote: I've got an instance of a class, ex : b=gtk.Button() I'd like to add methods and attributes to my instance b. I know it's possible by hacking b with setattr() methods. But i'd like to do it with inheritance, a kind of dynamic subclassing, without subclassing the class, only this instance b ! In fact, i've got my instance b, and another class MoreMethods class MoreMethods: def sayHello(self): print hello How could i write ... b = b + MoreMethods You can simply bind the methods you want to add to the Button instance. That means doing the equivalent of ``b.sayHello = sayHello.__get__(b)``. For example:: class Button(object): ... def set_label(self, label): ... print 'setting label:', label ... def add_methods(obj, cls): ... for name, value in cls.__dict__.items(): ... if callable(value) and hasattr(value, '__get__'): ... setattr(obj, name, value.__get__(obj, type(obj))) ... b = Button() b.set_label('k') setting label: k b.say_hello() Traceback (most recent call last): File interactive input, line 1, in module AttributeError: 'Button' object has no attribute 'say_hello' class MoreMethods(object): ... def say_hello(self): ... print 'hello' ... add_methods(b, MoreMethods) b.set_label('m') setting label: m b.say_hello() hello HTH, STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
On May 12, 3:40 pm, Dmitry Dzhus [EMAIL PROTECTED] wrote: Actually I'm trying to convert a string to a list of float numbers: str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0] str=53,20,4,2 map(lambda s: float(s), str.split(',')) Last expression returns: [53.0, 20.0, 4.0, 2.0] -- Happy Hacking. Dmitry Sphinx Dzhushttp://sphinx.net.ru Nice! The following also works using split and list comprehension (as suggested in a brazilian python forum): --- L = [] file = ['5,1378,1,9', '2,1,4,5'] str='' for item in file: L.append([float(n) for n in item.split(',')]) --- Thank you for all suggestions! -- http://mail.python.org/mailman/listinfo/python-list
Re: package rating system for the Cheese Shop
[EMAIL PROTECTED] wrote: Is there a package rating system for the Cheese Shop, like how Perl has cpanratings (http://cpanratings.perl.org/)? I don't know CPAN, but maybe this is what you're looking for: http://www.cheeserater.com/ ? STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: [Newbie] design question
[EMAIL PROTECTED] wrote: Suppose I have class ShoppingCart which has one method called buy(), and class Buyer who has one reference to ShoppingCart... Can I also have method buy() in class Buyer, which will then called ShoppingCard.buy(), and also do some other stuff? Is this legal design pattern, have methods with same name? In principle, this is legal. But OTOH, how could a ShoppingCart buy something? In my world, Buyers buy when using ShoppingCarts. Regards, Björn -- BOFH excuse #445: Browser's cookie is corrupted -- someone's been nibbling on it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a function to make checkbutton with information from a list?
On May 12, 11:04 am, Thomas Jansson [EMAIL PROTECTED] wrote: Dear all I am writing a program with tkinter where I have to create a lot of checkbuttons. They should have the same format but should have different names. My intention is to run the functions and the create all the buttons with the names from the list. I now the lines below doesn't work, but this is what I have so far. I don't really know how call the element in the dict use in the for loop. I tried to call +'item'+ but this doesn't work. def create_checkbox(self): self.checkbutton = [LNCOL, LFORM, LPOT, LGRID, LERR, LCOMP] for item in self.checkbutton: self.+'item'+Checkbutton = Chekcbutton(frame, onvalue='t', offvalue='f', variable=self.+'item'+) self.+'item'+Checkbutton.grid() How should I do this? Kind regards Thomas Jansson You can use exec(self. + name + = + value) to do what you want, but then you need to exec() each time you want to access the variable. I think it is much better to create a class. Here's what I came up with: from Tkinter import * class Window(Frame): def __init__(self, parent=None): Frame.__init__(self,parent=None) self.names = [LNCOL, LFORM, LPOT, LGRID, LERR, LCOMP, Sean] self.checkbuttons = [] self.f = Frame(root) for name in self.names: self.checkbuttons.append(CButton(parent=self.f, name=name, default=f)) self.f.pack(side=top,padx=5, pady=5) class CButton(object): def __init__(self, parent=None, name=None, default=None): self.name = name self.parent = parent self.variable = StringVar() self.variable.set(default) self.checkbutton = None self.create_checkbox(name) def create_checkbox(self,name): f = Frame(self.parent) Label(f, text=name).pack(side=left) self.checkbutton = Checkbutton(f, onvalue='t', offvalue='f', variable=self.variable) self.checkbutton.bind(Button-1, self.state_changed) self.pack() f.pack() def pack(self): self.checkbutton.pack() def state_changed(self, event=None): print %s: %s % (self.name, self.variable.get()) if __name__ == '__main__': root = Tk() Window().mainloop() ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: Read from Windows Address Book (.wab file format) ?
On May 12, 11:30 am, 詹光耀 [EMAIL PROTECTED] wrote: Hi all! I wonder if there's any Python module that could read from .wab file. I googled but found nothing useful. Any idea? Thanks :) Rio Hi Rio, Don't know if there's a python module for this, but this link, http://msdn2.microsoft.com/en-us/library/ms629361.aspx defines the MS API for the address book, so you could roll your own. If all you need is to read the data though, you could export the address data into a CSV file (Python DOES have a module for this) or VCard format. IIRC, someone on this newsgroup was talking about VCard just the other day. HTH rynt -- http://mail.python.org/mailman/listinfo/python-list
Re: package rating system for the Cheese Shop
On May 12, 2:49 pm, Steven Bethard [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: Is there a package rating system for the Cheese Shop, like how Perl has cpanratings (http://cpanratings.perl.org/)? I don't know CPAN, but maybe this is what you're looking for: http://www.cheeserater.com/ ? STeVe Thanks for the link STeVe. Yes, this is the sort of thing I was looking for. Looks like there's no way to actually leave comments on a package though; just a (+) or (-) rating. No way to say something like, I like x, y, and z about this package, but n, m, and especially o need to get fixed though. One strength of cpanratings is you can leave those comments. A well- written review comment, like I used this package, and here's how it worked out ... If you need certain feature x, you might try package y instead of this one. is much more valuable than a thumbs-up or thumbs-down. -- http://mail.python.org/mailman/listinfo/python-list
Re: design question
On May 12, 9:34 pm, Bjoern Schliessmann usenet- [EMAIL PROTECTED] wrote: In principle, this is legal. But OTOH, how could a ShoppingCart buy something? In my world, Buyers buy when using ShoppingCarts. Yes, I don't know either. I got this assignment for my homework, and in UML diagram class ShoppingCart has method buy(), and the class Buyer doesn't have any methods, only attribute ShoppingCart, and I must simulate/implement online shopping. In my world buyers buy too, just wanna check with somebody with more experience. :) Thank you both. -- http://mail.python.org/mailman/listinfo/python-list
How to cleanly pause/stop a long running function?
Suppose I have a function that may run for a long time - perhaps from several minutes to several hours. An example would be this file processing function: import os def processFiles(startDir): for root, dirs, files in os.walk(startDir): for fname in files: if fname.lower().endswith(.zip): # ... do interesting stuff with the file here ... Imagine that there are thousands of files to process. This could take a while. How can I implement this so that the caller can pause or interrupt this function, and resume its program flow? Doing a Ctrl+C interrupt would be a not-so-clean-way of performing such a thing, and it would quit the application altogether. I'd rather have the function return a status object of what it has accomplished thus far. I have heard about threads, queues, and asynchronous programming, but am not sure which is appropriate for this and how to apply it. Perhaps the above function should be a method of a class that inherits from the appropriate handler class? Any help will be appreciated. -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Optimizing numpy
I have the following, that is used to convert pixel data and thus should be as fast as possible: b = numpy.ndarray (shape=(w,h,4), dtype=numpy.uint8) a = numpy.frombuffer(buf, numpy.uint8) a.shape = (w, h, 3) b[:,:,0] = a[:,:,2] b[:,:,1] = a[:,:,1] b[:,:,2] = a[:,:,0] b[:,:,3] = 255 Can anyone tell me if there is a faster way? Will making use of weave.blitz or pyrex help? Thank You. -- http://mail.python.org/mailman/listinfo/python-list
Bug? import cp1252
Hi! I've a problem with these 2 scripts: file aaa.py (write in ANSI/cp1252): # -*- coding: cp1252 -*- compo={} compo['pxrtf']= { 'fichier': pxrtf.py, 'description': Génération de fichiers RTF } file bbb.py (write in ANSI/cp1252): # -*- coding: cp1252 -*- import aaa With run bbb.py, I see: Traceback (most recent call last): File D:\dev\python\bbb.py, line 3, in module import aaa File D:\dev\python\aaa.py, line 3 ^ SyntaxError: invalid syntax (run directly aaa.py give no problem) (Python 2.5.1 + win_XP-SP2_french) BUT, if I write the file aaa.py in UTF-8, with 1st line:# -*- coding: utf-8 -*- the problem is removed (file bbb.py stay in ANSI/cp1252) Bug? or am I wrong? @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
ctree data
A friend needs to convert c-tree plus data to MySql. I can to the to MySql part, but need some help with the from c-tree. If I just wanted to get this done, I would hunt down the ODBC driver and use some MSy thing. But I am trying to hone my Python skills, but right now I am in over my head, thus this post. I think with a little boost I will be able to make it all come together. (well, little boost may be an understatement - I have no clue how close/far I am from what I need.) My searching around has come up with a few ways to use Python to read the data: 1. pull what I need from some other py code that uses c-tree: http://oltp-platform.cvs.sourceforge.net/oltp-platform/OLTPP/services/PythonScript/PythonTranslate.h?view=markup http://oltp-platform.cvs.sourceforge.net/oltp-platform/OLTPP/scripts/TestZipCodes.py?view=markup 12 a,b,c = ZipCode.Get() 13 print Zip code is , a 14 print State is , b 15 print City is , c I am sure this is what I want. I just haven't figured out where to start. 2. Pyrex to create Python bindings to C API with minimal C knowledge. I took C and did a few little utilities on my own in the 90's. plus I can make a tarball. today I am not sure I even qualify for minimal. 3. the C API is present as a shared object (.so), use it from Python with ctypes. I have no idea what that means. 4. odbc - I am actually not thrilled about using the ctree odbc driver in any environment, because someone else who tried to use it on some other data a few years ago said it was flaky, and support was next to useless. 5, get someone who knows perl to do it using http://cpan.uwinnipeg.ca/htdocs/Db-Ctree/Db/Ctree.html - This just shows what lengths I am willing to go to. but I really don't want to start learning perl. TIA Carl K -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Python REGEX Question
johnny [EMAIL PROTECTED] wrote: I need to get the content inside the bracket. eg. some characters before bracket (3.12345). I need to get whatever inside the (), in this case 3.12345. How do you do this with python regular expression? I'm going to presume that you mean something like: I want to extract floating point numerics from parentheses embedded in other, arbitrary, text. Something like: given='adfasdfafd(3.14159265)asdfasdfadsfasf' import re mymatch = re.search(r'\(([0-9.]+)\)', given).groups()[0] mymatch '3.14159265' Of course, as with any time you're contemplating the use of regular expressions, there are lots of questions to consider about the exact requirements here. What if there are more than such pattern? Do you only want the first match per line (or other string)? (That's all my example will give you). What if there are no matches? My example will raise an AttributeError (since the re.search will return the None object rather than a match object; and naturally the None object has no .groups()' method. The following might work better: mymatches = re.findall(r'\(([0-9.]+)\)', given).groups()[0] if len(mymatches): ... ... and, of couse, you might be better with a compiled regexp if you're going to repeast the search on many strings: num_extractor = re.compile(r'\(([0-9.]+)\)') for line in myfile: for num in num_extractor(line): pass # do whatever with all these numbers -- Jim Dennis, Starshine: Signed, Sealed, Delivered -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
Cesar G. Miguel [EMAIL PROTECTED] writes: I've been studying python for 2 weeks now and got stucked in the following problem: for j in range(10): print j if(True): j=j+2 print 'interno',j What happens is that j=j+2 inside IF does not change the loop counter (j) as it would in C or Java, for example. Granted this question has already been answered in parts, but I just wanted to elaborate. Although the python for/in loop is superficially similar to C and Java for loops, they work in very different ways. Range creates a list object that can create an iterator, and the for/in construct under the hood sets j to the results of iterator.next(). The equivalent completely untested java would be something like: public ArrayListObject range(int n){ a = new ArrayListObject; //Java 1.5 addition I think. for(int x=0,xn,x++){ a.add(new Integer(x)); } return a; } Iterator i = range(10).iterator(); Integer j; while i.hasNext(){ j = i.next(); system.out.println(j.toString()); j = j + 2; system.out.println(interno + j.toString()); } This probably has a bunch of bugs. I'm learning just enough java these days to go with my jython. 1: Python range() returns a list object that can be expanded or modified to contain arbitrary objects. In java 1.5 this would be one of the List Collection objects with a checked type of java.lang.Object. So the following is legal for a python list, but would not be legal for a simple C++ or Java array. newlist = range(10) newlist[5] = foo newlist[8] = open(filename,'r') 2: The for/in loop takes advantage of the object-oriented nature of list objects to create an iterator for the list, and then calls iterator.next() until the iterator runs out of objects. You can do this in python as well: i = iter(range(10)) while True: try: j = i.next() print j j = j + 2 print j except StopIteration: break Python lists are not primitive arrays, so there is no need to explicitly step through the array index by index. You can also use an iterator on potentially infinite lists, streams, and generators. Another advantage to for/in construction is that loop counters are kept nicely separate from the temporary variable, making it more difficult to accidentally short-circuit the loop. If you want a loop with the potential for a short-circuit, you should probably use a while loop: j = 0 while j 10: if j == 5: j = j + 2 else: j = j + 1 print j Am I missing something? []'s Cesar -- Kirk Job Sluder -- http://mail.python.org/mailman/listinfo/python-list
Re: mmap thoughts
In article [EMAIL PROTECTED], James T. Dennis [EMAIL PROTECTED] wrote: * There don't seem to be any currently maintained SysV IPC (shm, message, and semaphore) modules for Python. I guess some people have managed to hack something together using ctypes; but I haven't actually read, much less tested, any of that code. http://NikitaTheSpider.com/python/shm/ Enjoy =) -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more -- http://mail.python.org/mailman/listinfo/python-list
Re: Popen and wget, problems
Jesse [EMAIL PROTECTED] writes: Hi all, I have a problem using wget and Popen. I hope someone can help. -- Problem -- I want to use the command: wget -nv -O dir/cpan.txt http://search.cpan.org; and capture all it's stdout+stderr. (Note that option -O requires 'dir' to be existing before wget is executed) Popen doesn't work, while os.system and shell do. Popen will give the error: dir/cpan.txt: No such file or directory While os.system and shell will give the correct result: 06:52:40 URL:http://search.cpan.org/ [3657/3657] - dir1/cpan.txt [1] [...] -- Python Code using Popen with cmd arg list -- # imports import os from subprocess import Popen, PIPE # vars and create dir cmd_set = ['wget', '-nv', '-O dir/cpan.txt', 'http://search.span.org'] cmd = ' '.join(cmd_set) print cmd: + cmd try: os.makedirs('dir') except: print 'dir already exists' # execute using Popen (does NOT work) proc = Popen(cmd_set, stdout=PIPE, stderr=PIPE) return_code = proc.wait() if return_code == 0: print Success:\n%s % (proc.stdout.read() + proc.stderr.read()) else: print Failure %s:\n%s % (return_code, proc.stderr.read() + proc.stdout.read()) # execute using os.system (does work) os.system(cmd) -- Python code output of Popen -- Failure 1: dir/cpan.txt: No such file or directory -- Question -- Why is Popen unable to correctly execute the wget, while os.system can? I don't know exactly why in this case Popen doesn't work, but the counterpart of os.system is Popen with option shell=True and the first parameter should be a string instead of list. That seems to work: proc = Popen(wget -nv -O dir/cpan.txt http://search.span.org;, shell=True, stdout=PIPE, stderr=PIPE) and this variant seems to work too: cmd_set = ['wget', '-nv', '-O', 'dir/cpan.txt', 'http://search.span.org'] -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Optimizing numpy
On May 12, 10:52 pm, Gerdus van Zyl [EMAIL PROTECTED] wrote: I have the following, that is used to convert pixel data and thus should be as fast as possible: b = numpy.ndarray (shape=(w,h,4), dtype=numpy.uint8) a = numpy.frombuffer(buf, numpy.uint8) a.shape = (w, h, 3) b[:,:,0] = a[:,:,2] b[:,:,1] = a[:,:,1] b[:,:,2] = a[:,:,0] b[:,:,3] = 255 You can express this as: b[:,:,0:3] = a[:,:,2:-1:-1] b[:,:,3] = 255 Can anyone tell me if there is a faster way? Will making use of weave.blitz or pyrex help? If you are going to use wave, then don't bother with weave.blitz use wave.inline instead. You'll need something like this: code = register char a0, a1, a2; for (int i=0; iw*h; i++) { a0 = *a++; a1 = *a++; a2 = *a++; *b++ = a2; *b++ = a1; *b++ = a0; *b++ = 0xFF; } wave.inline(code,['a','b','h','w'],compiler='gcc') Sturla Molden -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie look at Python and OO
You started this thread with a list of conceptual problems you were having. Are they now cleared up? Yes. Thank you, and everybody else. I'm still learning, and still getting used to Python. But, I understand the concepts that I was having trouble with before. -- http://mail.python.org/mailman/listinfo/python-list
Re: Bug? import cp1252
On May 13, 3:33 am, Méta-MCI [EMAIL PROTECTED] wrote: Hi! I've a problem with these 2 scripts: file aaa.py (write in ANSI/cp1252): What is ANSI/cp1252??? # -*- coding: cp1252 -*- compo={} compo['pxrtf']= { 'fichier': pxrtf.py, 'description': Génération de fichiers RTF } file bbb.py (write in ANSI/cp1252): # -*- coding: cp1252 -*- import aaa With run bbb.py, I see: Traceback (most recent call last): File D:\dev\python\bbb.py, line 3, in module import aaa File D:\dev\python\aaa.py, line 3 ^ SyntaxError: invalid syntax (run directly aaa.py give no problem) (Python 2.5.1 + win_XP-SP2_french) BUT, if I write the file aaa.py in UTF-8, with 1st line:# -*- coding: utf-8 -*- the problem is removed (file bbb.py stay in ANSI/cp1252) Bug? or am I wrong? @-salutations Michel, I can't reproduce this -- Python 2.5.1, Windows XP Pro SP2 Given that the syntax error seems to be pointing to a blank empty line, I suspect that's there's some invisible character in the file. This would be likely not to show up when we view your file through a web browser or news client. I suggest that you show us *exactly* what you've got: print open('aaa.py', 'rb').read() HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
Cesar G. Miguel [EMAIL PROTECTED] wrote: On May 12, 3:40 pm, Dmitry Dzhus [EMAIL PROTECTED] wrote: Actually I'm trying to convert a string to a list of float numbers: str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0] str=53,20,4,2 map(lambda s: float(s), str.split(',')) Last expression returns: [53.0, 20.0, 4.0, 2.0] -- Happy Hacking. Dmitry Sphinx Dzhushttp://sphinx.net.ru Nice! As somebody else alredy pointed out, the lambda is supererogatory (to say the least). The following also works using split and list comprehension (as suggested in a brazilian python forum): --- L = [] file = ['5,1378,1,9', '2,1,4,5'] str='' for item in file: L.append([float(n) for n in item.split(',')]) The assignment to str is useless (in fact potentially damaging because you're hiding a built-in name). L = [float(n) for item in file for n in item.split(',')] is what I'd call Pythonic, personally (yes, the two for clauses need to be in this order, that of their nesting). Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic subclassing ?
manatlan [EMAIL PROTECTED] wrote: I've got an instance of a class, ex : b=gtk.Button() I'd like to add methods and attributes to my instance b. I know it's possible by hacking b with setattr() methods. But i'd like to do it with inheritance, a kind of dynamic subclassing, without subclassing the class, only this instance b ! In fact, i've got my instance b, and another class MoreMethods class MoreMethods: def sayHello(self): print hello How could i write ... b = b + MoreMethods so b will continue to be a gtk.Button, + methods/attributs of MoreMethods (it's what i call dynamic inheritance) ...so, things like this should work : - b.set_label(k) - b.sayHello() I can't find the trick, but i'm pretty sure it's possible in an easy way. I think what you're asking for is totally weird, and with just about zero advantages compared with several saner alternatives that have already been proposed in this thread and that you have rejects, but sure, it's possible: def addaclass(aninst, onemoreclass): aninst.__class__ = type(aninst.__aclass__.__name__, (aninst.__aclass__, onemoreclass), {}) Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: ctree data
Carl K [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] |A friend needs to convert c-tree plus data to MySql. I can to the to MySql | part, but need some help with the from c-tree. If I just wanted to get this | done, I would hunt down the ODBC driver and use some MSy thing. But I am trying | to hone my Python skills, | My searching around has come up with a few ways to use Python to read the data: | | 1. pull what I need from some other py code that uses c-tree: | | http://oltp-platform.cvs.sourceforge.net/oltp-platform/OLTPP/services/PythonScript/PythonTranslate.h?view=markup | http://oltp-platform.cvs.sourceforge.net/oltp-platform/OLTPP/scripts/TestZipCodes.py?view=markup | | 12 a,b,c = ZipCode.Get() | 13 print Zip code is , a | 14 print State is , b | 15 print City is , c | | I am sure this is what I want. I just haven't figured out where to start. | | 2. Pyrex to create Python bindings to C API with minimal C knowledge. I took | C and did a few little utilities on my own in the 90's. plus I can make a | tarball. today I am not sure I even qualify for minimal. | | 3. the C API is present as a shared object (.so), use it from Python with | ctypes. I have no idea what that means. [snip] I personally would start with either 1 or 3, but probably 3 since the skill of using ctypes is transferable to other problems and I want to learn it anyway. Ctypes is a foreign function interface (FFI) module. It is new in the Python stdlib with 2.5 but has been around as a 3rd party module much longer. With a specification of the C API in hand, you should be able to write Python functions that call functions in the shared library. Ctypes handles the interconversion of Python and C datatypes and the calling details. I would start with the simplest thing that you can verify working: open database, get some info that you can print, so you know you really opened it, and close database. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
On May 12, 6:18 pm, Cesar G. Miguel [EMAIL PROTECTED] wrote: Am I missing something? Python for loops iterates over the elements in a container. It is similar to Java's for each loop. for j in range(10): print j if(True): j=j+2 print 'interno',j Is equivalent to: int[] range = {0,1,2,3,4,5,6,7,8,9}; for (int j : range) { system.out.writeln(j); if (true) { j += 2; system.out.writeln(iterno + j); } } If I remember Java correctly... -- http://mail.python.org/mailman/listinfo/python-list
Licence for webchecker module?
I want to use webchecker.py (distributed in Tools/webchecker of the Python source code tarball) in a project, but there is no license listed in any of the scripts that I can see. Is this code covered by the standard Python license? -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
__dict__ for instances?
While using PyGTK, I want to try and define signal handlers automagically, without explicitly writing the long dictionary (i.e. I want to use signal_autoconnect()). To do this, I need something that will inspect the current self and return a dictionary that looks like: { method_name : self.method_name } Class.__dict__ does something very similar, but when I use it, either I'm doing something wrong or it doesn't return methods bound to self, and python complains a wrong number of arguments is being passed to the methods (one instead of two). instance.__dict__ on the other hand returns an empty dictionary. This looks like it should be easy, but I can't find the solution :( -- (\__/) (O.o) ( ) This is Bunny. Copy Bunny into your signature to help him on his way to world domination! signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: ctree data
On May 13, 7:05 am, Carl K [EMAIL PROTECTED] wrote: A friend needs to convert c-tree plus data to MySql. I can to the to MySql part, but need some help with the from c-tree. If I just wanted to get this done, I would hunt down the ODBC driver and use some MSy thing. But I am trying to hone my Python skills, but right now I am in over my head, thus this post. I think with a little boost I will be able to make it all come together. (well, little boost may be an understatement - I have no clue how close/far I am from what I need.) My searching around has come up with a few ways to use Python to read the data: 1. pull what I need from some other py code that uses c-tree: http://oltp-platform.cvs.sourceforge.net/oltp-platform/OLTPP/services...http://oltp-platform.cvs.sourceforge.net/oltp-platform/OLTPP/scripts/... 12 a,b,c = ZipCode.Get() 13 print Zip code is , a 14 print State is , b 15 print City is , c I am sure this is what I want. I just haven't figured out where to start. 2. Pyrex to create Python bindings to C API with minimal C knowledge. I took C and did a few little utilities on my own in the 90's. plus I can make a tarball. today I am not sure I even qualify for minimal. 3. the C API is present as a shared object (.so), use it from Python with ctypes. I have no idea what that means. 4. odbc - I am actually not thrilled about using the ctree odbc driver in any environment, because someone else who tried to use it on some other data a few years ago said it was flaky, and support was next to useless. 5, get someone who knows perl to do it usinghttp://cpan.uwinnipeg.ca/htdocs/Db-Ctree/Db/Ctree.html- This just shows what lengths I am willing to go to. but I really don't want to start learning perl. Possible option 6: Find out if there is (a) a ctree utility program that dumps a ctree table to a flat file in documented easily-parsed format plus (b) a method of getting the metadata for each column (type, decimal places, etc) if that info is not already available from (a). It's entirely possible that SQL select * from the_table will do (a) for you, if the output is given with full precision, and there's a method of getting the columns delimited properly. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Interesting list Validity (True/False)
On May 12, 12:56?pm, Carsten Haese [EMAIL PROTECTED] wrote: On Fri, 2007-05-11 at 14:26 -0700, [EMAIL PROTECTED] wrote: if arg==True: tests the type property (whether a list is a boolean). That sounds nonsensical and incorrect. Please explain what you mean. quote Sec 2.2.3: Objects of different types, except different numeric types and different string types, never compare equal; /quote if arg==True tests whether the object known as arg is equal to the object known as True. Regards, -- Carsten Haesehttp://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job
On Apr 29, 2:44 am, War Office [EMAIL PROTECTED] wrote: Why can't any of you just discuss the fact that free-fall collapse of this building contradicts the laws of physics? Why do you assume he's even capable of doing so? He's just a crackpot, but he's in the unfortunate majority. Why do you all have to avoid the topic and rather go on a character assassination which is totally abhorent to scientific method? That is the new scientific method. -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread-safe dictionary
On May 12, 11:40 am, Martin v. Löwis [EMAIL PROTECTED] wrote: - in __getitem__, does it release the lock after returning the item? Yes, it does. - wouldn't it be better to use threading.RLock, mutex, ... instead? Better in what sense? Performance-wise? Semantically? Performance-wise, the best thing would be to do safe_dict = dict because the builtin dict is already thread-safe unless user-defined __hash__ or __eq__ methods get invoked (in which case the dictionary still works correctly - it's only that it may get modified while __hash__ or __eq__ is running). Semantically, it would be better to use a threading.RLock, if you expect that __hash__ or __eq__ may access the dictionary recursively. Regards, Martin Thank you! -- http://mail.python.org/mailman/listinfo/python-list
Re: How to cleanly pause/stop a long running function?
On May 12, 4:51 pm, Basilisk96 [EMAIL PROTECTED] wrote: Suppose I have a function that may run for a long time - perhaps from several minutes to several hours. An example would be this file processing function: import os def processFiles(startDir): for root, dirs, files in os.walk(startDir): for fname in files: if fname.lower().endswith(.zip): # ... do interesting stuff with the file here ... Imagine that there are thousands of files to process. This could take a while. How can I implement this so that the caller can pause or interrupt this function, and resume its program flow? Doing a Ctrl+C interrupt would be a not-so-clean-way of performing such a thing, and it would quit the application altogether. I'd rather have the function return a status object of what it has accomplished thus far. I have heard about threads, queues, and asynchronous programming, but am not sure which is appropriate for this and how to apply it. Perhaps the above function should be a method of a class that inherits from the appropriate handler class? Any help will be appreciated. -Basilisk96 Consider using generators. http://docs.python.org/tut/node11.html#SECTION0011100 This way, whatever part of your program calls this function can completely control the iteration. Maybe you can have it yield status information each time. -- http://mail.python.org/mailman/listinfo/python-list
Re: Interesting list Validity (True/False)
On Sat, 2007-05-12 at 17:55 -0700, [EMAIL PROTECTED] wrote: On May 12, 12:56?pm, Carsten Haese [EMAIL PROTECTED] wrote: On Fri, 2007-05-11 at 14:26 -0700, [EMAIL PROTECTED] wrote: if arg==True: tests the type property (whether a list is a boolean). That sounds nonsensical and incorrect. Please explain what you mean. quote Sec 2.2.3: Objects of different types, except different numeric types and different string types, never compare equal; /quote That doesn't explain what you mean. How does if arg==True test whether a list is a boolean? -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Problems with thread safety
Hi, In my C program, I want to use python scripts. This scripts should also have the ability to start threads. So at the initilisation phase I do: PyEval_InitThreads(); PyEval_ReleaseLock(); With the second call I want to release lock, for that the python threads can also do their work. But then, when I call a method in a script which starts a thread then, I get the following error: Fatal Python error: PyEval_AcquireThread: non-NULL old thread state Aborted (core dumped) What did I wrong? -- http://mail.python.org/mailman/listinfo/python-list
Re: Interesting list Validity (True/False)
On May 12, 8:10?pm, Carsten Haese [EMAIL PROTECTED] wrote: On Sat, 2007-05-12 at 17:55 -0700, [EMAIL PROTECTED] wrote: On May 12, 12:56?pm, Carsten Haese [EMAIL PROTECTED] wrote: On Fri, 2007-05-11 at 14:26 -0700, [EMAIL PROTECTED] wrote: if arg==True: tests the type property (whether a list is a boolean). That sounds nonsensical and incorrect. Please explain what you mean. quote Sec 2.2.3: Objects of different types, except different numeric types and different string types, never compare equal; /quote That doesn't explain what you mean. How does if arg==True test whether a list is a boolean? type(sys.argv) type 'list' type(True) type 'bool' Actually, it's this statement that's non-sensical. quote if arg==True tests whether the object known as arg is equal to the object known as True. /quote None of these four examples are equal to any other. a = 1 b = (1,) c = [1] d = gmpy.mpz(1) type(a) type 'int' type(b) type 'tuple' type(c) type 'list' type(d) type 'mpz' a==b False b==c False a==d True And yet a==d returns True. So why doesn't b==c also return True, they both have a 1 at index position 0? x = [1] y = [1] x==y True -- Carsten Haesehttp://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
[ANN] PyYAML-3.05: YAML parser and emitter for Python
Announcing PyYAML-3.05 A new bug fix release of PyYAML is now available: http://pyyaml.org/wiki/PyYAML Changes === * Windows binary packages were built with LibYAML trunk. * Fixed a bug that prevent processing a live stream of YAML documents in timely manner (Thanks edward(at)sweetbytes(dot)net). * Fixed a bug when the path in add_path_resolver contains boolean values (Thanks jstroud(at)mbi(dot)ucla(dot)edu). * Fixed loss of microsecond precision in timestamps (Thanks edemaine(at)mit(dot)edu). * Fixed loading an empty YAML stream. * A number of smaller fixes and improvements (see http://pyyaml.org/wiki/PyYAML#History for more details). Resources = PyYAML homepage: http://pyyaml.org/wiki/PyYAML PyYAML documentation: http://pyyaml.org/wiki/PyYAMLDocumentation TAR.GZ package: http://pyyaml.org/download/pyyaml/PyYAML-3.05.tar.gz ZIP package: http://pyyaml.org/download/pyyaml/PyYAML-3.05.zip Windows installer: http://pyyaml.org/download/pyyaml/PyYAML-3.05.win32-py2.3.exe http://pyyaml.org/download/pyyaml/PyYAML-3.05.win32-py2.4.exe http://pyyaml.org/download/pyyaml/PyYAML-3.05.win32-py2.5.exe PyYAML SVN repository: http://svn.pyyaml.org/pyyaml Submit a bug report: http://pyyaml.org/newticket?component=pyyaml YAML homepage: http://yaml.org/ YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core About PyYAML YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object. PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistance. Example === import yaml yaml.load( ... name: PyYAML ... description: YAML parser and emitter for Python ... homepage: http://pyyaml.org/wiki/PyYAML ... keywords: [YAML, serialization, configuration, persistance, pickle] ... ) {'keywords': ['YAML', 'serialization', 'configuration', 'persistance', 'pickle'], 'homepage': 'http://pyyaml.org/wiki/PyYAML', 'description': 'YAML parser and emitter for Python', 'name': 'PyYAML'} print yaml.dump(_) name: PyYAML homepage: http://pyyaml.org/wiki/PyYAML description: YAML parser and emitter for Python keywords: [YAML, serialization, configuration, persistance, pickle] Copyright = The PyYAML module is written by Kirill Simonov [EMAIL PROTECTED]. PyYAML is released under the MIT license. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to cleanly pause/stop a long running function?
On Sat, 12 May 2007 13:51:05 -0700, Basilisk96 wrote: Suppose I have a function that may run for a long time - perhaps from several minutes to several hours. An example would be this file processing function: import os def processFiles(startDir): for root, dirs, files in os.walk(startDir): for fname in files: if fname.lower().endswith(.zip): # ... do interesting stuff with the file here ... Imagine that there are thousands of files to process. This could take a while. How can I implement this so that the caller can pause or interrupt this function, and resume its program flow? I don't think there really is what I would call a _clean_ way, although people may disagree about what's clean and what isn't. Here's a way that uses global variables, with all the disadvantages that entails: last_dir_completed = None restart = object() # a unique object def processFiles(startDir): global last_dir_completed if startDir is restart: startDir = last_dir_completed for root, dirs, files in os.walk(startDir): for fname in files: if fname.lower().endswith(.zip): # ... do interesting stuff with the file here ... last_Dir_completed = root Here's another way, using a class. Probably not the best way, but a way. class DirLooper(object): def __init__(self, startdir): self.status = new self.startdir = startdir self.root = startdir def run(self): if self.status == 'new': self.loop(self.startdir) elif self.status == 'finished': print nothing to do else: self.loop(self.root) def loop(self, where): self.status = started for self.root, dirs, files in os.walk(where): # blah blah blah... Here's another way, catching the interrupt: def processFiles(startDir): try: for root, dirs, files in os.walk(startDir): # blah blah blah ... except KeyboardInterrupt: do_something_with_status() You can fill in the details :) As for which is better, I think the solution using a global variable is the worst, although it has the advantage of being easy to implement. I think you may need to try a few different implementations and judge for yourself. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to cleanly pause/stop a long running function?
Doing a Ctrl+C interrupt would be a not-so-clean-way of performing such a thing, and it would quit the application altogether. I'd rather have the function return a status object of what it has accomplished thus far. Just in case you are unaware that you can explicitly handle ^C in your python code, look up the KeyboardInterrupt exception. mt -- http://mail.python.org/mailman/listinfo/python-list
Re: Interesting list Validity (True/False)
On Sat, 12 May 2007 18:43:54 -0700, [EMAIL PROTECTED] wrote: On May 12, 8:10?pm, Carsten Haese [EMAIL PROTECTED] wrote: On Sat, 2007-05-12 at 17:55 -0700, [EMAIL PROTECTED] wrote: On May 12, 12:56?pm, Carsten Haese [EMAIL PROTECTED] wrote: On Fri, 2007-05-11 at 14:26 -0700, [EMAIL PROTECTED] wrote: if arg==True: tests the type property (whether a list is a boolean). That sounds nonsensical and incorrect. Please explain what you mean. quote Sec 2.2.3: Objects of different types, except different numeric types and different string types, never compare equal; /quote I should point out that only applies to built-in types, not custom classes. That doesn't explain what you mean. How does if arg==True test whether a list is a boolean? type(sys.argv) type 'list' type(True) type 'bool' That still doesn't make sense. However, using my incredible psychic ability to read between the lines, I think what Mensanator is trying (but failing) to say is that if arg==True first tests whether arg is of type bool, and if it is not, it knows they can't be equal. That's not actually correct. We can check this: import dis def test(arg): ... return arg == True ... dis.dis(test) 2 0 LOAD_FAST0 (arg) 3 LOAD_GLOBAL 0 (True) 6 COMPARE_OP 2 (==) 9 RETURN_VALUE As you can see, there is no explicit type test. (There may or may not be an _implicit_ type test, buried deep in the Python implementation of the COMPARE_OP operation, but that is neither here nor there.) Also, since bool is a subclass of int, we can do this: 1.0+0j == True True Actually, it's this statement that's non-sensical. quote if arg==True tests whether the object known as arg is equal to the object known as True. /quote Not at all, it makes perfect sense. X == Y always tests whether the argument X is equal to the object Y regardless of what X and Y are. None of these four examples are equal to any other. That's actually wrong, as you show further down. a = 1 b = (1,) c = [1] d = gmpy.mpz(1) type(a) type 'int' type(b) type 'tuple' type(c) type 'list' type(d) type 'mpz' a==b False b==c False a==d True See, a and d are equal. And yet a==d returns True. So why doesn't b==c also return True, they both have a 1 at index position 0? Why should they return true just because the contents are the same? A bag of shoes is not the same as a box of shoes, even if they are the same shoes. Since both lists and tuples are containers, neither are strings or numeric types, so the earlier rule applies: they are different types, so they can't be equal. gmpy.mpz(1) on the other hand, is both a numeric type and a custom class. It is free to define equal any way that makes sense, and it treats itself as a numeric type and therefore says that it is equal to 1, just like 1.0 and 1+0j are equal to 1. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Read from Windows Address Book (.wab file format) ?
On May 13, 3:57 am, rynt [EMAIL PROTECTED] wrote: On May 12, 11:30 am, 詹光耀 [EMAIL PROTECTED] wrote: Hi all! I wonder if there's any Python module that could read from .wab file. I googled but found nothing useful. Any idea? Thanks :) Rio Hi Rio, Don't know if there's a python module for this, but this link, http://msdn2.microsoft.com/en-us/library/ms629361.aspx defines the MS API for the address book, so you could roll your own. If all you need is to read the data though, you could export the address data into a CSV file (Python DOES have a module for this) or VCard format. IIRC, someone on this newsgroup was talking about VCard just the other day. HTH rynt Hi Rynt, Thanks for your help :) I looked the MSDN page but it seemed that at least I need Windows to use its DLL, while unfortunately I'm on Linux. I need to read (and later write) .wab from other Win users. CSV is fine, and that's how I am doing it right now. The problem is I cannot automate the process of exporting .wab to .csv on Linux. Also, I lose all the identity-property mapping in .wab since .csv is really a flat 2D table. Any other suggesions? :) Rio -- http://mail.python.org/mailman/listinfo/python-list
Re: __dict__ for instances?
On May 12, 5:20 pm, Ivan Voras [EMAIL PROTECTED] wrote: While using PyGTK, I want to try and define signal handlers automagically, without explicitly writing the long dictionary (i.e. I want to use signal_autoconnect()). To do this, I need something that will inspect the current self and return a dictionary that looks like: { method_name : self.method_name } Class.__dict__ does something very similar, but when I use it, either I'm doing something wrong or it doesn't return methods bound to self, and python complains a wrong number of arguments is being passed to the methods (one instead of two). instance.__dict__ on the other hand returns an empty dictionary. This looks like it should be easy, but I can't find the solution :( -- (\__/) (O.o) ( ) This is Bunny. Copy Bunny into your signature to help him on his way to world domination! signature.asc 1KDownload I think you want dir(instance) __dict__ returns the instance variables and values as a dictionary, but doesn't return methods. dir() returns a list of the instance's methods and variables. Then you'd need to iterate over the list with type() looking for instance methods instance = Class.Class() dict = {} methods = [f for f in dir(instance) if str(type(instance.f)) == type 'instancemethod'] for m in methods: dict[m.name] = m The above is untested. I'm sure there is a better way to do this. ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: Interesting list Validity (True/False)
On May 12, 11:02�pm, Steven D'Aprano [EMAIL PROTECTED] wrote: On Sat, 12 May 2007 18:43:54 -0700, [EMAIL PROTECTED] wrote: On May 12, 8:10?pm, Carsten Haese [EMAIL PROTECTED] wrote: On Sat, 2007-05-12 at 17:55 -0700, [EMAIL PROTECTED] wrote: On May 12, 12:56?pm, Carsten Haese [EMAIL PROTECTED] wrote: On Fri, 2007-05-11 at 14:26 -0700, [EMAIL PROTECTED] wrote: if arg==True: tests the type property (whether a list is a boolean). That sounds nonsensical and incorrect. Please explain what you mean. quote Sec 2.2.3: Objects of different types, except different numeric types and different string types, never compare equal; /quote I should point out that only applies to built-in types, not custom classes. That doesn't explain what you mean. How does if arg==True test whether a list is a boolean? type(sys.argv) type 'list' type(True) type 'bool' That still doesn't make sense. However, using my incredible psychic ability to read between the lines, I think what Mensanator is trying (but failing) to say is that if arg==True first tests whether arg is of type bool, and if it is not, it knows they can't be equal. That's not actually correct. We can check this: import dis def test(arg): ... � � return arg == True ... dis.dis(test) � 2 � � � � � 0 LOAD_FAST � � � � � � � �0 (arg) � � � � � � � 3 LOAD_GLOBAL � � � � � � �0 (True) � � � � � � � 6 COMPARE_OP � � � � � � � 2 (==) � � � � � � � 9 RETURN_VALUE As you can see, there is no explicit type test. (There may or may not be an _implicit_ type test, buried deep in the Python implementation of the COMPARE_OP operation, but that is neither here nor there.) Also, since bool is a subclass of int, we can do this: 1.0+0j == �True True Actually, it's this statement that's non-sensical. quote if arg==True tests whether the object known as arg is equal to the object known as True. /quote Not at all, it makes perfect sense. X == Y always tests whether the argument X is equal to the object Y regardless of what X and Y are. Except for the exceptions, that's why the statement is wrong. None of these four examples are equal to any other. That's actually wrong, as you show further down. No, it's not, as I show further down. a = 1 b = (1,) c = [1] d = gmpy.mpz(1) type(a) type 'int' type(b) type 'tuple' type(c) type 'list' type(d) type 'mpz' a==b False b==c False a==d True See, a and d are equal. No, they are not equal. Ints and mpzs should NEVER be used together in loops, even though it's legal. The ints ALWAYS have to be coerced to mpzs to perform arithmetic and this takes time...LOTS of it. The absolute stupidest thing you can do (assuming n is an mpz) is: while n 1: if n % 2 == 0: n = n/2 else: n = 3*n + 1 You should ALWAYS do: ZED = gmpy.mpz(0) ONE = gmpy.mpz(1) TWO = gmpy.mpz(2) TWE = gmpy.mpz(3) while n ONE: if n % TWO == ZED: n = n/TWO else: n = TWE*n + ONE This way, no coercion is performed. And yet a==d returns True. So why doesn't b==c also return True, they both have a 1 at index position 0? Why should they return true just because the contents are the same? Why should the int 1 return True when compared to mpz(1)? a = [1] b = [1] returns True for a==b? After all, it returns false if b is [2], so it looks at the content in this case. So for numerics, it's the value that matters, not the type. And this creates a false sense of equality when a==d returns True. A bag of shoes is not the same as a box of shoes, even if they are the same shoes. Exactly. For the very reason I show above. The fact that the int has the same shoes as the mpz doesn't mean the int should be used, it has to be coerced. Since both lists and tuples are containers, neither are strings or numeric types, so the earlier rule applies: they are different types, so they can't be equal. But you can't trust a==d returning True to mean a and d are equal. To say the comparison means the two objects are equal is misleading, in other words, wrong. It only takes one turd to spoil the whole punchbowl. gmpy.mpz(1) on the other hand, is both a numeric type and a custom class. It is free to define equal any way that makes sense, and it treats itself as a numeric type and therefore says that it is equal to 1, just like 1.0 and 1+0j are equal to 1. They are equal in the mathematical sense, but not otherwise. And to think that makes no difference is to be naive. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: keyword checker - keyword.kwlist
Gabriel Genellina kirjoitti: En Thu, 10 May 2007 17:03:13 -0300, [EMAIL PROTECTED] escribió: my_input = raw_input(...).strip() as Peter Otten suggested before --Gabriel Genellina Ok, it seems to work with strip(). Thanks for your help. Do you guys have any clue why mine previous code doesn't work? -- http://mail.python.org/mailman/listinfo/python-list
[ python-Bugs-1633621 ] curses should reset curses.{COLS, LINES} when term. resized
Bugs item #1633621, was opened at 2007-01-12 00:38 Message generated for change (Comment added) made by machamalahalaba You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1633621group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Library Group: Python 2.5 Status: Closed Resolution: Fixed Priority: 3 Private: No Submitted By: Matthias Klose (doko) Assigned to: Nobody/Anonymous (nobody) Summary: curses should reset curses.{COLS,LINES} when term. resized Initial Comment: [forwarded from http://bugs.debian.org/366698] The curses module does not reset curses.COLS and curses.LINES when the terminal is resized. -- Comment By: blubb (machamalahalaba) Date: 2007-05-12 18:17 Message: Logged In: YES user_id=1791654 Originator: NO I'm still able to reproduce this bug with Python 2.5.1. The following script always gives the same size: import curses while True: scr = curses.initscr() print curses.LINES, curses.COLS scr.getch() scr.getch() curses.endwin() -- Comment By: Walter Dörwald (doerwalter) Date: 2007-03-06 21:47 Message: Logged In: YES user_id=89016 Originator: NO Checked in as revision 54180 and 54181 (2.5) -- Comment By: Scott Dial (geekmug) Date: 2007-03-05 23:14 Message: Logged In: YES user_id=383208 Originator: NO I've reviewed this patch and I believe it to be the correct patch. I believe it would be prudent to add a test case for this. I'm unable to attach, but here is a link to a patch for that: http://scottdial.com/python-dev/curses-test.patch -- Comment By: Walter Dörwald (doerwalter) Date: 2007-02-12 19:59 Message: Logged In: YES user_id=89016 Originator: NO Here's a patch that implements the requested changes. File Added: diff.txt -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1633621group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-1717900 ] Destructor behavior faulty
Bugs item #1717900, was opened at 2007-05-12 22:41 Message generated for change (Tracker Item Submitted) made by Item Submitter You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1717900group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Interpreter Core Group: None Status: Open Resolution: None Priority: 5 Private: No Submitted By: Wolf Rogner (wrogner) Assigned to: Nobody/Anonymous (nobody) Summary: Destructor behavior faulty Initial Comment: I tried example 11.4. from bytesofpython (by C.H. Swaroop). Example works fine. Added a new Person instance 'wolf' - Program terminated with: Exception exceptions.AttributeError: 'NoneType' object has no attribute 'population' in bound method Person.__del__ of __main__.Person instance at 0xb7d48d6c ignored added print list(globals()) - ['kalam', '__builtins__', '__file__', 'DBGPHideChildren', 'swaroop', 'Person', 'wolf', '__name__', '__doc__'] changed wolf to aaa: print list(globals()) - ['aaa', 'kalam', '__builtins__', '__file__', 'DBGPHideChildren', 'swaroop', 'Person', '__name__', '__doc__'] Please note the position of 'aaa' at the beginning of the list, before 'Person'. With 'wolf' being after 'Person'. If the destructing code removes items in this order, no wonder I get an error. Person should not get deleted if refcount is still 0. Wolf Rogner -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1717900group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-1046945 ] improving distutils swig support - documentation
Bugs item #1046945, was opened at 2004-10-14 10:38 Message generated for change (Comment added) made by gbrandl You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1046945group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Distutils Group: Python 2.4 Status: Closed Resolution: Accepted Priority: 5 Private: No Submitted By: Lars Immisch (larsimmisch) Assigned to: Nobody/Anonymous (nobody) Summary: improving distutils swig support - documentation Initial Comment: This patch updates the documentation of distutils to describe the new swig_opts Extension keyword argument and the new --swig-opts commandline option. The --swig and --swig-cpp commandline options are not mentioned. This patch belongs to patch 1046644 or: http://sourceforge.net/tracker/index.php?func=detailaid=1046644group_id=5470atid=105470 -- Comment By: Georg Brandl (gbrandl) Date: 2007-05-12 21:07 Message: Logged In: YES user_id=849994 Originator: NO Committed as rev. 55287, 55288 (2.5). -- Comment By: Morten Lied Johansen (epcylon) Date: 2007-04-24 08:26 Message: Logged In: YES user_id=574105 Originator: NO Err... did this patch ever get in? (I've been looking in the docs for this information, but couldn't find it anywhere) -- Comment By: Fred L. Drake, Jr. (fdrake) Date: 2004-10-14 14:01 Message: Logged In: YES user_id=3066 This looks fine to go in after the 2.4b1 release; it's too late to change the docs for that one (the tarball has already been built). -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1046945group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-1583862 ] yield+break stops tracing
Bugs item #1583862, was opened at 2006-10-24 15:55 Message generated for change (Settings changed) made by gbrandl You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1583862group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Interpreter Core Group: Python 2.5 Status: Pending Resolution: Wont Fix Priority: 5 Private: No Submitted By: Lukas Lalinsky (luks) Assigned to: Nobody/Anonymous (nobody) Summary: yield+break stops tracing Initial Comment: Here is an example script: def myiter(): for i in range(10): yield i for i in myiter(): break print foo Now, if I try to trace it: $ python -m trace --trace --count test.py --- modulename: threading, funcname: settrace threading.py(70): _trace_hook = func --- modulename: test, funcname: module test.py(1): def myiter(): test.py(5): for i in myiter(): --- modulename: test, funcname: myiter test.py(2): for i in range(10): test.py(3): yield i test.py(6): break c:\python25\lib\ntpath.py:190: RuntimeWarning: tp_compare didn't return -1 or -2 for exception if i=max(p.rfind('/'), p.rfind('\\')): foo It stops tracing after the `break` statement. The line after, `print foo`, is not traced nor included in the coverage output. I'm not sure RuntimeWarning from ntpath.py is relevant here, because if I use the trace module in some other situation it doesn't print it. IMO, it's just a side effect of some different problem. -- Comment By: Raymond Hettinger (rhettinger) Date: 2007-04-11 16:52 Message: Logged In: YES user_id=80475 Originator: NO Using Py2.5.1, the problem seems to have gone away. Lukas, can you please verify that it is solved and then close. === [EMAIL PROTECTED] ~ $ py25/python -m trace --trace --count test.py --- modulename: threading, funcname: settrace threading.py(70): _trace_hook = func --- modulename: trace, funcname: module string(1): --- modulename: trace, funcname: module test.py(1): def myiter(): test.py(6): for i in myiter(): --- modulename: trace, funcname: myiter test.py(2): for i in range(10): test.py(3): yield i test.py(7): break --- modulename: trace, funcname: myiter test.py(9): print 'foo' foo -- Comment By: Lukas Lalinsky (luks) Date: 2006-10-24 16:05 Message: Logged In: YES user_id=587716 Oh, I forgot. This bug is specific to Python 2.5. It works fine in 2.4. -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1583862group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-1700132 ] import and capital letters
Bugs item #1700132, was opened at 2007-04-13 15:06 Message generated for change (Settings changed) made by gbrandl You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1700132group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Interpreter Core Group: Python 2.4 Status: Pending Resolution: None Priority: 5 Private: No Submitted By: omsynge (omsynge) Assigned to: Nobody/Anonymous (nobody) Summary: import and capital letters Initial Comment: Interactive and relative paths allow unlimited (Or at least I have not found a limit yet) number of characters to be uppercase. This is fine, but when the python interpreter reads directories from PYTHONPATH with 3 capital letters you then get a failure to locate the files. I have replicated this issue with python 2.2 and python 2.4. These where with red hat el3 and ubuntu (Some version not sure which) and an example import dcacheYaimInstallerTest.logger as logger works fine in interactive or relative paths, but not when installed via an RPM. import dcacheYaimInstallertest.logger as logger is just fine in both scenarios. This bug cost me some hours to trace and would have cost more had I not had a lot of experience of packaging, so I would be pleased if this could be fixed in all versions of Python. Regards Owen -- Comment By: Martin v. Löwis (loewis) Date: 2007-04-16 05:09 Message: Logged In: YES user_id=21627 Originator: NO I cannot reproduce the problem. The import statement works fine for me when I create /usr/lib/python2.4/site-packages/dcacheYaimInstallerTest/logger.py Can you share the RPM file that causes the problem? -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1700132group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-1717900 ] Destructor behavior faulty
Bugs item #1717900, was opened at 2007-05-12 15:41 Message generated for change (Comment added) made by alanmcintyre You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1717900group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Interpreter Core Group: None Status: Open Resolution: None Priority: 5 Private: No Submitted By: Wolf Rogner (wrogner) Assigned to: Nobody/Anonymous (nobody) Summary: Destructor behavior faulty Initial Comment: I tried example 11.4. from bytesofpython (by C.H. Swaroop). Example works fine. Added a new Person instance 'wolf' - Program terminated with: Exception exceptions.AttributeError: 'NoneType' object has no attribute 'population' in bound method Person.__del__ of __main__.Person instance at 0xb7d48d6c ignored added print list(globals()) - ['kalam', '__builtins__', '__file__', 'DBGPHideChildren', 'swaroop', 'Person', 'wolf', '__name__', '__doc__'] changed wolf to aaa: print list(globals()) - ['aaa', 'kalam', '__builtins__', '__file__', 'DBGPHideChildren', 'swaroop', 'Person', '__name__', '__doc__'] Please note the position of 'aaa' at the beginning of the list, before 'Person'. With 'wolf' being after 'Person'. If the destructing code removes items in this order, no wonder I get an error. Person should not get deleted if refcount is still 0. Wolf Rogner -- Comment By: Alan McIntyre (alanmcintyre) Date: 2007-05-12 18:36 Message: Logged In: YES user_id=1115903 Originator: NO Could you post the code for your entire script? It makes it a lot easier to figure out what's going on. -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1717900group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com