Re: Most direct way to strip unoprintable characters out of a string?
"Steve Bergman" <[EMAIL PROTECTED]> wrote: > George Sakkis wrote: > > > > > > >If by straightforward you mean one-liner, there is: > >''.join(c for c in input_string if c not in string.printable) > > > >If you care about performance though, string.translate is faster; as always, > >the best way to decide > >on a performance issue is to profile the alternatives on your data and see > >if it's worth going for > >the fastest one at the expense of readability. > > > > > > > Thank you for the reply. I was really thinking of some function in the > standard library like: > > s = stripUnprintable(s) > > When I learned php, I more or less took the route of using whatever I > found that 'worked'. In learning Python, I'm trying to take my time and > learn the 'right' (that's pronounced 'beautiful') way of doing things. > > As it stands, I've stashed the string.translate code in a short function > with a comment explaining what it does and how. I mainly didn't want to > use that if there was some trivial built-in that everyone else uses. No there's not a stripUnprintable in a standard module AFAIK, and that's a good thing; if every little function that one might ever wanted made it to the standard library, the language would be overwhelming. Make sure you calculate the unprintable characters only the first time it is called, not every time. Here's a way to encapsulate this in the same function, without polluting the global namespace with allchars and delchars: import string def stripUnprintable(input_string): try: filterUnprintable = stripUnprintable.filter except AttributeError: # only the first time it is called allchars = string.maketrans('','') delchars = allchars.translate(allchars, string.printable) filterUnprintable = stripUnprintable.filter = lambda input: input.translate(allchars, delchars) return filterUnprintable(input_string) George -- http://mail.python.org/mailman/listinfo/python-list
Re: Poor man's OCR: need performance improvement tips
Imagine a large matrix with dimensions [W,H], and a lots of smaller matrices with dimensions [p,q1], [p,q1], [p,q2], [p,q1], ... I have to slide a small window [p,q] horizontally over a larger matrix. After each slide I have to compare smaller matrices with the data from larger matrix (as defined by sliding window). I'm currently trying to use other kinds of optimizations (linearize data by columns), but the program no longer works, and it is so hard to debug. But it works very fast :) Here is an example of linearization by columns that i'm currently using : # setup: convert to 1 bit image img = Image.open(file_name) img2 = img.point([0]*255 + [1], "1") # find ocr lines, and for each do ... # extract OCR line region = img2.crop((0, ocrline.base_y-13, width, ocrline.base_y+3)) # h=16 region.load() # clean up upper two lines which should be empty but # sometimes contain pixels from other ocr line directly above draw = ImageDraw.Draw(region) draw.line((0,0,width,0), fill=1) draw.line((0,1,width,1), fill=1) # transpose data so I get columns as rows region = region.transpose(Image.FLIP_LEFT_RIGHT) region = region.transpose(Image.ROTATE_90) ocrline.data = region.tostring() # packs 8 pixels into 1 octet I do the same for known letters/codes (alphabet). Then I compare like this: def recognize (self, ocrline, x): for code_len in self.code_lengths: # descending order code = ocrline.data[x:x+code_len] ltr = self.letter_codes.get(code, None) if ltr is not None: return ltr, code_len # So I can advance x This currently "works" two orders of magnitude faster. -- http://mail.python.org/mailman/listinfo/python-list
New-style classes questions
I'm confused by the concepts of old-style vs new-style classes, I've read most of the documents I found about this but it doesn't "click". Probably because I wasn't around before 2.2. Anyway, the reason for new style classes are to make the whole type/object thing work better together. There are a number of new features etc. I think my problem is when new-style classes are used, at first I thought that all classes become new-style classes when I was using 2.4, but if I understand things correctly I need to subclass an existing class (assuming that this class does the same) for it to become a new-style class. Have I understood this correctly? If I have, then I've got the following question: Then I could write: class Foo( Object ) to make a new-style class, and class FooA to make an old-style class. What is the reason for allowing both styles? (backwards compatibility??) When I make my own classes should they always be new-style objects or are there reasons for using old-style object? -- http://mail.python.org/mailman/listinfo/python-list
Re: Most direct way to strip unoprintable characters out of a string?
George Sakkis wrote: > No there's not a stripUnprintable in a standard module AFAIK, and > that's a good thing; if every little function that one might ever wanted > made it to the standard library, the language would be overwhelming. ...and if there was a stripUnprintable function in the standard library that was based on C's mostly brain-dead locale model, US programmers would produce even more web applications that just don't work for non- US users... ("sanitizing" HTML data by running filters over encoded 8-bit data is hardly ever the right thing to do...) -- http://mail.python.org/mailman/listinfo/python-list
[RFC] Parametric Polymorphism
Hi, Sorry if this was previously discussed but it's something I miss in Python. I get around this using isinstance() but it would be cleaner to have separate functions with the same name but different argument types. I think the idea gets quite close to the Lisp/CLOS implementation of methods. Below is just simple implementation example (and class functions are not supported) but it can be further extended/optimised/modified for better type detection like issubclass() etc. The idea is similar to the @accepts decorator: methods = dict() def method(*types): def build_method(f): assert len(types) == f.func_code.co_argcount if not f.func_name in methods: methods[f.func_name] = dict() methods[f.func_name][str(types)] = f def new_f(*args, **kwds): type_str = str(tuple([type(arg) for arg in args])) assert type_str in methods[f.func_name] return methods[f.func_name][type_str](*args, **kwds) new_f.func_name = f.func_name return new_f return build_method And its utilisation: @method(int) def test(arg): print 'int', arg @method(float) def test(arg): print 'float', arg test(1) # succeeds test(1.5) # succeeds test(1, 2) # assert fails test('aaa') # assert fails Let me know what you think. Thanks. -- Catalin -- http://mail.python.org/mailman/listinfo/python-list
Re: Extending Embedded Python
Richard Townsend wrote: > In the "Extending and Embedding" part of the Python documentation: section > 5.4 "Extending Embedded Python" - it describes how to use a Python > extension module from Python that is embedded in a C application. > > Is it safe to call Py_InitModule() more than once in the same application - > in order to be able to use more than one extension module? yes. -- http://mail.python.org/mailman/listinfo/python-list
Re: [RFC] Parametric Polymorphism
Catalin Marinas wrote: > Hi, > > Sorry if this was previously discussed but it's something I miss in > Python. I get around this using isinstance() but it would be cleaner > to have separate functions with the same name but different argument > types. I think the idea gets quite close to the Lisp/CLOS > implementation of methods. > > Below is just simple implementation example (and class functions are > not supported) but it can be further extended/optimised/modified for > better type detection like issubclass() etc. The idea is similar to > the @accepts decorator: > > > methods = dict() > > def method(*types): > def build_method(f): > assert len(types) == f.func_code.co_argcount > > if not f.func_name in methods: > methods[f.func_name] = dict() > methods[f.func_name][str(types)] = f > > def new_f(*args, **kwds): > type_str = str(tuple([type(arg) for arg in args])) > assert type_str in methods[f.func_name] > return methods[f.func_name][type_str](*args, **kwds) > new_f.func_name = f.func_name > > return new_f > > return build_method > > > And its utilisation: > > @method(int) > def test(arg): > print 'int', arg > > @method(float) > def test(arg): > print 'float', arg > > test(1) # succeeds > test(1.5) # succeeds > test(1, 2) # assert fails > test('aaa') # assert fails > > > Let me know what you think. Thanks. google for gnosis utils and multimethods to see a more "oldfashioned" implementation. But your approach certainly is interesting - however, I _rarely_ need such functionality. Ususally duck-typing suits me well. Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: New-style classes questions
> What is the reason for allowing both styles? (backwards compatibility??) yes. > > When I make my own classes should they always be new-style objects or are > there reasons for using old-style object? No, use new style if you can - except from the rare cases where above mentioned backwards compatibilty is needed. E.g. exceptions have to be old-style, and for example omniorb needs old-style classes for corba implementations. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Django Vs Rails
Dnia 24 Sep 2005 22:48:40 -0700, [EMAIL PROTECTED] napisał(a): > You should give TurboGears a try. http://www.turbogears.org/about/status.html "TurboGears should be considered *alpha* software. This means that there can be *breaking API* changes between now and 1.0." It uses CherryPy (beta!), SQLObject (beta) and Kid (which has a couple of bugs that need fixing) This project is good only for fun and playing not for enterprise. -- JZ -- http://mail.python.org/mailman/listinfo/python-list
Re: [RFC] Parametric Polymorphism
"Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > google for gnosis utils and multimethods to see a more "oldfashioned" > implementation. I now remember to have seen it but it requires a lot of typing to achieve it and you would call a different function name from the one you define, reducing the code clarity. > But your approach certainly is interesting - however, The idea is not new. Lisp/CLOS implements the defmethod macro which creates a generic function (i.e. a dispatcher) with the same name as the function you define: http://www.lisp.org/HyperSpec/Body/mac_defmethod.html. Actually, the defmehod macro is the base for implementing object polymorphism. > I _rarely_ need such functionality. Ususally duck-typing suits me > well. Of course, duck-typing is simple to use but the parametric polymorphism is useful when the types are unrelated. Let's say you want to implement a colour-print function which should support basic types like ints and floats as well as lists and dictionaries. In this case, and thank to the function decorations support, the code would be clearer. Another use case is to extended the functionality of a class using functions but you cannot easily modify the class or create a subclass (the objects are generated by some factory implemented in a third-party library). Of course, you might be able to get around this but parametric polymorphism could reduce the written code. This idea only needs an optimised (and deterministic) implementation for the best parameter match based on subclass-superclass relations. It can also be extended to implement polymorphism based on the parameter values (something people tried to do in C++ with complicated templates but, well, only at compilation time, with obvious drawbacks). -- Catalin -- http://mail.python.org/mailman/listinfo/python-list
unittest setup
hi all, I noticed that setUp() and tearDown() is run before and after *earch* test* method in my TestCase subclasses. I'd like to run them *once* for each TestCase subclass. How do I do that. thanks paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Memory stats
Tarek Ziadé wrote: > Hi list, > > I am trying to find a general memory profiler that can measure the > memory usage in Python program > and gather some stats about object usages, and things like that. > > I am trying to find a simple python module to be able to customize it > and integrates it to other tools i have. > (it should exists i guess) Try the gc-module. It's a no-brainer to compute a class histogram. I once even wrote my own Qt-based analyzer - maybe I'll release it one day :) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: [RFC] Parametric Polymorphism
Catalin Marinas wrote: > Sorry if this was previously discussed but it's something I miss in > Python. I get around this using isinstance() but it would be cleaner > to have separate functions with the same name but different argument > types. I think the idea gets quite close to the Lisp/CLOS > implementation of methods. Take a look at PJE's generic function implementation. PyCon slides here: http://www.python.org/pycon/2005/papers/53/PyCon05Talk.html. -- Benji York -- http://mail.python.org/mailman/listinfo/python-list
Re: New-style classes questions
Diez B. Roggisch wrote: > > What is the reason for allowing both styles? (backwards compatibility??) > > yes. Note that there is another way to create new-style classes: __metaclass__ = type before the first class definition: >>> class Foo: pass ... >>> type(Foo) >>> __metaclass__ = type >>> class Bar: pass ... >>> type(Bar) I like this. However, perhaps other people reading my source code won't like it, because when they see 'class Foo:', they might expect an old-style class. But it's so much better to type and to read, that I prefer this. Does the Python style guide have any severe penalty for using this? regards, Gerrit. -- Temperature in Luleå, Norrbotten, Sweden: | Current temperature 05-09-25 15:19:47 11.0 degrees Celsius ( 51.9F) | -- Det finns inte dåligt väder, bara dåliga kläder. -- http://mail.python.org/mailman/listinfo/python-list
subprocess considered harmfull?
Hi all, I've been trying to use (Python 2.4 on WinXP) the subprocess module to execute a shell command (nmake in this case), and pass its output to a higher level. Using the following snippet: p = subprocess.Popen(nmake,stderr=subprocess.PIPE,stdout=subprocess.PIPE, \ universal_newlines=True, bufsize=1) os.sys.stdout.writelines(p.stdout) os.sys.stdout.writelines(p.stderr) Works fine on the command line, but fails when called from within Visual Studio, with the following error: File "C:\Python24\lib\subprocess.py", line 549, in __init__ (p2cread, p2cwrite, File "C:\Python24\lib\subprocess.py", line 609, in _get_handles p2cread = self._make_inheritable(p2cread) File "C:\Python24\lib\subprocess.py", line 650, in _make_inheritable DUPLICATE_SAME_ACCESS) TypeError: an integer is required If I replace the functionality with: p = os.popen4(nmake) # p[1] = stdout_and_stderr result pipe p[1].flush() os.sys.stdout.writelines(p[1].readlines()) All is well. I have a feeling this has been encountered before (by googling here), but didn't see any concise answer as to subprocess' robustness. So what is the matter here? And should I consider the subprocess module still unstable? Cheers, Uri -- http://mail.python.org/mailman/listinfo/python-list
Re: Example of signaling and creating a python daemon
Jon Monteleone wrote: > What I dont understand about daemonizing a python script is whether or not it > requires the > daemon creation, ie the signal handling and forking of the process, to be > part of the > daemon code or is this code in a separate program that acts like a wrapper to > turn a > python program into a daemon. The latter is how linux documentation > describes turning a > program into a daemon. > > I guess I am wondering about the difference between using python to daemonize > a program vs > using a bash script to daemonize a program. There is no difference in that. Daemonizing means detaching a process from the invoking process and making it a child to init, together with some other stuff. That's your first case and that's what daemonizing is about. Now if the process then "transforms" itself to another one - like with os.execvpe - that has nothing to say. And it's the way the bash-thingy works, using some daemonize-command that exactly does that. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Django Vs Rails
Jaroslaw Zabiello wrote: > Dnia 24 Sep 2005 22:48:40 -0700, [EMAIL PROTECTED] napisał(a): > > >>You should give TurboGears a try. > > This project is good only for fun and playing not for enterprise. That's my kind of project :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Using '__mul__' within a class
"Gerard Flanagan" <[EMAIL PROTECTED]> writes: [...] > class FibonacciMatrix: [...] > def Copy( self ): [...] __copy__ would be a more standard name. Then: import copy fm = FibonacciMatrix() fm2 = copy.copy(fm) I suppose you could also add: __deepcopy__ = __copy__ in the body of the class definition. John -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamically adding and removing methods
Steven D'Aprano wrote: > Or you could put the method in the class and have all instances recognise > it: > > py> C.eggs = new.instancemethod(eggs, None, C) > py> C().eggs(3) > eggs * 3 Why not just add it to the class directly? You just have to be sure it's a class and not an instance of a class. >>> def beacon(self, x): ...print "beacon + %s" % x ... >>> C.beacon = beacon >>> dir(A) ['__doc__', '__module__', 'beacon', 'ham', 'spam'] >>> A.beacon(3) beacon + 3 >>> del beacon >>> dir(A) ['__doc__', '__module__', 'beacon', 'ham', 'spam'] >>> A.beacon(3) beacon + 3 >>> dir(C) ['__doc__', '__module__', 'beacon', 'ham', 'spam'] Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: New-style classes questions
On Sun, 25 Sep 2005 15:24:29 +0200, Gerrit Holl wrote (in article <[EMAIL PROTECTED]>): > I like this. However, perhaps other people reading my source code won't > like it, because when they see 'class Foo:', they might expect an > old-style class. But it's so much better to type and to read, that I > prefer this. I personally would find this more difficult to read but it's a matter of taste I suppose. > Det finns inte dÃ¥ligt väder, bara dÃ¥liga kläder. Så sant som det var sagt jem -- http://mail.python.org/mailman/listinfo/python-list
Re: How to decompile an exe file compiled by py2exe?
Leo Jay <[EMAIL PROTECTED]> writes: [...] > I opened the `hjparser.exe' file in UltraEdit(a hex editor), and found > some partial statements and comments but not complete. > > so, my problem is i'm sure that the source code is in `hjparser.exe' > but i don't know how to decompile the executable file `hjparser.exe' > into `hjparser.py', [...] Unfortunately, things we're sure of are not always true. But you could try asking on the relevant mailing list for py2exe, making sure to say some nice things about Thomas Heller at the same time ;-) Personally, if the source were valuable to me, I would stop using my hard drive immediately and pay a company to try to recover it, perhaps making a direct copy of my HDD first using a low level copy command like dd, so I had my other data to continue working with (though of course, I'd hope I would have a restorable backup if it were valuable). John -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest setup
paul kölle wrote: > hi all, > > I noticed that setUp() and tearDown() is run before and after *earch* > test* method in my TestCase subclasses. I'd like to run them *once* for > each TestCase subclass. How do I do that. Create a global/test instance flag. Diez -- http://mail.python.org/mailman/listinfo/python-list
py2exe and OpenGL problem
I am using the new py2exe and python 24. When I run my setup.py, the dist seems to generate just fine. However run I run the resulting exe, I get an error: IOError: [Errno 2] No such file or directory 'c:\\app\\dist\\library.zip\\OpenGL\\version' Now I've tried the recommended route with older py2exes, where I exclude OpenGL and copy the entire directory over to my dist, but that didn't work. I included "version" into the "OpenGL" directory via my setup.py script, and it is there right in the library.zip, but I still get the same error. Anyone have any ideas or suggections? Thanks, Patrick -- http://mail.python.org/mailman/listinfo/python-list
Content MathML implementation?
Hi! I was looking for an implementation of a parser/model/serializer for Content MathML in Python. Does anyone know about something useful? I need to work with math expressions (arithmetic/bool), especially converting them between different representations (Python, SQL), determining dependencies on variables etc. And since my output format is Content MathML anyway, I wanted to ask if someone has implemented this before I start doing so. To make it clear: Presentation MathML does not help as it has a completely different model that is not usable for my purpose. Thanks for any hints, Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: What is "self"?
Michael Spencer wrote: > All is explained at: > http://users.rcn.com/python/download/Descriptor.htm#functions-and-methods > and further at: > http://www.python.org/pycon/2005/papers/36/pyc05_bla_dp.pdf > > "For objects, the machinery is in object.__getattribute__ which > transforms b.x into type(b).__dict__['x'].__get__(b, type(b))." > > What follows is my interpretation - hope it's correct: > > # what exactly is a bound method object? > # Illustrate b.f => type(b).__dict__['x'].__get__(b, type(b)) > > >>> class B(object): > ... def f(self, x): > ... return x or 42 > ... > >>> b = B() > >>> type(b).__dict__['f'] ># a plain old function > >>> _.__get__(b, type(b)) # invoke the descriptor protocol > # to make a bound method > > > >>> This still seems not quite right to me... Or more likely seems to be missing something still. (But it could be this migraine I've had the last couple of days preventing me from being able to concentrate on things with more than a few levels of complexity.) Playing around with the shell a bit gives the impression that calling a method in a instance gives the following (approximate) result... try: leader.__dict__["set_name"]("John") except: type(leader).__dict__["set_name"].__get__(leader, "John") # which results in... #Person.set_name(leader, "John") except: raise( AttributeError, "%s object has no attribute %s" \ % (leader, "set_name") ) Of course this wouldn't use the object names directly... I guess I'll need to look in the C object code to see exactly how it works. But the links you gave help. Thanks, Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: Content MathML implementation?
Stefan Behnel wrote: > Hi! > > I was looking for an implementation of a parser/model/serializer for Content > MathML in Python. Does anyone know about something useful? > > I need to work with math expressions (arithmetic/bool), especially converting > them between different representations (Python, SQL), determining dependencies > on variables etc. And since my output format is Content MathML anyway, I > wanted to ask if someone has implemented this before I start doing so. > > To make it clear: Presentation MathML does not help as it has a completely > different model that is not usable for my purpose. I've seen a Presentation MathML -> SVG renderer written in Python, but that's about it. I'd be very interested in seeing a Content MathML model (the parser and serializer parts can be any one of the various XML modules), so keep us informed! -- Robert Kern [EMAIL PROTECTED] "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: Most direct way to strip unoprintable characters out of a string?
Fredrik Lundh wrote: >("sanitizing" HTML data by running filters over encoded 8-bit data is hardly >ever the right thing to do...) > > > > I'm very much open to suggestions as to the right way to do this. I'm working on this primarily as a learning project and security is my motivation for wanting to strip the unprintables. Is there a better way? (This is a mod_python app , just for reference.) Thanks, Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: replacments for stdio?
Here's a suggestion for you: Check out the comp.lang.py thread titled "Catching stderr output from graphical apps" at > http://groups.google.com/group/comp.lang.python/browse_frm/thread/1d63e12e15ca528b/7bf604115b5e914e#7bf604115b5e914e I strongly suspect that the code discussed could probably be adapted to handle sys.stdout instead of, or in addition to, output to sys.stderr. It also sounds like it can be made platform independent. Best, -Martin P.S. Please post your results back to the newsgroup -- thanks! [EMAIL PROTECTED] wrote: > hi, >i was wondering if anyone have written a GUI module that can > function as a replacment for stdin/stdout? ie. has a file like > interface, by which one could just assaign it to sys.stdout or > sys.stdin and have all your prints and raw_inputs and other such things > shown in a GUI window? > > Thanks in advance, > Ido Yehieli. -- http://mail.python.org/mailman/listinfo/python-list
cElementTree clear semantics
Hi, I am trying to understand how cElementTree's clear works: I have a (relatively) large XML file, that I do not wish to load into memory. So, naturally, I tried something like this: from cElementTree import iterparse for event, elem in iterparse("data.xml"): if elem.tag == "schnappi": count += 1 elem.clear() ... which resulted in caching of all elements in memory except for those named (i.e. the process' memory footprint grew more and more). Then I though about clear()'ing all elements that I did not really need: from cElementTree import iterparse for event, elem in iterparse("data.xml"): if elem.tag == "schnappi": count += 1 elem.clear() ... which gave a suitably small memory footprint, *BUT* since has a number of subelements, and I subscribe to 'end'-events, the element is returned after all of its subelements have been read and clear()'ed. So, I see indeed a element, but calling its getiterator() gives me completely empty subelements, which is not what I wanted :( Finally, I thought about keeping track of when to clear and when not to by subscribing to start and end elements (so that I would collect the entire -subtree in memory and only than release it): from cElementTree import iterparse clear_flag = True for event, elem in iterparse("data.xml", ("start", "end")): if event == "start" and elem.tag == "schnappi": # start collecting elements clear_flag = False if event == "end" and elem.tag == "schnappi": clear_flag = True # do something with elem # unless we are collecting elements, clear() if clear_flag: elem.clear() This gave me the desired behaviour, but: * It looks *very* ugly * It's twice as slow as version which sees 'end'-events only. Now, there *has* to be a better way. What am I missing? Thanks in advance, ivr -- "...but it's HDTV -- it's got a better resolution than the real world." -- Fry, "When aliens attack" -- http://mail.python.org/mailman/listinfo/python-list
Re: cElementTree clear semantics
Igor V. Rafienko wrote: > This gave me the desired behaviour, but: > > * It looks *very* ugly > * It's twice as slow as version which sees 'end'-events only. > > Now, there *has* to be a better way. What am I missing? > Try emailing the author for support. -- http://mail.python.org/mailman/listinfo/python-list
Re: cElementTree clear semantics
D H wrote: > Igor V. Rafienko wrote: >> This gave me the desired behaviour, but: >> >> * It looks *very* ugly >> * It's twice as slow as version which sees 'end'-events only. >> >> Now, there *has* to be a better way. What am I missing? >> > > Try emailing the author for support. I don't think that's needed. He is one of the most active members of c.l.py, and you should know that yourself. Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: cElementTree clear semantics
Reinhold Birkenfeld wrote: > D H wrote: > >>Igor V. Rafienko wrote: >> >>>This gave me the desired behaviour, but: >>> >>>* It looks *very* ugly >>>* It's twice as slow as version which sees 'end'-events only. >>> >>>Now, there *has* to be a better way. What am I missing? >>> >> >>Try emailing the author for support. > > > I don't think that's needed. He is one of the most active members > of c.l.py, and you should know that yourself. > I would recommend emailing the author of a library when you have a question about that library. You should know that yourself as well. -- http://mail.python.org/mailman/listinfo/python-list
Re: cElementTree clear semantics
D H wrote: > Reinhold Birkenfeld wrote: >> D H wrote: >> >>>Igor V. Rafienko wrote: >>> This gave me the desired behaviour, but: * It looks *very* ugly * It's twice as slow as version which sees 'end'-events only. Now, there *has* to be a better way. What am I missing? >>> >>>Try emailing the author for support. >> >> >> I don't think that's needed. He is one of the most active members >> of c.l.py, and you should know that yourself. >> > > I would recommend emailing the author of a library when you have a > question about that library. You should know that yourself as well. Well, if I had e.g. a question about Boo, I would of course first ask here because I know the expert writes here. Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: cElementTree clear semantics
Reinhold Birkenfeld wrote: > > Well, if I had e.g. a question about Boo, I would of course first ask > here because I know the expert writes here. > > Reinhold Reinhold Birkenfeld also wrote: > If I had wanted to say "you have opinions? fuck off!", I would have said >"you have opinions? fuck off!". Take your own advice asshole. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamically adding and removing methods
On Sun, 25 Sep 2005 14:52:56 +, Ron Adam wrote: > Steven D'Aprano wrote: > > >> Or you could put the method in the class and have all instances recognise >> it: >> >> py> C.eggs = new.instancemethod(eggs, None, C) >> py> C().eggs(3) >> eggs * 3 > > Why not just add it to the class directly? You just have to be sure > it's a class and not an instance of a class. Because I started off explicitly adding functions to instances directly, and when I discovered that didn't work properly, I never even tried adding it to the class until after I discovered that instancemethod() worked. As far as I can see, Python's treatment of functions when you dynamically add them to classes and instances is rather confused. See, for example: py> class Klass: ... pass ... py> def eggs(self, x): ... print "eggs * %s" % x ... py> inst = Klass() # Create a class instance. py> inst.eggs = eggs # Dynamically add a function/method. py> inst.eggs(1) Traceback (most recent call last): File "", line 1, in ? TypeError: eggs() takes exactly 2 arguments (1 given) >From this, I can conclude that when you assign the function to the instance attribute, it gets modified to take two arguments instead of one. Test it by explicitly passing an instance: py> inst.eggs(inst, 1) eggs * 1 My hypothesis is confirmed. Can we get the unmodified function back again? py> neweggs = inst.eggs py> neweggs(1) Traceback (most recent call last): File "", line 1, in ? TypeError: eggs() takes exactly 2 arguments (1 given) Nope. That is a gotcha. Storing a function object as an attribute, then retrieving it, doesn't give you back the original object again. So while you can do this: def printgraph(f): # print a graph of a function parameters = get_params() draw_graph(f, parameters) you can't do this: def printgraph(function): # print a graph of a function parameters = get_params() parameters.function = f # WARNING: f is modified here draw_graph(parameters) When storing the function object as an instance object, it is half-converted to a method: even though eggs is modified to expect two arguments, Python doesn't know enough to automatically pass the instance object as the first argument like it does when you call a true instance method. Furthermore, the type of the attribute isn't changed: py> type(eggs) py> type(inst.eggs) But if you assign a class attribute to a function, the type changes, and Python knows to pass the instance object: py> Klass.eggs = eggs py> inst2 = Klass() py> type(inst2.eggs) py> inst2.eggs(1) eggs * 1 The different behaviour between adding a function to a class and an instance is an inconsistency. The class behaviour is useful, the instance behaviour is broken. > >>> def beacon(self, x): > ...print "beacon + %s" % x > ... Did you mean bacon? *wink* > >>> C.beacon = beacon > >>> dir(A) > ['__doc__', '__module__', 'beacon', 'ham', 'spam'] Okay, you aren't showing all your code. What is A? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Reinhold Birkenfeld [was "Re: cElementTree clear semantics"]
D H wrote: > Reinhold Birkenfeld wrote: > >> >> Well, if I had e.g. a question about Boo, I would of course first ask >> here because I know the expert writes here. >> >> Reinhold > > > Reinhold Birkenfeld also wrote: > > If I had wanted to say "you have opinions? fuck off!", I would have said > >"you have opinions? fuck off!". > > > Take your own advice asshole. -- http://mail.python.org/mailman/listinfo/python-list
Struggling with basics
A week ago I posted a simple little hi-score routine that I was using to learn Python. I've only just managed to examine the code, and the responses that people gave, and I'm now seriously struggling to understand why things aren't working correctly. At present my code is as follows... import random import bisect class HiScores: def __init__(self,hiScores): self.hiScores=[entry for entry in hiScores] def showScores(self): for score,name in self.hiScores: score=str(score).zfill(5) print "%s - %s" % name,score def addScore(self,score,name): score.zfill(5) bisect.insort(self.hiScores,(score,name)) if len(self.hiScores)==6: self.hiScores.pop() def lastScore(self): return self.hiScores[-1][0] def main(): hiScores=[('1','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('0','Epsilon')] a=HiScores(hiScores) print "Original Scores\n---" a.showScores() while 1: newScore=str(random.randint(0,1)) if newScore > a.lastScore(): print "Congratulations, you scored %s " % newScore name=raw_input("Please enter your name :") a.addScore(newScore,name) a.showScores() if __name__=="__main__": main() My first problem (lack of understanding of course) is that if I run the above, I get an error saying: print "%s - %s" % name,score TypeError: not enough arguments for format string Now I understand what it's saying, but I don't understand why. If I change the code to read: print "%s - %n" % name, score (thinking of course that ah-ha, score is numeric) then I get the same error. The only way for the program to run is to simply have print name,score (or print score,name) The final part that's simply not working correctly is that the entire program isn't sorting the data. If I run the program and get a score of, say, 6789, then when I add my name, nothing is entered. I have changed the clause that deletes (pops) the last array if the array count is 6 and seen what figures are being entered into the array. Sure enough they are going in the array, and they are being sorted, but they are only being sorted AFTER the 0 of the initial array creation. I'm pretty sure it's to do with comparing a string against an integer but can't for the life of me see where to force the comparrison to check against two integers. Apologies for going over old ground and if I'm not understanding, I'm getting there honest ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: cElementTree clear semantics
D H wrote: > Reinhold Birkenfeld wrote: > >> >> Well, if I had e.g. a question about Boo, I would of course first ask >> here because I know the expert writes here. >> >> Reinhold > > Reinhold Birkenfeld also wrote: > > If I had wanted to say "you have opinions? fuck off!", I would have said > >"you have opinions? fuck off!". > > > Take your own advice asshole. QED. Irony tags for sale. Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: "Re: cElementTree clear semantics"
D H wrote: > D H wrote: >> Reinhold Birkenfeld wrote: >> >>> >>> Well, if I had e.g. a question about Boo, I would of course first ask >>> here because I know the expert writes here. >>> >>> Reinhold >> >> >> Reinhold Birkenfeld also wrote: >> > If I had wanted to say "you have opinions? fuck off!", I would have said >> >"you have opinions? fuck off!". >> >> >> Take your own advice asshole. And what's that about? Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: Struggling with basics
Jason wrote: > A week ago I posted a simple little hi-score routine that I was using to > learn Python. > > I've only just managed to examine the code, and the responses that > people gave, and I'm now seriously struggling to understand why things > aren't working correctly. > > At present my code is as follows... > > import random > import bisect > > class HiScores: > def __init__(self,hiScores): > self.hiScores=[entry for entry in hiScores] > > def showScores(self): > for score,name in self.hiScores: > score=str(score).zfill(5) > print "%s - %s" % name,score > > > def addScore(self,score,name): > score.zfill(5) > bisect.insort(self.hiScores,(score,name)) > if len(self.hiScores)==6: > self.hiScores.pop() > > def lastScore(self): > return self.hiScores[-1][0] > > def main(): > > hiScores=[('1','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('0','Epsilon')] > > > a=HiScores(hiScores) > print "Original Scores\n---" > a.showScores() > > while 1: > newScore=str(random.randint(0,1)) > if newScore > a.lastScore(): > print "Congratulations, you scored %s " % newScore > name=raw_input("Please enter your name :") > a.addScore(newScore,name) > a.showScores() > > if __name__=="__main__": > main() > > > My first problem (lack of understanding of course) is that if I run the > above, I get an error saying: > > print "%s - %s" % name,score > TypeError: not enough arguments for format string > > Now I understand what it's saying, but I don't understand why. The '%' operator expects a tuple or a single value on its right. So you have to set parentheses around "name, score". That needs getting used to, but otherwise it can't be discerned from print ("%s - %s" % name), (score). > If I change the code to read: > > print "%s - %n" % name, score (thinking of course that ah-ha, score is > numeric) then I get the same error. For integers you can use %s or %i (or %d), see http://docs.python.org/lib/typesseq-strings.html. > Apologies for going over old ground and if I'm not understanding, I'm > getting there honest ;) No problem. c.l.py is newbie-friendly. Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess considered harmfull?
Hi also ! In other fields, I also found uses which did not function with subprocess, but OK with popen2/4 @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Struggling with basics
Jason wrote: > My first problem (lack of understanding of course) is that if I run the > above, I get an error saying: > > print "%s - %s" % name,score > TypeError: not enough arguments for format string > > Now I understand what it's saying, but I don't understand why. > The problem is precedence. print "%s - %s" % name,score is equivalent to: print ("%s - %s" % name),score not: print "%s - %s" % (name,score) The % operator binds more tightly than the comma, so you need to put parentheses around the argument to % (as in the last line above). -- http://mail.python.org/mailman/listinfo/python-list
Reinhold Birkenfeld [Re: "Re: cElementTree clear semantics"]
Reinhold Birkenfeld wrote: > D H wrote: > >>D H wrote: >> >>>Reinhold Birkenfeld wrote: >>> >>> Well, if I had e.g. a question about Boo, I would of course first ask here because I know the expert writes here. Reinhold >>> >>> >>>Reinhold Birkenfeld also wrote: >>> > If I had wanted to say "you have opinions? fuck off!", I would have said >>> >"you have opinions? fuck off!". >>> >>> >>>Take your own advice asshole. > > > And what's that about? I think it means you should fuck off, asshole. -- http://mail.python.org/mailman/listinfo/python-list
Re: "Re: cElementTree clear semantics"
D H wrote: > Reinhold Birkenfeld wrote: >> D H wrote: >> >>>D H wrote: >>> Reinhold Birkenfeld wrote: >Well, if I had e.g. a question about Boo, I would of course first ask >here because I know the expert writes here. > >Reinhold Reinhold Birkenfeld also wrote: > If I had wanted to say "you have opinions? fuck off!", I would have said >"you have opinions? fuck off!". Take your own advice asshole. >> >> >> And what's that about? > > I think it means you should fuck off, asshole. I think you've made that clear. *plonk* Reinhold PS: I really wonder why you get upset when someone except you mentions boo. -- http://mail.python.org/mailman/listinfo/python-list
Re: cElementTree clear semantics
Igor V. Rafienko wrote: > Finally, I thought about keeping track of when to clear and when not > to by subscribing to start and end elements (so that I would collect > the entire -subtree in memory and only than release it): > > from cElementTree import iterparse > clear_flag = True > for event, elem in iterparse("data.xml", ("start", "end")): > if event == "start" and elem.tag == "schnappi": > # start collecting elements > clear_flag = False > if event == "end" and elem.tag == "schnappi": > clear_flag = True > # do something with elem > # unless we are collecting elements, clear() > if clear_flag: > elem.clear() > > This gave me the desired behaviour, but: > > * It looks *very* ugly > * It's twice as slow as version which sees 'end'-events only. > > Now, there *has* to be a better way. What am I missing? the iterparse/clear approach works best if your XML file has a record-like structure. if you have toplevel records with lots of schnappi records in them, iterate over the records and use find (etc) to locate the subrecords you're interested in: for event, elem in iterparse("data.xml"): if event.tag == "record": # deal with schnappi subrecords for schappi in elem.findall(".//schnappi"): process(schnappi) elem.clear() the collect flag approach isn't that bad ("twice as slow" doesn't really say much: "raw" cElementTree is extremely fast compared to the Python interpreter, so everything you end up doing in Python will slow things down quite a bit). to make your application code look a bit less convoluted, put the logic in a generator function: # in library def process(filename, annoying_animal): clear = True start = "start"; end = "end" for event, elem in iterparse(filename, (start, end)): if elem.tag == annoying_animal: if event is start: clear = False else: yield elem clear = True if clear: elem.clear() # in application for subelem in process(filename, "schnappi"): # do something with subelem (I've reorganized the code a bit to cut down on the operations. also note the "is" trick; iterparse returns the event strings you pass in, so comparing on object identities is safe) an alternative is to use the lower-level XMLParser class (which is similar to SAX, but faster), but that will most likely result in more and tricker Python code... -- http://mail.python.org/mailman/listinfo/python-list
Reinhold Birkenfeld [Re: "Re: cElementTree clear semantics"]
Reinhold Birkenfeld wrote: > D H wrote: > >>Reinhold Birkenfeld wrote: >> >>>D H wrote: >>> >>> D H wrote: >Reinhold Birkenfeld wrote: > > > >>Well, if I had e.g. a question about Boo, I would of course first ask >>here because I know the expert writes here. >> >>Reinhold > > >Reinhold Birkenfeld also wrote: > >>If I had wanted to say "you have opinions? fuck off!", I would have said >>"you have opinions? fuck off!". > > >Take your own advice asshole. >>> >>> >>>And what's that about? >> >>I think it means you should fuck off, asshole. > > > I think you've made that clear. > > *plonk* > > Reinhold > > PS: I really wonder why you get upset when someone except you mentions boo. You're the only one making any association between this thread about celementree and boo. So again I'll say, take your own advice and fuck off. -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess considered harmfull?
Uri Nix wrote: > Using the following snippet: > p = > subprocess.Popen(nmake,stderr=subprocess.PIPE,stdout=subprocess.PIPE, \ >universal_newlines=True, bufsize=1) > os.sys.stdout.writelines(p.stdout) > os.sys.stdout.writelines(p.stderr) > Works fine on the command line, but fails when called from within > Visual Studio, with the following error: > File "C:\Python24\lib\subprocess.py", line 549, in __init__ > (p2cread, p2cwrite, > File "C:\Python24\lib\subprocess.py", line 609, in _get_handles > p2cread = self._make_inheritable(p2cread) > File "C:\Python24\lib\subprocess.py", line 650, in _make_inheritable > DUPLICATE_SAME_ACCESS) > TypeError: an integer is required This looks like these known bugs: http://python.org/sf/1124861 http://python.org/sf/1126208 Try setting stderr to subprocess.PIPE. I think that was what worked for me. (You might also try setting shell=True. That's what I currently have in my code that didn't work before.) STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Reinhold Birkenfeld [Re: "Re: cElementTree clear semantics"]
Doug Holton wrote: > You're the only one making any association between this thread about > celementree and boo. really? judging from the Original-From header in your posts, your internet provider is sure making the same association... -- http://mail.python.org/mailman/listinfo/python-list
Re: cElementTree clear semantics
[ Fredrik Lundh ] [ ... ] > the iterparse/clear approach works best if your XML file has a > record-like structure. if you have toplevel records with lots of > schnappi records in them, iterate over the records and use find > (etc) to locate the subrecords you're interested in: (...) The problem is that the file looks like this: green Lama white mother schnappi green human rabbit ... and there is really nothing above . The "something interesting" part consists of a variety of elements, and calling findall for each of them although possible, would probably be unpractical (say, distinguishing 's colors from ). Conceptually I need a "XML subtree iterator", rather than an XML element iterator. -elements are the ones having a complex internal structure, and I'd like to be able to speak of my XML as a sequence of Python objects representing s and their internal structure. [ ... ] > (I've reorganized the code a bit to cut down on the operations. also > note the "is" trick; iterparse returns the event strings you pass > in, so comparing on object identities is safe) Neat trick. Thank you for your input, ivr -- "...but it's HDTV -- it's got a better resolution than the real world." -- Fry, "When aliens attack" -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess considered harmfull?
Steven Bethard wrote: > > Using the following snippet: > > p = > > subprocess.Popen(nmake,stderr=subprocess.PIPE,stdout=subprocess.PIPE, \ > >universal_newlines=True, bufsize=1) > > os.sys.stdout.writelines(p.stdout) > > os.sys.stdout.writelines(p.stderr) > > Works fine on the command line, but fails when called from within > > Visual Studio, with the following error: > > File "C:\Python24\lib\subprocess.py", line 549, in __init__ > > (p2cread, p2cwrite, > > File "C:\Python24\lib\subprocess.py", line 609, in _get_handles > > p2cread = self._make_inheritable(p2cread) > > File "C:\Python24\lib\subprocess.py", line 650, in _make_inheritable > > DUPLICATE_SAME_ACCESS) > > TypeError: an integer is required > > This looks like these known bugs: > http://python.org/sf/1124861 > http://python.org/sf/1126208 > > Try setting stderr to subprocess.PIPE. I think that was what worked for > me. (You might also try setting shell=True. That's what I currently > have in my code that didn't work before.) if someone wants to investigate, is seeing this problem, and have the win32 extensions on their machine, try changing this line in subprocess.py: if 0: # <-- change this to use pywin32 instead of the _subprocess driver to: if 1: # <-- change this to use _subprocess instead of the pywin32 driver and see if it either fixes the problem (not very likely) or gives you a better error message (very likely). -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamically adding and removing methods
Steven D'Aprano wrote: > py> class Klass: > ... pass > ... > py> def eggs(self, x): > ... print "eggs * %s" % x > ... > py> inst = Klass() # Create a class instance. > py> inst.eggs = eggs # Dynamically add a function/method. > py> inst.eggs(1) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: eggs() takes exactly 2 arguments (1 given) > > From this, I can conclude that when you assign the function to the > instance attribute, it gets modified to take two arguments instead of one. No. Look at your eggs function. It takes two arguments. So the function is not modified at all. (Perhaps you expected it to be?) > Can we get the unmodified function back again? > > py> neweggs = inst.eggs > py> neweggs(1) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: eggs() takes exactly 2 arguments (1 given) > > Nope. That is a gotcha. Storing a function object as an attribute, then > retrieving it, doesn't give you back the original object again. Again, look at your eggs function. It takes two arguments. So you got exactly the same object back. Testing this: py> class Klass: ... pass ... py> def eggs(self, x): ... print "eggs * %s" % x ... py> inst = Klass() py> inst.eggs = eggs py> neweggs = inst.eggs py> eggs is neweggs True So you get back exactly what you previously assigned. Note that it's actually with *classes*, not *instances* that you don't get back what you set: py> Klass.eggs = eggs py> Klass.eggs py> Klass.eggs is eggs False > Furthermore, the type of the attribute isn't changed: > > py> type(eggs) > > py> type(inst.eggs) > > > But if you assign a class attribute to a function, the type changes, and > Python knows to pass the instance object: > > py> Klass.eggs = eggs > py> inst2 = Klass() > py> type(inst2.eggs) > > py> inst2.eggs(1) > eggs * 1 > > The different behaviour between adding a function to a class and an > instance is an inconsistency. The class behaviour is useful, the instance > behaviour is broken. With classes, the descriptor machinery is invoked: py> Klass.eggs py> Klass.eggs.__get__(None, Klass) py> Klass.eggs.__get__(Klass(), Klass) > Because instances do not invoke the descriptor machinery, you get a different result: py> inst.eggs However, you can manually invoke the descriptor machinery if that's what you really want: py> inst.eggs.__get__(None, Klass) py> inst.eggs.__get__(inst, Klass) > py> inst.eggs.__get__(inst, Klass)(1) eggs * 1 Yes, the behavior of functions that are attributes of classes is different from the behavior of functions that are attributes of instances. But I'm not sure I'd say that it's broken. It's a direct result of the fact that classes are the only things that implicitly invoke the descriptor machinery. Note that if instances invoked the descriptor machinery, setting a function as an attribute of an instance would mean you'd always get bound methods back. So code like the following would break: py> class C(object): ... pass ... py> def f(x): ... print 'f(%s)' % x ... py> def g(obj): ... obj.f('g') ... py> c = C() py> c.f = f py> g(c) f(g) If instances invoked the descriptor machinery, "obj.f" would return a bound method of the "c" instance, where "x" in the "f" function was bound to the "c" object. Thus the call to "obj.f" would result in: py> g(c) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in g TypeError: f() takes exactly 1 argument (2 given) Not that I'm claiming I write code like this. ;) But I'd be hesitant to call it broken. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Python Shell (IDLE) Lag
Hey everyone, just a quick general question about using the main python shell (I'm using IDLE on Windows to be exact). Whenever I print some really long output to the screen (> 3000 characters or so), my shell will start lagging very badly. I'm not sure if the shell keeps some memory dedicated to this already outputted data or what, but either way I can't seme to unlock these resources. Restarting just the shell doesn't help, so I end up having to closing IDLE completely and restarting it. Needless to say, this is a pain when I've got a lot of commands in the shell already I want to repeat because I lose them all. Anyone know of any way to free up these resources without restarting IDLE? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Fredrik Lundh [Re: Reinhold Birkenfeld [Re: "Re: cElementTree clear semantics"]]
Fredrik Lundh wrote: > Doug Holton wrote: > > >>You're the only one making any association between this thread about >>celementree and boo. > > > really? judging from the Original-From header in your posts, your internet > provider is sure making the same association... You seriously need some help. -- http://mail.python.org/mailman/listinfo/python-list
Re: cElementTree clear semantics
Igor V. Rafienko wrote: > The problem is that the file looks like this: > > ... lots of schnappi records ... okay. I think your first approach from cElementTree import iterparse for event, elem in iterparse("data.xml"): if elem.tag == "schnappi": count += 1 elem.clear() is the right one for this case. with this code, the clear call will destroy each schnappi record when you're done with it, so you will release all memory allocated for the schnappi elements. however, you will end up with a single toplevel element that contains a large number of empty subelements. this is usually no problem (it'll use a couple of megabytes), but you can get rid of the dead schnappis too, if you want to. see the example that starts with "context = iterparse" on this page http://effbot.org/zone/element-iterparse.htm for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: cElementTree clear semantics
Reinhold Birkenfeld wrote: > D H wrote: > > I would recommend emailing the author of a library when you have a > > question about that library. You should know that yourself as well. > > Well, if I had e.g. a question about Boo, I would of course first ask > here because I know the expert writes here. Regardless of anyone's alleged connection with Boo or newsgroup participation level, the advice to contact the package author/maintainer is sound. It happens every now and again that people post questions to comp.lang.python about fairly specific issues or packages that would be best sent to mailing lists or other resources devoted to such topics. It's far better to get a high quality opinion from a small group of people than a lower quality opinion from a larger group or a delayed response from the maintainer because he/she doesn't happen to be spending time sifting through flame wars amidst large volumes of relatively uninteresting/irrelevant messages. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Struggling with basics
Jason wrote: >A week ago I posted a simple little hi-score routine that I was using to >learn Python. > >I've only just managed to examine the code, and the responses that >people gave, and I'm now seriously struggling to understand why things >aren't working correctly. > >At present my code is as follows... > >import random >import bisect > >class HiScores: > def __init__(self,hiScores): > self.hiScores=[entry for entry in hiScores] > > def showScores(self): > for score,name in self.hiScores: > score=str(score).zfill(5) > print "%s - %s" % name,score > > > def addScore(self,score,name): > score.zfill(5) > bisect.insort(self.hiScores,(score,name)) > if len(self.hiScores)==6: > self.hiScores.pop() > > def lastScore(self): > return self.hiScores[-1][0] > >def main(): > >hiScores=[('1','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('0','Epsilon')] > > > a=HiScores(hiScores) > print "Original Scores\n---" > a.showScores() > > while 1: > newScore=str(random.randint(0,1)) > if newScore > a.lastScore(): > print "Congratulations, you scored %s " % newScore > name=raw_input("Please enter your name :") > a.addScore(newScore,name) > a.showScores() > >if __name__=="__main__": > main() > > >My first problem (lack of understanding of course) is that if I run the >above, I get an error saying: > > print "%s - %s" % name,score >TypeError: not enough arguments for format string > > >Now I understand what it's saying, but I don't understand why. > >If I change the code to read: > >print "%s - %n" % name, score (thinking of course that ah-ha, score is >numeric) then I get the same error. > >The only way for the program to run is to simply have > >print name,score (or print score,name) > > This is because 'print' is accepting 'score' as a seperate argument, not the formatting, as you want it to. Try 'print "%s - %s" % (name, score)' > >The final part that's simply not working correctly is that the entire >program isn't sorting the data. > >If I run the program and get a score of, say, 6789, then when I add my >name, nothing is entered. I have changed the clause that deletes (pops) >the last array if the array count is 6 and seen what figures are being >entered into the array. > >Sure enough they are going in the array, and they are being sorted, but >they are only being sorted AFTER the 0 of the initial array creation. > >I'm pretty sure it's to do with comparing a string against an integer >but can't for the life of me see where to force the comparrison to check >against two integers. > > > Humm. This is a harder problem. I will copy this text into JEdit to highlight the text and see if i cannot find the problem. >Apologies for going over old ground and if I'm not understanding, I'm >getting there honest ;) > > > HTH, Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: cElementTree clear semantics
Paul Boddie wrote: > Reinhold Birkenfeld wrote: >> D H wrote: >> > I would recommend emailing the author of a library when you have a >> > question about that library. You should know that yourself as well. >> >> Well, if I had e.g. a question about Boo, I would of course first ask >> here because I know the expert writes here. > > Regardless of anyone's alleged connection with Boo or newsgroup > participation level Which was sort of an ironic from my side. I did not expect "D H" to go overboard on this. > the advice to contact the package author/maintainer is sound. Correct. But if the post is already in the newsgroup and the author is known to write there extensively, it sounds ridiculous to say "contact the author". > It happens every now and again that people > post questions to comp.lang.python about fairly specific issues or > packages that would be best sent to mailing lists or other resources > devoted to such topics. It's far better to get a high quality opinion > from a small group of people than a lower quality opinion from a larger > group or a delayed response from the maintainer because he/she doesn't > happen to be spending time sifting through flame wars amidst large > volumes of relatively uninteresting/irrelevant messages. Hey, the flame war stopped before it got interesting ;) Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: cElementTree clear semantics
On 2005-09-25, D H <[EMAIL PROTECTED]> wrote: >>>Igor V. Rafienko wrote: >>> This gave me the desired behaviour, but: * It looks *very* ugly * It's twice as slow as version which sees 'end'-events only. Now, there *has* to be a better way. What am I missing? >>> >>>Try emailing the author for support. >> >> I don't think that's needed. He is one of the most active >> members of c.l.py, and you should know that yourself. > > I would recommend emailing the author of a library when you > have a question about that library. You should know that > yourself as well. Why?? For the things I "support", I much prefer answering questions in a public forum. That way the knowledge is available to everybody, and it reduces the number of e-mailed duplicate questions. Most of the gurus I know (not that I'm attempting to placing myself in that category) feel the same way. ESR explained it well. Quoting from http://www.catb.org/~esr/faqs/smart-questions.html#forum You are likely to be ignored, or written off as a loser, if you: [...] * post a personal email to somebody who is neither an acquaintance of yours nor personally responsible for solving your problem [...] In general, questions to a well-selected public forum are more likely to get useful answers than equivalent questions to a private one. There are multiple reasons for this. One is simply the size of the pool of potential respondents. Another is the size of the audience; hackers would rather answer questions that educate a lot of people than questions which only serve a few. -- Grant Edwards grante Yow! I'm a GENIUS! I at want to dispute sentence visi.comstructure with SUSAN SONTAG!! -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest setup
Diez B. Roggisch wrote: > paul kölle wrote: > >>hi all, >> >>I noticed that setUp() and tearDown() is run before and after *earch* >>test* method in my TestCase subclasses. I'd like to run them *once* for >>each TestCase subclass. How do I do that. > > > Create a global/test instance flag. I'm not sure if I understood what you mean, I tried: setup = 'down' class BaseTest(unittest.TestCase): def setUp(self): global setup if setup == 'up': print 'Not running setUp() again...' return ... all setup work goes here. ... setup = 'up' This didn't work, (tried to reset the flag in the last test* method to 'down', no dice) and: class BaseTest(unittest.TestCase): def __init__(self, ...): unittest.TestCase.__init__(self, ...) self.setup = 'down' def setUp(self): if self.setup == 'up': return dowork self.setup = 'up' Failed also, I'm not sure why, __init__ was called way too often and self.setup was always reset to 'down'. I finally gave up and created my own method which I call in *every* test* method which is ugly, leads to longer runtime and code duplication. But at least it encouraged me to read the unittest docs more carefully. Now I seem to understand that: TestSuite.addTest(TestCaseSubclass('testSomething')) TestSuite.addTest(TestCaseSubclass('testSomethingOther')) will create two instances of TestCaseSubclass, so there is no way that 'testSomethingOther' will ever see what 'testSomething' might have created if all work is done with instance data right? Initially I thought it goes like: "run setUp(), run all test* methods, run tearDown()" and that is what the unittest docs call a "fixture" A test fixture represents the preparation needed to perform one or more tests, and any associate cleanup actions. but further down: Each instance of the TestCase will only be used to run a single test method, so a new fixture is created for each test. It seems to me my case is not that exotic, I thought it would be quite natural to write the boilerplate stuff in setUp() and build on that to step through the applications state with test* methods each building on top of each other. Is that the wrong approach? Are there other frameworks supporting such a style? thanks Paul -- http://mail.python.org/mailman/listinfo/python-list
cannot write to file after close()
Hello Python-Gurus, == f = open(LOGFILE,'w') f.write(time + '\n') f.close command = 'ping -n 20' + target + '>>' + LOGFILE system(command) == produces an error saying that a file cannot be accessed because it is used by another process. I asume it is f which is used but don't understand why. Any ideas? Thanks a lot! Cheers, Rainer -- http://mail.python.org/mailman/listinfo/python-list
Re: cannot write to file after close()
Rainer Hubovsky wrote: > Hello Python-Gurus, > > == > f = open(LOGFILE,'w') > f.write(time + '\n') > f.close > > command = 'ping -n 20' + target + '>>' + LOGFILE > system(command) > == > > produces an error saying that a file cannot be accessed because it is used > by another process. I asume it is f which is used but don't understand why. > > Any ideas? Is the above exactly your code? If yes, it should be f.close() The parentheses are necessary to make the statement a function call. Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: cElementTree clear semantics
Paul Boddie wrote: > Regardless of anyone's alleged connection with Boo or newsgroup > participation level, the advice to contact the package > author/maintainer is sound. It happens every now and again that people > post questions to comp.lang.python about fairly specific issues or > packages that would be best sent to mailing lists or other resources > devoted to such topics. It's far better to get a high quality opinion > from a small group of people than a lower quality opinion from a larger > group or a delayed response from the maintainer because he/she doesn't > happen to be spending time sifting through flame wars amidst large > volumes of relatively uninteresting/irrelevant messages. well, for the record, I strongly recommend people to post questions in public forums. google is far more likely to pick up answers from mailing list archives and newsgroups than from the "I really should do something about all the mails in my support folder" part of my brain. it's often a good idea to spend a little time looking for the right forum (the xml-sig is a good place for elementtree-related questions), but posting a question about a widely used Python library to c.l.python is never wrong. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Shell (IDLE) Lag
Just a little addendum... this lag only happens when the output is a very long continuous string. If I print out 3000 or so LINES of output there's no problem, its only when it's one long continuous string. -- http://mail.python.org/mailman/listinfo/python-list
Re: Struggling with basics
Peter wrote: >Jason wrote: > > > >>A week ago I posted a simple little hi-score routine that I was using to >>learn Python. >> >>I've only just managed to examine the code, and the responses that >>people gave, and I'm now seriously struggling to understand why things >>aren't working correctly. >> >>At present my code is as follows... >> >>import random >>import bisect >> >>class HiScores: >>def __init__(self,hiScores): >>self.hiScores=[entry for entry in hiScores] >> >>def showScores(self): >>for score,name in self.hiScores: >>score=str(score).zfill(5) >>print "%s - %s" % name,score >> >> >>def addScore(self,score,name): >>score.zfill(5) >>bisect.insort(self.hiScores,(score,name)) >>if len(self.hiScores)==6: >>self.hiScores.pop() >> >>def lastScore(self): >>return self.hiScores[-1][0] >> >>def main(): >> >>hiScores=[('1','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('0','Epsilon')] >> >> >>a=HiScores(hiScores) >>print "Original Scores\n---" >>a.showScores() >> >>while 1: >>newScore=str(random.randint(0,1)) >>if newScore > a.lastScore(): >>print "Congratulations, you scored %s " % newScore >>name=raw_input("Please enter your name :") >>a.addScore(newScore,name) >>a.showScores() >> >>if __name__=="__main__": >>main() >> >> >>My first problem (lack of understanding of course) is that if I run the >>above, I get an error saying: >> >>print "%s - %s" % name,score >>TypeError: not enough arguments for format string >> >> >>Now I understand what it's saying, but I don't understand why. >> >>If I change the code to read: >> >>print "%s - %n" % name, score (thinking of course that ah-ha, score is >>numeric) then I get the same error. >> >>The only way for the program to run is to simply have >> >>print name,score (or print score,name) >> >> >> >> >This is because 'print' is accepting 'score' as a seperate argument, not >the formatting, as you want it to. >Try 'print "%s - %s" % (name, score)' > > > > >>The final part that's simply not working correctly is that the entire >>program isn't sorting the data. >> >>If I run the program and get a score of, say, 6789, then when I add my >>name, nothing is entered. I have changed the clause that deletes (pops) >>the last array if the array count is 6 and seen what figures are being >>entered into the array. >> >>Sure enough they are going in the array, and they are being sorted, but >>they are only being sorted AFTER the 0 of the initial array creation. >> >>I'm pretty sure it's to do with comparing a string against an integer >>but can't for the life of me see where to force the comparrison to check >>against two integers. >> >> >> >> >> >Humm. This is a harder problem. I will copy this text into JEdit to >highlight the text and see if i cannot find the problem. > > > Correction: I will fix my apearently semi-broaken Python installation wich gives me undefined reference errors from math.h and then see if i cannot fix the problem. -.- >>Apologies for going over old ground and if I'm not understanding, I'm >>getting there honest ;) >> >> >> >> >> > >HTH, >Peter > > > Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing class variable at class creation time
Thank you all! After all, I found at least three more or less convenient alternatives: 1) Pass X as default parameter to F. 2) Set globals() from inside A, something like globals()['A_locals'] = locals() or globals()['A_X'] = X. Then access A_locals or A_X from F. 3) Use sys._getframe(1) or sys._getframe().f_back to get the caller frame. But the following won't work: > self.__class__.X Because there is no self around here, I'm not trying to access X from a class instance but instead from code running at class definition time. > class A: > ... X = 2 > ... print X Of course this will print X but the point was to do it from inside a function. Regards, Carlos -- http://mail.python.org/mailman/listinfo/python-list
Re: [RFC] Parametric Polymorphism
On Sun, 25 Sep 2005, Catalin Marinas wrote: > Sorry if this was previously discussed but it's something I miss in > Python. I get around this using isinstance() but it would be cleaner to > have separate functions with the same name but different argument types. > I think the idea gets quite close to the Lisp/CLOS implementation of > methods. > > Below is just simple implementation example (and class functions are > not supported) but it can be further extended/optimised/modified for > better type detection like issubclass() etc. The idea is similar to > the @accepts decorator: > > methods = dict() > > def method(*types): >def build_method(f): >assert len(types) == f.func_code.co_argcount > >if not f.func_name in methods: >methods[f.func_name] = dict() >methods[f.func_name][str(types)] = f > >def new_f(*args, **kwds): >type_str = str(tuple([type(arg) for arg in args])) >assert type_str in methods[f.func_name] >return methods[f.func_name][type_str](*args, **kwds) >new_f.func_name = f.func_name > >return new_f > >return build_method Neat. I'd come up with the same general idea myself, but since i am a worthless slob, i never actually implemented it. Is there any reason you have to stringify the type signature? Types are hashable, so a tuple of types is hashable, so you can just use that as a key. Replace "methods[f.func_name][str(types)] = f" with "methods[f.func_name][types] = f" and "type_str = str(tuple([type(arg) for arg in args]))" with "type_str = tuple(type(arg) for arg in args)". And then rename type_str to types thoughout. Also, we can exploit the closureness of new_f to avoid a dict lookup: f_implementations = methods[f.func_name] def new_f(*args, **kwds): types = tuple(type(arg) for arg in args) return f_implementations[types](*args, **kwds) tom -- double mashed, future mashed, millennium mashed; man it was mashed -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: add sys to __builtins__
I'm into *real* purity. I would rather begin every script: from python import list, str, dict, sys, os Oh wait. I only use dict in less than 50% of my scripts: from python import list, str, sys, os That's better. On Saturday 03 September 2005 02:09, tiissa wrote: > I was just stating your proposal didn't really solve anything. A good > editor/template and .pythonrc already save you the typing of 'import > sys' in scripts for the former and shell command for the latter. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Struggling with basics
Rather than reply to those individuals, just a big "thanks" to those that have helped. It's definitely making sense, the fact that I need to show the two-element tuple to show correctly was one of those head-slapping moments. And Dennis Lee Bieber hit the nail on the head when he mentioned that I'd declared the initial scores as strings, yet I was comparing them against integers. I simply removed the single-quotes from the scores and everything slotted into place. Again, I now have the list working, apart from the list is reversed (as per Dennis Lee Bieber mentioned). I'm afraid I don't understand what you mean about the DIFF report but I'll investigate further and learn a bit more. Again, thanks for the assistance. -- http://mail.python.org/mailman/listinfo/python-list
Re: Struggling with basics
Duncan Booth wrote: >Jason wrote: > > > >>My first problem (lack of understanding of course) is that if I run the >>above, I get an error saying: >> >> print "%s - %s" % name,score >>TypeError: not enough arguments for format string >> >>Now I understand what it's saying, but I don't understand why. >> >> >> > >The problem is precedence. > > print "%s - %s" % name,score > >is equivalent to: > > print ("%s - %s" % name),score > >not: > > print "%s - %s" % (name,score) > >The % operator binds more tightly than the comma, so you need to put >parentheses around the argument to % (as in the last line above). > > Well said. :) - Peter -- http://mail.python.org/mailman/listinfo/python-list
Best practices for dynamically loading plugins at startup
Dear coders... I'm working on an application that is supposed to support "plugins". The idea is to use the plugins as packages like this: Plugins/ __init__.py Plugin1.py Plugin2.py Plugin3.py When the application starts up I want to have these modules loaded dynamically. Users can put their own plugin modules into the Plugins/ directory and the application should know about it. Since I don't know which plugins have been put into that directory I cannot just "import Plugin1, Plugin2, Plugin3" in the "__init__.py". So I need to find out the *.py there and load them during startup. I could do that with a "walk" over that directory. Each plugin is supposed to be a class derived from a general "Plugin" superclass. I just don't know how to 'register' every plugin. The main application needs to know which plugin classes there are. On IRC I was recommended walking through all objects and finding out if the class is a subclass of "Plugin". Another person recommended using metaclasses to automatically register the plugin in a global list. Since I have only little real-life Python knowledge I wonder what the best practice for this kind of problem is. I looked at the "supybot" IRC bot to get an idea how plugins are handled there. Unfortunately it was still a bit over my (python) head. Regards Christoph -- ~ ~ ~ ".signature" [Modified] 3 lines --100%--3,41 All -- http://mail.python.org/mailman/listinfo/python-list
Re: Struggling with basics
Jason wrote: > Rather than reply to those individuals, just a big "thanks" to those > that have helped. > > It's definitely making sense, the fact that I need to show the > two-element tuple to show correctly was one of those head-slapping moments. > > And Dennis Lee Bieber hit the nail on the head when he mentioned that > I'd declared the initial scores as strings, yet I was comparing them > against integers. I simply removed the single-quotes from the scores > and everything slotted into place. > > Again, I now have the list working, apart from the list is reversed (as > per Dennis Lee Bieber mentioned). I'm afraid I don't understand what > you mean about the DIFF report but I'll investigate further and learn a > bit more. Please bear in mind: If you just remove the quotes from '00050', you will get a value of 40. This is because integer literals with leading zeroes are inter- preted as octal. Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: py2exe and OpenGL problem
Line 13:17 of OpenGL.__init__.py, replace with: try: filename = os.path.join(os.path.dirname(__file__), 'version') __version__ = string.strip(open(filename).read()) except Exception, err: __version__ = '2.0.2.02' HTH, Mike [EMAIL PROTECTED] wrote: >I am using the new py2exe and python 24. When I run my setup.py, the >dist seems to generate just fine. However run I run the resulting exe, >I get an error: > >IOError: [Errno 2] No such file or directory >'c:\\app\\dist\\library.zip\\OpenGL\\version' > >Now I've tried the recommended route with older py2exes, where I >exclude OpenGL and copy the entire directory over to my dist, but that >didn't work. I included "version" into the "OpenGL" directory via my >setup.py script, and it is there right in the library.zip, but I still >get the same error. > >Anyone have any ideas or suggections? > > -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Best practices for dynamically loading plugins at startup
Christoph Haas napisał(a): > Since I don't know which plugins have been put into that directory > I cannot just "import Plugin1, Plugin2, Plugin3" in the "__init__.py". > So I need to find out the *.py there and load them during startup. > I could do that with a "walk" over that directory. See entry for __import__ at http://www.python.org/doc/2.3/lib/built-in-funcs.html -- Jarek Zgoda http://jpa.berlios.de/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Struggling with basics
Reinhold Birkenfeld wrote: > Jason wrote: >> Rather than reply to those individuals, just a big "thanks" to those >> that have helped. >> >> It's definitely making sense, the fact that I need to show the >> two-element tuple to show correctly was one of those head-slapping moments. >> >> And Dennis Lee Bieber hit the nail on the head when he mentioned that >> I'd declared the initial scores as strings, yet I was comparing them >> against integers. I simply removed the single-quotes from the scores >> and everything slotted into place. >> >> Again, I now have the list working, apart from the list is reversed (as >> per Dennis Lee Bieber mentioned). I'm afraid I don't understand what >> you mean about the DIFF report but I'll investigate further and learn a >> bit more. > > Please bear in mind: If you just remove the quotes from '00050', you will get > a value of 40. This is because integer literals with leading zeroes are inter- > preted as octal. > > Reinhold Doh! Just found that out! lol. OK I'm going to read a bit more in the manual now; I'm determined to crack this nut by the morning. -- http://mail.python.org/mailman/listinfo/python-list
Re: Struggling with basics
Peter wrote: > Peter wrote: > >> Jason wrote: >> >> >> >>> A week ago I posted a simple little hi-score routine that I was >>> using to learn Python. >>> >>> I've only just managed to examine the code, and the responses that >>> people gave, and I'm now seriously struggling to understand why >>> things aren't working correctly. >>> >>> At present my code is as follows... >>> >>> import random >>> import bisect >>> >>> class HiScores: >>>def __init__(self,hiScores): >>>self.hiScores=[entry for entry in hiScores] >>> >>>def showScores(self): >>>for score,name in self.hiScores: >>>score=str(score).zfill(5) >>>print "%s - %s" % name,score >>> >>> >>>def addScore(self,score,name): >>>score.zfill(5) >>>bisect.insort(self.hiScores,(score,name)) >>>if len(self.hiScores)==6: >>>self.hiScores.pop() >>> >>>def lastScore(self): >>>return self.hiScores[-1][0] >>> >>> def main(): >>> >>> hiScores=[('1','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('0','Epsilon')] >>> >>> >>>a=HiScores(hiScores) >>>print "Original Scores\n---" >>>a.showScores() >>> >>>while 1: >>>newScore=str(random.randint(0,1)) >>>if newScore > a.lastScore(): >>>print "Congratulations, you scored %s " % newScore >>>name=raw_input("Please enter your name :") >>>a.addScore(newScore,name) >>>a.showScores() >>> >>> if __name__=="__main__": >>>main() >>> >>> >>> My first problem (lack of understanding of course) is that if I run >>> the above, I get an error saying: >>> >>>print "%s - %s" % name,score >>> TypeError: not enough arguments for format string >>> >>> >>> Now I understand what it's saying, but I don't understand why. >>> >>> If I change the code to read: >>> >>> print "%s - %n" % name, score (thinking of course that ah-ha, score >>> is numeric) then I get the same error. >>> >>> The only way for the program to run is to simply have >>> >>> print name,score (or print score,name) >>> >>> >>> >> >> This is because 'print' is accepting 'score' as a seperate argument, >> not the formatting, as you want it to. >> Try 'print "%s - %s" % (name, score)' >> >> >> >> >>> The final part that's simply not working correctly is that the >>> entire program isn't sorting the data. >>> >>> If I run the program and get a score of, say, 6789, then when I add >>> my name, nothing is entered. I have changed the clause that deletes >>> (pops) the last array if the array count is 6 and seen what figures >>> are being entered into the array. >>> >>> Sure enough they are going in the array, and they are being sorted, >>> but they are only being sorted AFTER the 0 of the initial array >>> creation. >>> >>> I'm pretty sure it's to do with comparing a string against an >>> integer but can't for the life of me see where to force the >>> comparrison to check against two integers. >>> >>> >>> >>> >> >> Humm. This is a harder problem. I will copy this text into JEdit to >> highlight the text and see if i cannot find the problem. >> >> >> > Correction: I will fix my apearently semi-broaken Python installation > wich gives me undefined reference errors from math.h and then see if i > cannot fix the problem. -.- > Well, My Python2.4 may have a broken math module, but my Python2.3 only has a broken cPickle. *Kicks computer*. Try changing pop() to pop(0) and it should work. string.pop by default removes the last element appended to the list, you want the first, which is the oldest. >>> Apologies for going over old ground and if I'm not understanding, >>> I'm getting there honest ;) >>> >>> >>> >>> >> >> >> HTH, >> Peter >> >> >> > Peter > > > HTH, Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Struggling with basics
On Sun, 25 Sep 2005, Jason wrote: > A week ago I posted a simple little hi-score routine that I was using to > learn Python. > > I've only just managed to examine the code, and the responses that people > gave, and I'm now seriously struggling to understand why things aren't > working correctly. Others have dealt with the string printing problem, so i'll leave that. The problem with the sorting is that you're not consistent about how scores are represented - are they strings or integers? At present, you sometimes use one and sometimes the other, with the result that the sort basically pukes all over you. To fix this, pick one type (hint: integers), and use that consistently. I'll show you how to do that below (although it's not exactly hard). Oh, and i'm a picky git, so i'm going to point out some other flaws in the code! > At present my code is as follows... > > import random > import bisect > > class HiScores: >def __init__(self,hiScores): >self.hiScores=[entry for entry in hiScores] One bug and one wart here. The wart is the way you initialise self.hiScores - you use a list comprehension when you can just call the list builtin: self.hiScores = list(hiScores) The bug is that you don't sort the list. If you're certain that the initial set of high scores will always come sorted, that's okay, but i'd say it was good practice to sort them, just in case. In fact, i'd punt the addition to addScore: def __init__(self, hiScores): self.hiScores = [] for score, name in hiScores: self.addScore(score, name) This is the 'Once And Only Once' principle in action; the knowledge about how to keep the list sorted is expressed once and only once, in addScore; if any other parts of the code need to add items, they call that. This means there's only one piece of code you have to check to make sure it's going to get this right. >def showScores(self): >for score,name in self.hiScores: >score=str(score).zfill(5) >print "%s - %s" % name,score As has been pointed out, you need to wrap parens round "name, score" to make it into a tuple. Apart from that, i'd skip the string interpolation and just write: for score, name in self.hiScores: print name, "-", str(score).zfill(5) If you insist on the string interpolation, i'd still elide the intermediate variable and write: for score, name in self.hiScores: print "%s - %05i" % (name, score) The %05i in the format string means 'an integer, zero-filled to five digits'. Good, eh? >def addScore(self,score,name): >score.zfill(5) >bisect.insort(self.hiScores,(score,name)) >if len(self.hiScores)==6: >self.hiScores.pop() Two problems there. Well, two and a half. Firstly, the type confusion - are scores strings or integers? the zfill indicates that you're thinking in terms of strings here. You should be using integers, so you can just drop that line. And if you were working with strings, the zfill would still be wrong (this is the half problem!) - zfill doesn't affect the string it's called on (strings are immutable), it makes a new zero-filled string and returns it. You're not doing anything with the return value of that call, so the zero-filled string would just evaporate into thin air. Secondly, bisect.insort sorts the list so that the highest scores are at the tail end of the list; list.pop takes things off that same end, so you're popping the highest scores, not the lowest! You need to say pop(0) to specify that the item should be popped off the head (ie the low end) of the list. Also, i'd be tempted to program defensively and change the test guarding the pop to "while (len(self.hiScores > 6):". All in all, that makes my version: def addScore(self, score, name): bisect.insort(self.hiScores, (int(score), name)) while(len(self.hiScores) > 6): self.hiScores.pop(0) >def lastScore(self): >return self.hiScores[-1][0] This will return the top score; you want self.hiScores[0][0]. > def main(): > > > hiScores=[('1','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('0','Epsilon')] Here you've got scores as strings, and this is the root of the problem. Change this to: hiScores=[(1,'Alpha'),(7500,'Beta'),(5000,'Gamma'),(2500,'Delta'),(0,'Epsilon')] Note that i've taken the leading zeroes off - leading zeroes on integers in python are a magic signal that the number is octal (yes, base eight!), which is not what you want at all. >a=HiScores(hiScores) >print "Original Scores\n---" >a.showScores() > >while 1: "while True:" is preferred here. >newScore=str(random.randint(0,1)) Take out the str(). >if newScore > a.lastScore(): >print "Congratulations, you scored %s " % newScore Make that a %i (or a %05i). >name=raw_input("Please enter your name :") >
Re: cElementTree clear semantics
Grant Edwards wrote: > On 2005-09-25, D H <[EMAIL PROTECTED]> wrote: > Igor V. Rafienko wrote: >This gave me the desired behaviour, but: > >* It looks *very* ugly >* It's twice as slow as version which sees 'end'-events only. > >Now, there *has* to be a better way. What am I missing? Try emailing the author for support. >>> >>>I don't think that's needed. He is one of the most active >>>members of c.l.py, and you should know that yourself. >> >>I would recommend emailing the author of a library when you >>have a question about that library. You should know that >>yourself as well. > > > Why?? Please tell me I don't have to explain to you why the author of a 3rd party library might be able to answer a question specific to that library. > For the things I "support", I much prefer answering questions > in a public forum. Right, which is exactly why we have sourceforge, tigris, google groups, and numerous other free resources where you can set up a mailing list to publicly ask and answer questions about your software. Of course it may not get you as many paypal hits as spamming larger forums with your support questions will, but it is the decent thing to do. -- http://mail.python.org/mailman/listinfo/python-list
Re: cElementTree clear semantics
Fredrik Lundh wrote: > Paul Boddie wrote: > > >>Regardless of anyone's alleged connection with Boo or newsgroup >>participation level, the advice to contact the package >>author/maintainer is sound. It happens every now and again that people >>post questions to comp.lang.python about fairly specific issues or >>packages that would be best sent to mailing lists or other resources >>devoted to such topics. It's far better to get a high quality opinion >>from a small group of people than a lower quality opinion from a larger >>group or a delayed response from the maintainer because he/she doesn't >>happen to be spending time sifting through flame wars amidst large >>volumes of relatively uninteresting/irrelevant messages. > > > well, for the record, I strongly recommend people to post questions in > public forums. google is far more likely to pick up answers from mailing > list archives and newsgroups than from the "I really should do something > about all the mails in my support folder" part of my brain. You run your own server and get plenty of paypal donations. Why not run your own mailing list for support? If not, see sourceforge or google groups: http://groups.google.com/groups/create?lnk=l&hl=en -- http://mail.python.org/mailman/listinfo/python-list
Re: cElementTree clear semantics
On 2005-09-25, D H <[EMAIL PROTECTED]> wrote: >>>I would recommend emailing the author of a library when you >>>have a question about that library. You should know that >>>yourself as well. >> >> Why?? > > Please tell me I don't have to explain to you why the author > of a 3rd party library might be able to answer a question > specific to that library. Of course not. And when that author reads this group, why not post questions here so that everybody can benefit from the information? >> For the things I "support", I much prefer answering questions >> in a public forum. > > Right, which is exactly why we have sourceforge, tigris, > google groups, Exactly how do you think c.l.p on google groups differs from c.l.p on the rest of Usenet? > and numerous other free resources where you can set up a > mailing list to publicly ask and answer questions about your > software. Of course it may not get you as many paypal hits as > spamming larger forums with your support questions will, WTF are you on about? What the hell is a "Paypal hit"? How is posting a single, on-topic, question to c.l.p "spamming"? > but it is the decent thing to do. You sir, are a loon. -- Grant Edwards grante Yow! Where do your SOCKS at go when you lose them in visi.comth' WASHER? -- http://mail.python.org/mailman/listinfo/python-list
Find out if host is alive
What is the fastest way to find out a host is alive should i make a sys call and ping or is thier an easier way -- http://mail.python.org/mailman/listinfo/python-list
Re: Struggling with basics
Tom, best explanation yet! Entertaining as well as educational. The "%05i" trick is very neat, must remember that one! Everything working a charm apart from the viewScores is still returning the results from the lowest score (at the top) to the highest score. What I'd like to know is do you think it would be better to sort the list in memory, or print it out sorted? If the latter, then naturally I'd need to change the showScores section to show the list in a reverse order. But, would sorting the list in memory be more effective? -- http://mail.python.org/mailman/listinfo/python-list
Re: Find out if host is alive
Eyual> What is the fastest way to find out a host is alive should i make Eyual> a sys call and ping or is thier an easier way What is the fastest Eyual> way to find out a host is alive should i make a sys call and ping Eyual> or is thier an easier way Depends on the meaning of "host is alive". If that means "up and available to do something for me", try connecting to the port of interest using the socket module. -- Skip Montanaro Katrina Benefit Concerts: http://www.musi-cal.com/katrina [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: cElementTree clear semantics
Paul Boddie: > Regardless of anyone's alleged connection with Boo or newsgroup > participation level, the advice to contact the package > author/maintainer is sound. It happens every now and again that people > post questions to comp.lang.python about fairly specific issues or > packages that would be best sent to mailing lists or other resources > devoted to such topics. It's far better to get a high quality opinion > from a small group of people than a lower quality opinion from a larger > group or a delayed response from the maintainer because he/she doesn't > happen to be spending time sifting through flame wars amidst large > volumes of relatively uninteresting/irrelevant messages. As the author of a widely used component (Scintilla) I feel public fora should be preferred over private mail since * The effort in answering is spread over more people. * The author will only have experience in a narrow range of usage and the query is likely to match some other user's experience. * The author may be out of touch or busy. * The author will make mistakes which can be picked up by other participants. I'd estimate that 10% of the answers I give are wrong or useless, sometimes due to misunderstanding the query and sometimes due to confusion over how the component works. * Public fora are archived and searchable. Neil -- http://mail.python.org/mailman/listinfo/python-list
Grant Edwards [Re: cElementTree clear semantics]
Grant Edwards wrote: > On 2005-09-25, D H <[EMAIL PROTECTED]> wrote: > > I would recommend emailing the author of a library when you have a question about that library. You should know that yourself as well. >>> >>>Why?? >> >>Please tell me I don't have to explain to you why the author >>of a 3rd party library might be able to answer a question >>specific to that library. > > > Of course not. And when that author reads this group, why not > post questions here so that everybody can benefit from the > information? When did I ever argue against that? I was suggesting a resource to use to support your own software. I think you have assumed that I suggested posting here about celementree was off-topic. Tell me where I ever said that. I said to the first guy that he should ask the author for help, meaning that he could get help that way as well. Furthermore, I believe that is the more efficient way to get help, by contacting the author directly, especially if that author is too lazy to set up their own support forum or list. >>>For the things I "support", I much prefer answering questions >>>in a public forum. >> >>Right, which is exactly why we have sourceforge, tigris, >>google groups, > > > Exactly how do you think c.l.p on google groups differs from > c.l.p on the rest of Usenet? Who the fuck said that? Are you pulling this shit out of your ass? >>and numerous other free resources where you can set up a >>mailing list to publicly ask and answer questions about your >>software. Of course it may not get you as many paypal hits as >>spamming larger forums with your support questions will, > > > WTF are you on about? What the hell is a "Paypal hit"? How is > posting a single, on-topic, question to c.l.p "spamming"? Fredrik Lundh gets money via paypal on his site where his software is located. That's what I meant. Where did I say this particular post is a spam? Again, your ass? where do you get this shit? > >>but it is the decent thing to do. > > > You sir, are a loon. > You're a funny ass. -- http://mail.python.org/mailman/listinfo/python-list
Struggling with this concept please help
Hello everyone I know many have helped but I cannot get this to work out correctly. I cannot use BeautifulSoup at all. I need to: Parse the HTML and extracting all the links, convert them to IP addresses, and build a list of all these IP addresses, thwn I need to sort the list and remove the duplicates so that unit testing will work. Please help I have never done python before and I can't seem to get the hang of it. """ Module to print IP addresses of tags in web file containing HTML >>> showIPnums('http://22c118.cs.uiowa.edu/uploads/easy.html') ['0.0.0.0', '128.255.44.134', '128.255.45.54'] >>> showIPnums('http://22c118.cs.uiowa.edu/uploads/pytorg.html') ['0.0.0.0', '128.255.135.49', '128.255.244.57', '128.255.30.11', '128.255.34.132', '128.255.44.51', '128.255.45.53', '128.255.45.54', '129.255.241.42', '64.202.167.129'] """ import htmllib import formatter import urllib import socket from urlparse import urlparse class HTML_Parser(htmllib.HTMLParser): def __init__(self): htmllib.HTMLParser.__init__(self, formatter.AbstractFormatter(formatter.NullWriter())) def start_a(self, args): for key, value in args: if key.lower() == 'href': global listURL def showIPnums(URL): parser = HTML_Parser() connect = urllib.urlopen(URL) data = connect.read() parser.feed(data) parser.close() connect.close() if __name__ == '__main__': import doctest, sys doctest.testmod(sys.modules[__name__]) -- http://mail.python.org/mailman/listinfo/python-list
Carrying variables over from function to function
Alright heres my problem. . .Say I want to carry over a variable from one function to another or even another run of the same function. Is that possible? Heres a quick example of what I'm talking about. def abc(): x = 1 y = x + 1 print y def abcd(): y = x + 1 print y abc() abcd() the output would be: abc() 2 abcd() Traceback (most recent call last): File "(stdin)", line 1, in ? File "(stdin)", line 2, in abcd NameError: global name 'x' is not defined See, I want y in the second function to equal 4, carrying the x from the first function over to the next. Is there any way to do this? -Ivan _ Dont just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Carrying variables over from function to function
"Ivan Shevanski" <[EMAIL PROTECTED]> wrote: > Alright heres my problem. . .Say I want to carry over a variable from one > function to another or even another run of the same function. Is that > possible? You want one of two things. The most obvious would be a global variable. Something like this: def abc(): global x x = 1 y = x + 1 print y def abcd(): global x y = x + 1 print y This works, and is sometimes even the right thing to do, but in general, good software design looks for ways to decouple functions from each other and generally frowns on the use of global variables. More likely, what you really want to do is declare a class, and have your shared variable be an instance variable. Your two functions abc() and abcd() would then be methods of that class. -- http://mail.python.org/mailman/listinfo/python-list
Re: Alternatives to Stackless Python?
Honestly I am not knowledgeable about either option but mainly I was specifically targetting my feature set towards the things that a higher level game engine would need such as the one described here: http://harkal.sylphis3d.com/2005/08/10/multithreaded-game-scripting-with-stackless-python/ Which I guess the main difference that I see between stackless and NanoThreads is the ability to communicate between threads through channels and other methods. This is very important in games where the actors need to communicate among each other to create interactive and interesting gameplay. And perhaps scheduling overhead, memory costs and slow thread creation could be otherh areas where the two differ (but I am unsure). And finally, how good is NanoThreads at non-preemptive multithreading and event-driven control? These are more areas that I see the two possibly differing. Also, Greenlets look really interesting, I will have to evaluate these more closely. -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest setup
"paul kölle" <[EMAIL PROTECTED]> wrote: > > [snipped] > > It seems to me my case is not that exotic, I thought it would be quite > natural to write the boilerplate stuff in setUp() and build on that to > step through the applications state with test* methods each building on > top of each other. Is that the wrong approach? Are there other > frameworks supporting such a style? Yes, py.test: http://codespeak.net/py/current/doc/test.html. George -- http://mail.python.org/mailman/listinfo/python-list
Let's enjoy this list! [Re: "Re: cElementTree clear semantics"]
[D H] > I think it means you should fuck off, asshole. Such language looks very inappropriate to me in a public list, and builds a bad and long-lasting prejudice against those resorting to it. Flamers should rather, for their own image, email each other privately on their matters (yet D.H. is not providing his/her email address in the last messages I've seen). Flamers being in the strong need of an audience may easily find special forums for people enjoying flames. As for the Python list, let's keep it the calm and enjoyable place it usually is. Resist the temptation of feeding flames, rather ignore or merely learn to "killfile" the (happily few) abusers we got. Enough said for now! Keep happy, all of you. :-) -- François Pinard http://pinard.progiciels-bpi.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest setup
[George Sakkis] > Yes, py.test: http://codespeak.net/py/current/doc/test.html. The whole http://codespeak.net site contains many interesting projects, which are all worth a good look! However, there is a generic ``LICENSE`` file claiming copyrights on all files, without explaining what the copyright conditions are. This file also delegates copyright issues to individual files, which are usually silent on the matter. Could this whole issue be clarified? Or did I miss something I should not have? -- François Pinard http://pinard.progiciels-bpi.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess considered harmfull?
"Fredrik Lundh" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Steven Bethard wrote: > >> > Using the following snippet: >> > p = >> > subprocess.Popen(nmake,stderr=subprocess.PIPE,stdout=subprocess.PIPE, \ >> >universal_newlines=True, bufsize=1) >> > os.sys.stdout.writelines(p.stdout) >> > os.sys.stdout.writelines(p.stderr) >> > Works fine on the command line, but fails when called from within >> > Visual Studio, with the following error: >> > File "C:\Python24\lib\subprocess.py", line 549, in __init__ >> > (p2cread, p2cwrite, >> > File "C:\Python24\lib\subprocess.py", line 609, in _get_handles >> > p2cread = self._make_inheritable(p2cread) >> > File "C:\Python24\lib\subprocess.py", line 650, in _make_inheritable >> > DUPLICATE_SAME_ACCESS) >> > TypeError: an integer is required >> >> This looks like these known bugs: >> http://python.org/sf/1124861 >> http://python.org/sf/1126208 >> >> Try setting stderr to subprocess.PIPE. I think that was what worked for >> me. (You might also try setting shell=True. That's what I currently >> have in my code that didn't work before.) > > if someone wants to investigate, is seeing this problem, and have the win32 > extensions on their machine, try changing this line in subprocess.py: > >if 0: # <-- change this to use pywin32 instead of the _subprocess driver > > to: > >if 1: # <-- change this to use _subprocess instead of the pywin32 driver > > and see if it either fixes the problem (not very likely) or gives you a better > error message (very likely). > > > The error msg is only slightly better: error: (6, 'DuplicateHandle', 'The handle is invalid.') Basically, gui apps like VS don't have a console, so GetStdHandle returns 0. _subprocess.GetStdHandle returns None if the handle is 0, which gives the original error. Pywin32 just returns the 0, so the process gets one step further but still hits the above error. Subprocess.py should probably check the result of GetStdHandle for None (or 0) and throw a readable error that says something like "No standard handle available, you must specify one" Roger == Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News== http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups = East and West-Coast Server Farms - Total Privacy via Encryption = -- http://mail.python.org/mailman/listinfo/python-list
Re: Struggling with basics
"Jason" <[EMAIL PROTECTED]> wrote: > What I'd like to know is do you think it would be better to sort the > list in memory, or print it out sorted? If the latter, then naturally > I'd need to change the showScores section to show the list in a reverse > order. But, would sorting the list in memory be more effective? The list *is* sorted; the thing is that it is in ascending order (from lowest to highest) but you would rather have it in descending. There are (at least) two alternatives: 1. Keep the list as it is now in ascending order and print it in reverse. In python 2.4, this is as elegant and efficient as it can, using the reversed() builtin function. Just replace in showScores "for score,name in self.hiScores" with "for score,name in reversed(self.hiScores)". reversed() returns an iterator over the sequence, not a new list, so the memory overhead is minimal. 2. Instead of storing (score,name) pairs, store (-score,name). When a list of the latter is in ascending order, the former is in descending. In this case of course, you have to make sure that showScores() and lastScore() return the actual (positive) score, not the stored (negative) one. I would go for the first alternative but YMMV. George -- http://mail.python.org/mailman/listinfo/python-list
Re: Struggling with this concept please help
"George" <[EMAIL PROTECTED]> wrote: > Hello everyone I know many have helped but I cannot get this to work > out correctly. I cannot use BeautifulSoup at all. I need to: > [snipped] What do you mean you cannot use BeautifulSoup ? You cannot download it, install it, import it, or you are not allowed to use it because it's a homework ? If it's the latter, I doubt that you'll get a solution spelled out for you in this group. George -- http://mail.python.org/mailman/listinfo/python-list
Re: Struggling with this concept please help
Not allowed to use Beautiful Soup because of the very important built ins that is provides that makes it very simple to complete this problem. Not my choice . This is a review question for our final in two months and I just want to get things going so I can try to understand things better. Please help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Django Vs Rails
If you are looking for something pythonic, full featured and very easy to use, you should check this out: http://karrigell.sourceforge.net Give it a try and let me know how it goes... Cheers, Luis -- http://mail.python.org/mailman/listinfo/python-list
Re: Struggling with basics
George Sakkis wrote: > "Jason" <[EMAIL PROTECTED]> wrote: > >> What I'd like to know is do you think it would be better to sort the >> list in memory, or print it out sorted? If the latter, then naturally >> I'd need to change the showScores section to show the list in a reverse >> order. But, would sorting the list in memory be more effective? > > The list *is* sorted; the thing is that it is in ascending order (from lowest > to highest) but you > would rather have it in descending. There are (at least) two alternatives: > > 1. Keep the list as it is now in ascending order and print it in reverse. In > python 2.4, this is as > elegant and efficient as it can, using the reversed() builtin function. Just > replace in showScores > "for score,name in self.hiScores" with "for score,name in > reversed(self.hiScores)". reversed() > returns an iterator over the sequence, not a new list, so the memory overhead > is minimal. > > 2. Instead of storing (score,name) pairs, store (-score,name). When a list of > the latter is in > ascending order, the former is in descending. In this case of course, you > have to make sure that > showScores() and lastScore() return the actual (positive) score, not the > stored (negative) one. > > I would go for the first alternative but YMMV. > > George > > Thanks George, I've learned a lot tonight. -- http://mail.python.org/mailman/listinfo/python-list
One measurement by which Python is more popular than Ruby, Java, Perl, PHP and .NET
One measurement by which Python is more popular than Ruby, Java, Perl, PHP and .NET is in the world of Podcasts. At Podcastalley, podcasts are ranked by popularity in each of several genre's. In the "Technology" genre there are 1026 podcasts listed and ranked, and of the ones that are about programming languages and related areas, they show up in the rankings like this: 32. Python411 44. Perlcast 49. ProPHP 99. DotNetRocks 120. JavaCast and the Ruby on Rails podcast is not even ranked due to receiving zero votes ;-))) Just alight hearted comparison. The Python411 podcast sereis can be found at http://www.awaretek.com/python/index.html";>Python411 and you can subscribe to it by rss at http://www.awaretek.com/python/index.xml Python411 is a series of podcasts aimed at those who are learning Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Metaclasses, decorators, and synchronization
You could do it with a metaclass, but I think that's probably overkill. It's not really efficient as it's doing test/set of an RLock all the time, but hey - you didn't ask for efficient. :) 1 import threading 2 3 def synchronized(func): 4 def innerMethod(self, *args, **kwargs): 5 if not hasattr(self, '_sync_lock'): 6 self._sync_lock = threading.RLock() 7 self._sync_lock.acquire() 8 print 'acquired %r' % self._sync_lock 9 try: 10 return func(self, *args, **kwargs) 11 finally: 12 self._sync_lock.release() 13 print 'released %r' % self._sync_lock 14 return innerMethod 15 16 class Foo(object): 17 @synchronized 18 def mySyncMethod(self): 19 print "blah" 20 21 22 f = Foo() 23 f.mySyncMethod() If you used a metaclass, you could save yourself the hassle of adding a sync_lock in each instance, but you could also do that by just using a plain old base class and making sure you call the base class's __init__ to add in the sync lock. vic On 9/24/05, Michael Ekstrand <[EMAIL PROTECTED]> wrote: > I've been googling around for a bit trying to find some mechanism for > doing in Python something like Java's synchronized methods. In the > decorators PEP, I see examples using a hypothetical synchronized > decorator, but haven't stumbled across any actual implementation of > such a decorator. I've also found Synch.py, but that seems to use > pre-2.2 metaclasses from what I have read. > > Basically, what I want to do is something like this: > > class MyClass: > __metaclass__ = SynchronizedMeta > @synchronized > def my_sync_method(): > pass > > where SychronizedMeta is some metaclass that implements synchronization > logic for classes bearing some synchronized decorator (probably also > defined by the module defining SynchronizedMeta). > > After looking in the Cheeseshop, the Python source distribution, and > Google, I have not been able to find anything that implements this > functionality. If there isn't anything, that's fine, I'll just write it > myself (and hopefully be able to put it in the cheeseshop), but I'd > rather avoid duplicating effort solving previously solved problems... > So, does anyone know of anything that alreaady does this? (or are there > some serious problems with my design?) > > TIA, > Michael > > -- > http://mail.python.org/mailman/listinfo/python-list > -- "Never attribute to malice that which can be adequately explained by stupidity." - Hanlon's Razor -- http://mail.python.org/mailman/listinfo/python-list
how to merge sound files
Hi Is there a lib or code example for merging 2 sound files( wav or mp3 ) Thanks Wen -- http://mail.python.org/mailman/listinfo/python-list