Re: Generators and propagation of exceptions
On Apr 8, 3:47 pm, r wrote: > I'm already making something like this (that is, if I understand you > correctly). In the example below (an "almost" real code this time, I > made too many mistakes before) all the Expressions (including the > Error one) implement an 'eval' method that gets called by one of the > loops. So I don't have to do anything to detect the error, just have > to catch it and reraise it at each stage so that it propagates to the > next level (what I have to do anyway as the next level generates > errors as well). > > class Expression(object): > def eval(self): > pass > > class Error(Expression): > def __init__(self, exception): > self.exception = exception > > def eval(self): > raise self.exception Perhaps, instead of raising exceptions at each level, you could return an Error object that implements the eval() (or whatever appropriate protocol) to return an appropriate new Error object. In this case, you could have class Error(Expression); def eval(self): return unicode(self.exception) Error would itself be created by Expression.parseToken(), instead of raising an exception. The idea is that at each level of parsing, instead of raising an exception you return an object which, when interpreted at the next outer level, will again return an appropriate error object for that level. You might be able to have a single Error object which implements the required methods at each level to just return self. I don't know if this really works when you start nesting but perhaps it is worth a try. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.7.1
On Nov 27, 11:33 pm, Benjamin Peterson wrote: > On behalf of the Python development team, I'm happy as a clam to announce the > immediate availability of Python 2.7.1. Will there be Mac binaries for 2.7.1 and 3.1.3? Currently the web site shows only source and Windows binaries. Thanks, Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: PyGUI 2.0.4
On Apr 21, 8:05 am, Greg Ewing wrote: > PyGUI 2.0.4 is available: > > http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/ > > Fixes a few more bugs and hopefully improves things > on Windows, although I can't be sure it will fix all > the Windows problems people are having, because I > haven't been able to reproduce some of them. There is still a problem with unhandled WM_MOUSELEAVE events on WinXP/ Python 2.5. For example, - run blobedit.py - add a blob - quit the app; the "Save Changes" dialog appears - mouse over one of the buttons, then off the button to get this error: Traceback (most recent call last): File "C:\Downloads\PyGUI-2.0.4\GUI\Win32\Components.py", line 208, in _win_event_message event = win_message_to_event(message, self) File "C:\Downloads\PyGUI-2.0.4\GUI\Win32\Events.py", line 65, in win_message_to_event kind, button = win_message_map[msg] KeyError: 675 Adding this line to win_message_map in GUI/Win32/Events.py seems to fix it: wc.WM_MOUSELEAVE: ('mouse_leave', None), Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: utf-8 read/write file
On Oct 8, 5:55 pm, gigs <[EMAIL PROTECTED]> wrote: > Benjamin wrote: > > On Oct 8, 12:49 pm, Bruno <[EMAIL PROTECTED]> wrote: > >> Hi! > > >> I have big .txt file which i want to read, process and write to another > >> .txt file. > >> I have done script for that, but im having problem with croatian characters > >> (©,Ð,®,È,Æ). > > UnicodeDecodeError: 'utf8' codec can't decode byte 0x9e in position 0: > unexpected code byte Are you sure you have UTF-8 data? I guess your file is encoded in CP1250 or CP1252; in both of these charsets 0x9e represents LATIN SMALL LETTER Z WITH CARON. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: tcl/tk version confusion with tkinter in Python 2.6, on OS X
On Oct 6, 5:58 pm, [EMAIL PROTECTED] wrote: > On Oct 6, 4:48 pm, [EMAIL PROTECTED] wrote: > > > I'm having trouble with tkinter on a new installation of Python (2.6), > > built with the framework option from source that was downloaded from > > python.org. I'm running OS 10.4 on a PowerPC G4. > > > The problem first arose when I tried to run matplotlib - it couldn't > > find tcl/tk because it was searching for 8.5, and I had 8.4. I also had this problem. The error message at this point is ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/ lib/python2.6/lib-dynload/_tkinter.so, 2): Library not loaded: / Library/Frameworks/Tcl.framework/Versions/8.5/Tcl Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/ lib/python2.6/lib-dynload/_tkinter.so Reason: image not found Note that at this point I did have Tk 8.4 installed at /System/Library/Frameworks/Tk.framework/Versions/8.4 and this works fine with Python 2.5, so Python 2.6 seems to be looking specifically for Tk 8.5. > >I found > > and built tcl/tk 8.5, which led to a new error, reproduced below: > > RuntimeError: tk.h version (8.4) doesn't match libtk.a version (8.5) I installed Tcl/Tk 8.5 from ActiveState and got the same error. > Based on what I'm seeing in the error message and in the setup.py file > in the source code, it appears that Python 2.6 is looking in > /System/Library/Frameworks for a Tcl/Tk installation rather than in > /Library/Frameworks, which is second on the list of places to look. > Tcl/Tk 8.4 comes standard with OS X in 10.4 and 10.5, and it's > installed > in /System/Library/Frameworks. The problem is that Python 2.6 seems to > be linked against Tcl/Tk 8.5--is this correct?--and when it finds Tcl/ > tk > 8.4, it returns an error. I don't think that is quite right. In this second error, I think 8.4 is the compiled-in version, 8.5 is the version detected at runtime. 8.4 is the value of _tkinter.TK_VERSION, 8.4 is read from the Tk object. It looks to me like Python 2.6 is built against Tcl/tk 8.4 but at runtime it looks for Tcl/tk 8.5. > Should a bug report be filed against this? If the Mac build of Python > 2.6 consistently looks in /System/Library/Frameworks for Tcl/Tk, it > won't run Tkinter applications. It makes the build pretty much useless > for anyone needing it to run Tkinter apps, including Idle. I'd say > it's > a showstopper issue. I think so. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Prioritization function needed (recursive help!)
rh0dium wrote: > Hi all, > > I need some help on writing a recursive priority function > > Given a list = [ A, B, C, D] > > Where the following constraints are in place: > > A depends on [B, C] > C depends on [B] > > Figure out real order that prioritizes these. You need a topological sort. http://en.wikipedia.org/wiki/Topological_sort Two Python implementations: http://pypi.python.org/pypi/topsort/0.9 http://www.bitformation.com/art/python_toposort.html Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there any way to automatically create a transcript of an interactive Python session?
Jonathan Mark wrote: > Some languages, such as Scheme, permit you to make a transcript of an > interactive console session. Is there a way to do that in Python? > Maybe IPython's logging feature is what you want? http://ipython.scipy.org/doc/manual/node6.html#SECTION00066000 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple inheritance of a dynamic list of classes?
[EMAIL PROTECTED] wrote: > Hi, > > I am currently using the Cmd module for a mixed cli+gui application. I > am starting to refactor my code and it would be highly desirable if > many commands could be built as simple plugins. > > My idea was: > - Load a list of plugin names (i.e. from the config file, or from the > plugins directory) > - Import all plugins found dynamically: > and this is easy, since I can do, for example: > > PLUGIN_NAMES=['foo', 'bar'] > PLUGIN_MODULES = map(__import__, PLUGIN_NAMES) > PLUGINS = [item.Commands for item in PLUGIN_MODULES] > > Now, what I have to do is to define my command line class. This is > usually done by subclassing cmd.Cmd: > > class MyCli(cmd.Cmd): > > > Now I want to add the commands defined in foo.Commands and > bar.Commands. foo.Commands contains the functions corresponding to the > new commands this way: > #foo.py > class Commands > > def do_this(self,args): > ... > def do_that(self,args): > ... > > I've seen I can do it by explicitely import them and using multiple > inheritance: > > class MyCli(cmd.Cmd , foo.Commands, bar.Commands) > > > so that do_this and do_that are now methods of a Cmd command line. > > Now: > - how can I instead have MyCli inherit from a dynamic list of modules? > - is there a better way than using multiple inheritance to plug-in > dynamically commands in a Cmd command line? Your plugins could define plain functions with names starting with do_. Then you can create an empty subclass of cmd.Cmd and just plug in the imported commands: In [1]: import cmd In [3]: def do_this(self, arg): print 'This', arg ...: In [4]: def do_that(self, arg): print 'That', arg ...: In [8]: class MyCmd(cmd.Cmd): pass ...: In [9]: MyCmd.do_this = do_this In [10]: MyCmd.do_that = do_that In [11]: c=MyCmd() In [12]: c.cmdloop() (Cmd) help Undocumented commands: == help that this (Cmd) that That In your code you could use introspection to locate the plugin commands, something like PLUGIN_MODULES = map(__import__, PLUGIN_NAMES) for module in PLUGIN_MODULES: for name in dir(module): if name.startswith('do_'): setattr(MyCmd, name, getattr(module, name)) If the plugin module defines a list of commands then use that instead of dir(module). Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Array delete
azrael wrote: > if you are new to python then this will be easier to understand. if > you change this a liitle bit (depending on syntax) it should work in > any language. > just copy and paste to a .py file Yikes. If you are new to Python please ignore this un-Pythonic abomination. Check(listItem, temp) is just a long-winded way to say 'listItem in temp' and the whole thing could better be written as def main(): list, temp = [1, 1, 2, 4, 8, 8, 8, 8, 8, 8, 10], [] for item in list: if item not in temp: temp.append(item) print temp # print the new list where duplicates are removed For longer lists the set() method will probably be faster as this one searches temp for each item. Kent > > def main(): > list, temp = [1, 1, 2, 4, 8, 8, 8, 8, 8, 8, 10], [] > for i in range(len(list)): > if Check(list[i], temp) == 1: > temp.append(list[i]) > print temp # print the new list where duplicates are removed > > def Check(listItem,temp): > for i in range(len(temp)): > if listItem == temp[i]: > return 0 > return 1 > > if __name__=="__main__": > main() -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode formatting for Strings
[EMAIL PROTECTED] wrote: > Hi, > > I´m trying desperately to tell the interpreter to put an 'á' in my > string, so here is the code snippet: > > # -*- coding: utf-8 -*- > filename = u"Ataris Aquáticos #2.txt" > f = open(filename, 'w') > > Then I save it with Windows Notepad, in the UTF-8 format. So: > > 1) I put the "magic comment" at the start of the file > 2) I write u"" to specify my unicode string > 3) I save it in the UTF-8 format > > And even so, I get an error! > > File "Ataris Aqußticos #2.py", line 1 > SyntaxError: Non-ASCII character '\xff' in file Ataris Aqußticos #2.py > on line 1 It looks like you are saving the file in Unicode format (not utf-8) and Python is choking on the Byte Order Mark that Notepad puts at the beginning of the document. Try using an editor that will save utf-8 without a BOM, e.g. jedit or TextPad. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: in place-ness of list.append
Bart Van Loon wrote: > Hi all, > > I would like to find out of a good way to append an element to a list > without chaing that list in place, like the builtin list.append() does. > > currently, I am using the following (for a list of integers, but it > could be anything, really) > > #-- > def addnumber(alist, num): > """ work around the inplace-ness of .append """ > mylist = alist[:] > mylist.append(num) > return mylist > #-- Use + : In [1]: a=[1,2] In [2]: b=a+[3] In [3]: a Out[3]: [1, 2] In [4]: b Out[4]: [1, 2, 3] Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Can I undecorate a function?
[EMAIL PROTECTED] wrote: > Matt> In some instances I want to access just the function f, though, > Matt> and catch the values before they've been decorated. > > def f(x): > return x * x > > @as_string > def fs(x): > return f(x) or just fs = as_string(f) Kent > > Call the one you want. > > Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python book, new edition?
Bjoern Schliessmann wrote: > Demel, Jeff wrote: > >> Does anyone know if there's a plan in the works for a new edition >> of Learning Python? The current edition (2nd) is a few years old >> and looks like it only covers Python 2.3. > > IIRC, differences to 2.4 are in it, too. No, it is one version back from that. From the Preface to the second edition: "This edition has been thoroughly updated to reflect Python 2.2...in addition, discussion of anticipated changes in the upcoming 2.3 release have been incorporated." Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Some basic newbie questions...
jonathan.beckett wrote: I'm just finding it a bit weird that some of the built in functions are > static, rather than methods of objects (such as len() being used to > find the length of a list). Another explanation here: http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Slowdown in Jython
tac-tics wrote: > I have an application written in jython which has to process a number > of records. It runs fine until it gets to about 666 records (and maybe > that's a sign), and then, it's performance and responsiveness goes down > the toilet. It looks like it's running out of memory and is being > forced to use extended memory, but I do not know enough about the > language to figure out where this is happening. It will eventually > finish the task, but the window stops responding, and it ends up taking > several hours (as opposed to several minutes as it should). I really > just wish I had a tool for polling the amount of memory Jython was > using at any given moment. > > Does anyone have any strategy or advice for me? You can find out how much memory Jython is using the same as you would for any other application, e.g. Windows Task Manager or the equivalent. Jython is a Java application and you can increase the max heap available the same as for other java apps, using the command line switch -Xmx, e.g. -Xmx512m to set the max heap to 512 megabytes. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: One module per class, bad idea?
Carl Banks wrote: > Kent Johnson wrote: >> Carl Banks wrote: >>> Now, I think this is the best way to use modules, but you don't need to >>> use modules to do get higher-level organization; you could use packages >>> instead. It's a pain if you're working on two different classes in the >>> same system you have to keep switching files; but I guess some people >>> prefer to switch files rather than to scroll for some reason. >> That would be me. I strongly prefer to switch files rather than scroll. >> I use an editor that makes it easy to switch files. For me it is much >> easier to switch between files than to scroll between two parts of a >> file, and I don't lose my place when I switch back. I like to be able to >> see things side by side. > > Man, I don't know you do it. > > Say I'm sitting there concentrating on programming something, and I see > that I'll have to make a change in another file. All of a sudden, I > have to recall some filename out of thin air. Totally breaks my train > of thought, sometimes I space out trying to think of it because I have > to cold-start an entirely different part of my brain. It's less of a > mental distraction to just scroll. But then to go back to where you were, you have to scroll back and find your place. For me, just a click or keystroke to restore the last file with the cursor or selection exactly where I left it. And if I am going back and forth between the two, each switch is equally easy after the first (opening the file). > (BTW, any decent editor will let you view different positions of the > same file side-by-side.) Right, at a cost of showing you half as much of the one you care about. Anyway, I'm not trying to convince anyone to change, just pointing out that there are different styles of editing that make sense to those who use them, if not to outside observers ;-) Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: One module per class, bad idea?
Carl Banks wrote: > Now, I think this is the best way to use modules, but you don't need to > use modules to do get higher-level organization; you could use packages > instead. It's a pain if you're working on two different classes in the > same system you have to keep switching files; but I guess some people > prefer to switch files rather than to scroll for some reason. That would be me. I strongly prefer to switch files rather than scroll. I use an editor that makes it easy to switch files. For me it is much easier to switch between files than to scroll between two parts of a file, and I don't lose my place when I switch back. I like to be able to see things side by side. So I do tend to put classes in separate modules. Not always - when two or more classes are closely related or a class has one or more helper classes they may share a module - but in general my major classes are each to a module. It does make the imports look funny - I tend to give the module the same name as the class, Java style, so I have from foo.bar.MyClass import MyClass but that is a minor point IMO. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Common Python Idioms
Fredrik Lundh wrote: > Stephen Eilert wrote: > >> I do think that, if it is faster, Python should translate >> "x.has_key(y)" to "y in x". > > http://svn.python.org/view/sandbox/trunk/2to3/fix_has_key.py?view=markup Seems to have moved to here: http://svn.python.org/view/sandbox/trunk/2to3/fixes/fix_has_key.py?view=markup > > > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: reloading modules
Dustan wrote: > [EMAIL PROTECTED] wrote: >> I'm using python.exe to execute my modules. I have a music.py module >> which contains my classes and a main.py module which uses these >> classes. In python.exe, I call "import main" to execute my program. The >> problem is that I have to close python and reopen it everytime i change >> music.py or main.py. What should I be doing. >> >> Thanks, >> >> Aine. > import main > ### Execution Occurs ### # You go off to edit your module reload(main) > ### Execution Occurs ### If you edit music.py you will have to import music reload(music) to get the new music module, then reload(main) to run again. You could just type > python main.py at the command line each time you want to run, or use an editor that lets you run the program from within the editor. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Functions, callable objects, and bound/unbound methods
Ron Garret wrote: > The reason I want to do this is that I want to implement a trace > facility that traces only specific class methods. I want to say: > > trace(c1.m1) > > and have c1.m1 be replaced with a wrapper that prints debugging info > before actually calling the old value of m1. The reason I want that to > be an instance of a callable class instead of a function is that I need > a place to store the old value of the method so I can restore it, and I > don't want to start building a global data structure because that gets > horribly ugly, and a callable class is the Right Thing -- if there's a > way to actually make it work. If the only reason for a callable class is to save a single value (the original function), you could instead store it as an attribute of the wrapper function. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Functions, callable objects, and bound/unbound methods
Ron Garret wrote: > The reason I want to do this is that I want to implement a trace > facility that traces only specific class methods. I want to say: > > trace(c1.m1) > > and have c1.m1 be replaced with a wrapper that prints debugging info > before actually calling the old value of m1. The reason I want that to > be an instance of a callable class instead of a function is that I need > a place to store the old value of the method so I can restore it, and I > don't want to start building a global data structure because that gets > horribly ugly, and a callable class is the Right Thing -- if there's a > way to actually make it work. If the only reason for a callable class is to save a single value (the original function), you could instead store it as an attribute of the wrapper function. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: a quickie: range - x
Steven D'Aprano wrote: > On Wed, 29 Nov 2006 19:42:16 -0800, rjtucke wrote: > >> I want an iterable from 0 to N except for element m (<=M). > x = range(m-1) + range(m+1, N) Should be range(m) + range(m+1, N) Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: multi split function taking delimiter list
[EMAIL PROTECTED] wrote: > Hi, I'm looking for something like: > > multi_split( 'a:=b+c' , [':=','+'] ) > > returning: > ['a', ':=', 'b', '+', 'c'] > > whats the python way to achieve this, preferably without regexp? What do you have against regexp? re.split() does exactly what you want: In [1]: import re In [2]: re.split(r'(:=|\+)', 'a:=b+c') Out[2]: ['a', ':=', 'b', '+', 'c'] Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: command text parsing and hints displaying on user input.
Andy wrote: > Hi guys, > > I'm writing a program with a feature of accepting user input as command > text and parsing it to correct function calls...example: > > "5 minutes later"/"5 min later"/"5 minute later"/"after 5 minutes"... > are being parsed as the same rule so the system will call a later > function with minutes=5 as parameter. Maybe one of these will help: http://cheeseshop.python.org/pypi/parsedatetime/0.7.4 http://cheeseshop.python.org/pypi/when/1 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: why should dict not be callable?
[EMAIL PROTECTED] wrote: > A couple of times recently I've come across this problem: I have a > large list to sort and I need to the the "key=function" argument to > sort appropriately. But I actually have the key mapping in a big > dictionary. Now I have to make an intermediary function: > > def key_fn(key): >return key_dict[key] Try key=key_dict.__getitem__ In [3]: d=dict(a=1,b=2) In [4]: d.__getitem__('a') Out[4]: 1 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Book about database application development?
Wolfgang Keller wrote: > I know about the existence of MVC. But what I'm actually missing is a nice > textbook that teaches how to actually implement it (and other design patterns > which are useful for database applications) in a real-world application in a > way that leads to non-ridiculous behaviour of the resulting application when > it gets actually used. Maybe you would like Martin Fowler's "Patterns of Enterprise Application Architecture" http://martinfowler.com/books.html#eaa > Preferrably using a language for the examples that's readable for someone who > has learned programming ages ago with Pascal and is now using Python because > he _hates_ everything that remotely ressembles to any mutation of > C(++/#/Java). Examples are mostly Java and C#, sorry! Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: preemptive OOP?
Mark Elston wrote: > * Kent Johnson wrote (on 9/30/2006 2:04 PM): >> John Salerno wrote: >>> So my question in general is, is it a good idea to default to an OOP >>> design like my second example when you aren't even sure you will need >>> it? I know it won't hurt, and is probably smart to do sometimes, but >>> maybe it also just adds unnecessary code to the program. >> In general, no. I'm a strong believer in You Aren't Going to Need It >> (YAGNI): >> http://c2.com/xp/YouArentGonnaNeedIt.html >> >> because it *does* hurt >> - you have to write the code in the first place >> - every time you see a reference to MyNotebook you have to remind >> yourself that it's just a wx.Notebook >> - anyone else looking at the code has to figure out that MyNotebook is >> just wx.Notebook, and then wonder if they are missing something subtle >> because you must have had a reason to create a new class... >> >> and so on...Putting in extra complexity because you think you will need >> it later leads to code bloat. It's usually a bad idea. >> >> Possible exceptions are >> - If you are really, really, really sure you are going to need it >> really, really soon and it would be much, much easier to add it now then >> after the next three features go in, then you might consider adding it >> now. But are you really that good at predicting the future? >> - When you are working in a domain that you are very familiar with and >> the last six times you did this job, you needed this code, and you have >> no reason to think this time is any different. >> >> You struck a nerve here, I have seen so clearly at work the difference >> between projects that practice YAGNI and those that are designed to meet >> any possible contingency. It's the difference between running with >> running shoes on or wet, muddy boots. >> >> Kent > > I have only caught the tail of this thread so far so I may have missed > some important info. However, Kent's response is, I think, a bit of > an oversimplification. > > The answer to the original question, as quoted above, is ... it depends. > On several things, actually. Of course. > However, when an application (or library) is designed to provide a more > 'general purpose' solution to one or more problems and is likely to have > a lifetime beyond the 'short term' (whatever that may mean to you), then > OO can start to pay off. In these kinds of applications you see the > need for future maintenance and a likely need to expand on the existing > solution to add new features or cover new ground. This is made easier > when the mechanism for this expansion is planned for in advance. I am a fan of OOP and use it all the time. I was just arguing against using it when it is not called for. > > Without this prior planning, any expansion (not to mention bug fixing) > becomes more difficult and makes the resulting code more brittle. While > not all planning for the future requires OO, this is one mechanism that > can be employed effectively *because* it is generally well understood > and can be readily grasped *if* it is planned and documented well. Unfortunately prior planning is an attempt to predict the future. Correctly planning for future requirements is difficult. It is possible to expand code without making it brittle. Robert Martin has a great rule of thumb - first, do the simplest thing that meets the current requirements. When the requirements change, change the code so it will accommodate future changes of the same type. Rather than try to anticipate all future changes, make the code easy to change. > > There is certainly a *lot* of 'Gratuitous OOP' (GOOP?) out there. This > isn't a good thing. However, that doesn't mean that the use of OOP in > any given project is bad. It may be inappropriate. In my experience a lot of GOOP results exactly from trying to anticipate future requirements, thus introducing unneeded interfaces, factories, etc. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: preemptive OOP?
John Salerno wrote: > So my question in general is, is it a good idea to default to an OOP > design like my second example when you aren't even sure you will need > it? I know it won't hurt, and is probably smart to do sometimes, but > maybe it also just adds unnecessary code to the program. In general, no. I'm a strong believer in You Aren't Going to Need It (YAGNI): http://c2.com/xp/YouArentGonnaNeedIt.html because it *does* hurt - you have to write the code in the first place - every time you see a reference to MyNotebook you have to remind yourself that it's just a wx.Notebook - anyone else looking at the code has to figure out that MyNotebook is just wx.Notebook, and then wonder if they are missing something subtle because you must have had a reason to create a new class... and so on...Putting in extra complexity because you think you will need it later leads to code bloat. It's usually a bad idea. Possible exceptions are - If you are really, really, really sure you are going to need it really, really soon and it would be much, much easier to add it now then after the next three features go in, then you might consider adding it now. But are you really that good at predicting the future? - When you are working in a domain that you are very familiar with and the last six times you did this job, you needed this code, and you have no reason to think this time is any different. You struck a nerve here, I have seen so clearly at work the difference between projects that practice YAGNI and those that are designed to meet any possible contingency. It's the difference between running with running shoes on or wet, muddy boots. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: windev vs python SOS
[EMAIL PROTECTED] wrote: > Hi Stéphane, > > stéphane bard wrote: >> hello, my boss ask me to prefer windev to python. >> I have to argue > > First, no matter how good is Python, you should not desagree with your > boss. > Second, Windew is quite good and fun, you will love it. Yes, the boss is always right, shut up and drink your Kool-Aid! ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: efficient text file search.
noro wrote: > Is there a more efficient method to find a string in a text file then: > > f=file('somefile') > for line in f: > if 'string' in line: > print 'FOUND' Probably better to read the whole file at once if it isn't too big: f = file('somefile') data = f.read() if 'string' in data: print 'FOUND' -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for the Perfect Editor
Dick Moores wrote: > At 06:30 PM 9/10/2006, Kent Johnson wrote: >> Dick Moores wrote: >>> Also, why do you use TextPad instead of IDLE? >> You're kidding, right? > > No. Tell me, please. Macros? Comparing files? What else? OK...please, no one interpret this as IDLE bashing or attempt to show me a better way. I'm happy with TextPad and just writing this because I was asked... In my opinion: - Most of my Python work is actually in Jython. I can run a Jython program with a tool in TP. Actually I have separate tools for each active project that set the correct working directory and invoke a batch file with the right jars. Can't do that in IDLE. - TextPad is a good general-purpose editor, not just for Python. All the following reasons really come under this heading. I have an editor I like, it works great for Python, there is really no reason to use IDLE. - Fast and powerful multi-file search (easily specify the directory and file types to search) - Syntax highlighting for XML, HTML, Velocity templates, Ruby, Java, JavaScript, R, SQL, CSS...all file types I use more or less frequently. - Word wrap - Show invisibles - Customizable with macros and external tools - Open as binary etc... Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for the Perfect Editor
Dick Moores wrote: > I downloaded Python (7) from > http://www.textpad.com/add-ons/synn2t.html and put the file > PythonV2.4.syn in C:\Program Files\TextPad 4\system . > > However, no syntax highlighting is showing up. so I must have done > something wrong. Do I have to do something other than put > PythonV2.4.syn in C:\Program Files\TextPad 4\system ? One more step - make a new Document Class for Python (in the prefs). Associate it with *.py, turn on syntax highlighting and select the syntax file you downloaded. > > Also, why do you use TextPad instead of IDLE? You're kidding, right? Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for the Perfect Editor
Dick Moores wrote: > At 01:10 PM 9/8/2006, Doug Stell wrote: >> Try www.TextPad.com. I've used it for years and love it. It >> understands many programming language constructs and can be taught to >> understand python so that things show up in color. > > Any tips on how to teach TextPad to understand python? Download and install the Python syntax highlighting definition from the TextPad website. I make a tool to run the front window in Python. Here are the values from the preferences window for the tool: Command: C:\Python24\python.exe Parameters: -u $File Init fldr: $FileDir regex to match output: ^.*"([^"]+)", *line ([0-9]+) with File: 1, Line: 2 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the name of a class
Kirk Strauser wrote: > Larry Bates wrote: > >> print print b.__class__.__name__ gives what you want > > That doesn't seem to do it, though. Here's the result of importing a module > from my company's internally-developed library: > from Daycos.TableCopier.copyfro import StateProcessor print StateProcessor.__class__.__name__ > type > > I'm looking for something that would print 'StateProcessor' but am not > having much luck. It looks like StateProcessor is a class; StateProcessor.__class__ is the class of a class, i.e. type. Try StateProcessor.__name__ Kent -- http://mail.python.org/mailman/listinfo/python-list
Python proficiency test
I recently helped create an on-line Python proficiency test. The publisher of the test is looking for beta testers to try the test and give feedback. If you are interested, here is an announcement from the publisher: > Brainbench is currently beta testing a new series of test questions > for our Python 2.4 test. > > We are looking for knowledgeable Python 2.4 users. > > To take the test, simply go to > http://www.brainbench.com/xml/bb/common/testcenter/betatests.xml > and the rest should be self-explanatory. > > Any feedback you can provide us on the quality of the questions and > the test itself would be greatly appreciated. > You will be given the opportunity to provide anonymous feedback on > each question as it is administered as well as at the end of the test. > > We hope that you enjoy the test and look forward to your feedback! > > Feel free to pass this along to your friends. > > Thanks in advance for your help and good luck! Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Standard Yes / No Windows Dialog box creation
[EMAIL PROTECTED] wrote: > I found a way to create "Open File" or "Open Folder" windows dialog > boxes, but not to create an easier Yes / No dialog box... > Maybe someone has a solution for this? Maybe you would like EasyGui http://www.ferg.org/easygui/ Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: nested functions
Fredrik Lundh wrote: > George Sakkis wrote: > >> It shouldn't come as a surprise if it turns out to be slower, since the >> nested function is redefined every time the outer is called. > > except that it isn't, really: all that happens is that a new function object > is created from > prebuilt parts, and assigned to a local variable. it's not slower than, say, > a method call. Interesting. So func_code for a nested function is created when the module is compiled, and stuck in a new function object when the definition is executed. Like George, I always assumed that the body of the nested function was compiled when the outer function was executed, but that doesn't really make any sense - the *code* for the inner function is static, just the environment changes (globals(), closure). dis.dis reveals all: In [10]: def g(): : def h(): : print 'foo' : return h : In [11]: dis.dis(g) 2 0 LOAD_CONST 1 (", line 2>) 3 MAKE_FUNCTION0 6 STORE_FAST 0 (h) 4 9 LOAD_FAST0 (h) 12 RETURN_VALUE Thanks Fredrik! Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a better way of accessing functions in a module?
Ant wrote: > Ant wrote: > ... >> But this feels like a hack... Is there a cleaner way for accessing the >> functions of the current module similar to the __dict__ attribute of >> classes? i.e. a way to access the local symbol table? > > Sorry - posted too soon. Found the globals() built-in... You can also import __main__ tests = [x for x in dir(__main__) if x.endswith("test")] for test in tests: getattr(__main__, test)() but I second the suggestion of looking in to unittest or one of the other test frameworks. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: regexp questoin
[EMAIL PROTECTED] wrote: > hi > > i created a script to ask user for an input that can be a pattern > right now, i use re to compile that pattern > pat = re.compile(r"%s" %(userinput) ) #userinput is passed from > command line argument > if the user key in a pattern , eg [-] , and my script will search some > lines that contains [-] > > pat.findall(lines) > > but the script produce some error: sre_constants.error: unexpected end > of regular expression > > how can i successful catch patterns such as "[-]" in my regexp > compilation where input is unknown...? Maybe you want pat = re.compile(re.escape(userinput)) Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: secure xmlrpc server?
Kent Johnson wrote: > Laszlo Nagy wrote: >> But I do not know how to create an XML RPC server in Python that uses >> HTTPS for XML transports. > > This recent recipe seems to do exactly what you want: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496786 It was gently pointed out to me that the OP is the author of the recipe...well I guess he figured it out! That will teach me to get two days behind on reading c.l.py... -- http://mail.python.org/mailman/listinfo/python-list
Re: secure xmlrpc server?
Laszlo Nagy wrote: > But I do not know how to create an XML RPC server in Python that uses > HTTPS for XML transports. This recent recipe seems to do exactly what you want: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496786 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Storing nothing in a dictionary and passing it to a function
[EMAIL PROTECTED] wrote: > Hi, > > I'm writing a hand-written recursive decent parser for SPICE syntax > parsing. In one case I have one function that handles a bunch of > similar cases (you pass the name and the number of tokens you're > looking for). In another case I have a function that handles a > different set of tokens and so it can't use the same arguments as the > first one, and in fact takes no arguments. However, these functions > are semantically similar and are called from the same place one right > after the other. > > I'd like to have a dictionary (actually a nested dictionary) to call > these functions so I can avoid if-then-elsing everything. Eath > dictionary item has three things in it: the function to be called, a > string to pass to the function (which is also the key to the dict), and > a tuple to pass to the function. In the case of the function with no > arguments, obviously I'd like not to pass anything. > > I'm trying to do this 'functionally' (i guess), by avoiding > if-then-elses and just calling out the functions by accessing them and > their arguments from the dictionary. > > something like this: > alldict = \ > {'pulse': {'func': self.arbtrandef, 'args':(2,5)},\ >'sin' : {'func': self.arbtrandef, 'args':(2,3)},\ >'exp' : {'func': self.arbtrandef, 'args':(2,4)},\ >'pwl' : {'func': self.pwldef, 'args': (None,)},\ > <--- how > do I store "no" arguments? >'sffm' : {'func': self.arbtrandef, 'args':(5,0)}} > > for it in alldict.items(): > name = it[0] > args = (name,) + it[1]['args'] > it[1]['func'](*args) > > So basically this doesn't work. > > Any thoughts? You could omit the 'args' entry completely and test for this in the dispatch: 'pwl' : {'func': self.pwldef},\ for name, params in alldict.items(): try args = (name,) + params['args'] except KeyError: args = () params['func'](*args) Or include the 'name' parameter in the arg list and use an empty tuple for the arg to pwldef: 'exp' : {'func': self.arbtrandef, 'args':('exp', 2,4)},\ 'pwl' : {'func': self.pwldef, 'args': ()},\ for name, params in alldict.items(): params['func'](*args) Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: PQRC - Python Quick Reference Card - v 0.55
Laurent Pointal wrote: > And I'll maintain a fixed URL at > > http://laurent.pointal.org/python/pqrc/ Broken at the moment. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: [ANN] lxml 1.0 released
Stefan Behnel wrote: > Hallo everyone, > > I have the honour to announce the availability of lxml 1.0. > > http://codespeak.net/lxml/ > > It's downloadable from cheeseshop: > http://cheeseshop.python.org/pypi/lxml Are there any plans to offer a Windows installer? Thanks, Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for Visual Basic or C# programmers
A.M wrote: > I am trying to find the equivalent functions such as vb's str or asc in > Python. Is there any resource that help me to find these kinds of functions > in Python faster? The Library Reference has a section on built-in functions: http://docs.python.org/lib/built-in-funcs.html Also take a look at the section on string methods: http://docs.python.org/lib/string-methods.html Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: An oddity in list comparison and element assignment
[EMAIL PROTECTED] wrote: > Hi Alex, > With all due respect to your well-deserved standing in the Python > community, I'm not convinced that equality shouldn't imply invariance > under identical operations. > > Perhaps the most fundamental notion is mathematics is that the left and > right sides of an equation remain identical after any operation applied > to both sides. Our experience of the physical world is similar. If I > make identical modifications to the engines of two identical > automobiles, I expect the difference in performance to be identical. > If my expectation is met, I would assert that either the two vehicles > were not identical to begin with or that my modifications were not > performed identically. But programming is not mathematics and assignment is not an equation. How about this: In [1]: a=3.0 In [2]: b=3 In [3]: a==b Out[3]: True In [4]: a/2 == b/2 Out[4]: False Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: os.walk trouble
The Prophet wrote: > As my first Python script, I am trying to make a program that recurses > a directory searching for files whose names match a pattern. If your patterns are simple (supported by fnmatch), the path module makes this very easy: import path for f in path.path(dirname).walkfiles('*.foo'): # process a .foo file here http://www.jorendorff.com/articles/python/path/index.html Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: genexp performance problem?
Delaney, Timothy (Tim) wrote: > python -mtimeit "sum(int(L) for L in xrange(3000))" > 100 loops, best of 3: 6.76 msec per loop > > python -mtimeit -s "g = (int(L) for L in xrange(3000))" "sum(g)" > 100 loops, best of 3: 1.09 usec per loop > > The generator comprehension needs to create a new generator each time > around. Reusing the generator doesn't give a correct answer; after the first sum() the generator is exhausted: In [1]: g=(int(L) for L in xrange(10)) In [2]: sum(g) Out[2]: 45 In [3]: sum(g) Out[3]: 0 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing python dictionary in Java using JPython
sandip desale wrote: > Hi, > > We have some tools which are developed in Python and using python dictionaries. Now for some new requirments we are using Java and want to use the existing dictionaries as both the tools are executed on the same platform. So we are trying to use the existing dictionaries only using JPython libraries. How do you access the dictionary files from Python? The same thing may work in Jython. For example importing the file, if it is Python syntax, should work in Jython; also I think format 0 (text) and format 1 pickles are compatible with Jython. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Speed up this code?
[EMAIL PROTECTED] wrote: > I'm creating a program to calculate all primes numbers in a range of 0 > to n, where n is whatever the user wants it to be. I've worked out the > algorithm and it works perfectly and is pretty fast, but the one thing > seriously slowing down the program is the following code: > > def rmlist(original, deletions): >return [i for i in original if i not in deletions] > > original will be a list of odd numbers and deletions will be numbers > that are not prime, thus this code will return all items in original > that are not in deletions. For n > 100,000 or so, the program takes a > very long time to run, whereas it's fine for numbers up to 10,000. > > Does anybody know a faster way to do this? (finding the difference all > items in list a that are not in list b)? - Make deletions a set, testing for membership in a set is much faster than searching a large list. - Find a better algorithm ;) Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to handle exceptions with try/finally
Zameer wrote: > I wonder where the "else" goes in try..except..finally... > try / except / else / finally See the PEP: http://www.python.org/dev/peps/pep-0341/ Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding Upper-case characters in regexps, unicode friendly.
[EMAIL PROTECTED] wrote: > I'm trying to make a unicode friendly regexp to grab sentences > reasonably reliably for as many unicode languages as possible, focusing > on european languages first, hence it'd be useful to be able to refer > to any uppercase unicode character instead of just the typical [A-Z], > which doesn't include, for example É. Is there a way to do this, or > do I have to stick with using the isupper method of the string class? > See http://tinyurl.com/7jqgt Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: NEWB: how to convert a string to dict (dictionary)
manstey wrote: > Hi, > > How do I convert a string like: > a="{'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'}" > > into a dictionary: > b={'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'} Try this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 -- http://mail.python.org/mailman/listinfo/python-list
Re: can't figure out error: module has no attribute...
Chris_147 wrote: > but it seems to depend on from where I start the Python shell. > > so I've got a module selfservicelabels.py with some variables defined, > like this: > BtnSave = "link=label.save" > DeliveryAutomaat= "//[EMAIL PROTECTED]'deliveryMethod' and @value='AU']" > This module is in the Lib directory. > > Now when I do > import selfservicelabels > selfservicelabels.BtnSave >-> link=nmbs.label.save > selfservicelabels.DeliveryAutomaat >-> AttributeError: 'module' object has no attribute > 'DeliveryAutomaat' > > to make it more strange: PyCrust and Idle recognise DeliveryAutomaat > perfectly. > Everything above is done with Python 2.4.3 on Windows XP SP2 > > So after some testing it seems to depend on from which partition I > start Python. Probably you have multiple copies of selfservicelabels.py or an old selfservicelabels.pyc that is being imported. Try import selfservicelabels print selfservicelabels.__file__ to see where the import is coming from. Kent > So open commandline and navigate to a dir on C: everything works > perfectly. > Close python shell en navigate to D: some variables in > selfservicelabels.py are not known. > What is going on here? Is this a known error? > -- http://mail.python.org/mailman/listinfo/python-list
GUI viewer for profiler output?
Can anyone point me to a GUI program that allows viewing and browsing the output of the profiler? I know I have used one in the past but I can't seem to find it... Thanks, Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: grabbing portions of a file to output files
[EMAIL PROTECTED] wrote: > hi. > I have a file with this kind of structure: > > Hxxx > . > . > . > x > Hxxx > ... > > ... > x > H > . > > and so onlines starting with 'H' are headers. I wish to get the > parts of the file > where line start with 'H' all the way till before the next 'H' and save > to files of different names...how is the best way to do it ? > thanks Something like this? out = None for line in open(...): if line.startswith('H'): if out: out.close() out = open(..., 'w') if out: out.write(line) out.close() Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: who can give me the detailed introduction of re modle?
softwindow wrote: > the re module is too large and difficult to study > > i need a detaild introduction. > http://www.amk.ca/python/howto/regex/ Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: OOP and Tkinter
Ronny Mandal wrote: > file front_ui.py: > > class Front(object): > _images = [] # Holds image refs to prevent GC > def __init__(self, root): > # Widget Initialization > self._listbox_1 = Tkinter.Listbox(root, > height = 0, > width = 0, > ... > ) > > other file: > > from Front_ui import Front > > class CustomFront(Front): > Front._listbox_1.insert( 0, 'foo' ) > > ... > ... > File "H:\My Documents\Komodo\Front.py", line 63, in CustomFront > Front._listbox_1.insert( 0, foo' ) > AttributeError: type object 'Front' has no attribute '_listbox_1' > > > i.e., it cannot find the listbox! Strange, both files is in the same > folder. What is wrong here? _listbox_1 is an instance attribute, not a class attribute. You need to refer to self._listbox_1 from a CustomFront method, or change _listbox_1 to a class attribute if that is what you really want. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: any plans to make pprint() a builtin?
Duncan Booth wrote: > Personally I'd just like to see 'python' a builtin shorthand for importing > a name you aren't going to use much > e.g. > > python.pprint.pprint(x) Would you settle for import py py.std.pprint.pprint(x) ? http://codespeak.net/py/current/doc/misc.html#the-py-std-hook Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: retain values between fun calls
George Sakkis wrote: > Gary Wessle wrote: >> Hi >> >> the second argument in the functions below suppose to retain its value >> between function calls, the first does, the second does not and I >> would like to know why it doesn't? and how to make it so it does? >> >> thanks >> >> # it does >> def f(a, L=[]): >> L.append(a) >> return L >> print f('a') >> print f('b') >> >> >> # it does not >> def f(a, b=1): >> b = a + b >> return b >> print f(1) >> print f(2) > > It's a FAQ: > http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects. > > Whenever you want to control one or more objects beyond the lifetime of > a single function call, your first thought should be to use a class to > couple behaviour with state: > > class SomeFancyClassName(object): > def __init__(self, b=1): > self.b = b > def f(self, a): > self.b += a > return self.b > > x = SomeFancyClassName() > print x.f(1) > print x.f(2) If you make the class callable you can match the original syntax: In [40]: class F(object): : b=1 : def __call__(self, a): : F.b += a : return F.b : : In [41]: f=F() In [42]: f(1) Out[42]: 2 In [43]: f(2) Out[43]: 4 Alternately you can use an attribute of the function to save the state: In [35]: def f(a): : f.b += a : return f.b : In [36]: f.b=1 In [37]: f(1) Out[37]: 2 In [38]: f(2) Out[38]: 4 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: glob() that traverses a folder tree
[EMAIL PROTECTED] wrote: > # i'm guessing os.walk() is the best way to traverse folder trees. > > import os, glob > > for dir, subdir, files in os.walk('.\InteropSolution'): >for file in files: > if glob.fnmatch.fnmatch(file,"*.dll") or > glob.fnmatch.fnmatch(file,"*.exe"): > print dir+file Or use Jason Orendorff's path module. For a single glob it is very easy: import path for f in path.path('.\InteropSolution').walkfiles('*.dll'): print f For multiple globs you have to work a little harder: for f in path.path('.\InteropSolution').walkfiles(): if f.fnmatch('*.dll') or f.fnmatch('*.exe'): print f or maybe for f in path.path('.\InteropSolution').walkfiles(): if f.ext in ['.dll', '.exe']: print f http://www.jorendorff.com/articles/python/path/index.html Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest: How to fail if environment does not allow execution?
Kai Grossjohann wrote: > I wrote a test case that depends on a certain file existing in the > environment. So, I guess I should test that the file exists in the > setUp method. But what if it doesn't exist? How do I fail in that case? > > I would like to emit an error message explaining what is wrong. I would just use the file normally in the test. If it's not there you will get an IOError with a traceback and a helpful error message. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Memory leak in Python
[EMAIL PROTECTED] wrote: > Sure, are there any available simulators...since i am modifying some > stuff i thought of creating one of my own. But if you know some > exisiting simlators , those can be of great help to me. http://simpy.sourceforge.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: reusing parts of a string in RE matches?
John Salerno wrote: > I probably should find an RE group to post to, but my news server at > work doesn't seem to have one, so I apologize. But this is in Python > anyway :) > > So my question is, how can find all occurrences of a pattern in a > string, including overlapping matches? You can specify a start location to re.search(), and get the location of a match from a match object. This allows you to loop, searching the string following the last match: import re string = 'abababababababab' pattern = re.compile(r'ab(?=a)') ans = [] start = 0 while True: m = pattern.search(string, start) if not m: break ans.append( (m.start(), m.end()) ) start = m.start() + 1 print ans # => [(0, 2), (2, 4), (4, 6), (6, 8), (8, 10), (10, 12), (12, 14)] Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: data entry tool
Peter wrote: > This post seeks advice on whether python would be appropriate for a task, or > whether you can suggest another approach. > > The project is to transcribe historical records such as schools admissions, > ship passenger lists, birth/death/marriages, etc for genealogy studies. > What we need is a simple software tool that will give the user a form set > out like the page being transcribed, do some simple validation and put the > data in a file (can be fixed field length plain text). Data files from > volunteers will be compiled into a master database. > > This software tool needs to work on a variety of different computers; Win95, > Win98, WinXP, Mac, Linux. Take a look at Tkinter, it is pretty easy to get started with and good for making simple GUIs. Look at the csv module for writing the data to files. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expressions, substituting and adding in one step?
John Salerno wrote: > Call > me crazy, but I'm interested in regular expressions right now. :) Not crazy at all. REs are a powerful and useful tool that every programmer should know how to use. They're just not the right tool for every job! Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Enumerating Regular Expressions
[EMAIL PROTECTED] wrote: > Hi all, > > Does anybody know of a module that allows you to enumerate all the > strings a particular regular expression describes? Make a generator that yields *all* strings in your chosen alphabet (see the monthly threads about permutations and combinations for hints). Filter with the regex. Halting is left as an exercise for the reader. (Halting when the length reaches a predetermined limit would be one way to do it.) Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expressions, substituting and adding in one step?
John Salerno wrote: > Ok, this might look familiar. I'd like to use regular expressions to > change this line: > > self.source += '' + paragraph + '\n\n' > > to read: > > self.source += '%s\n\n' % paragraph > > Now, matching the middle part and replacing it with '%s' is easy, but > how would I add the extra string to the end of the line? Is it done all > at once, or must I make a new regex to match? > > Also, I figure I'd use a group to match the word 'paragraph', and use > that group to insert the word at the end, but how will I 'retain' the > state of \1 if I use more than one regex to do this? Do it all in one match / substitution using \1 to insert the value of the paragraph group at the new location: In [19]: test = "self.source += '' + paragraph + '\n\n'" In [20]: re.sub(r"'' \+ (.*?) \+ '\n\n'", r"'%s\n\n' % \1", test) Out[20]: "self.source += '%s\n\n' % paragraph" Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Global utility module/package
Christoph Haas wrote: > Evening, > > I'm currently working on a larger Python project that consists of multiple > programs and packages. As I need a few utility functions time and again I > moved them all into a Utility package and created a class there. ... > As I know that importing packages from multiple modules always keeps it a > singleton I thought of something like this: > > Util.py: > > debugFlag = False > vibranceLevel = 'good' > > def function1(): >global debugFlag >print debugFlag > > main.py: > > import Util > Util.debugFlag = True > Util.function1(whatever) > > def doThis(): >Util.function1(42) > > Here I don't use classes any longer. Good. But to access the "package > variables" I probably need to use "global" again which just moved the > ugliness to another position. This is fine. You don't need 'global' statements to read global variables, function1() can be simply def function1(): print debugFlag Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: the print statement
[EMAIL PROTECTED] wrote: > Thank you. Yes, that post answers most of the questions. I now have a > bit of an understanding of the \xhh pattern. It's still unclear to me, > however, how one can go from the \x92 pattern and arrive at the > apostrophe character. Is \x92 theh apostrophe character in another > character set? If so, which character set? \x92 is a right single quote in Windows cp1252. http://www.microsoft.com/globaldev/reference/sbcs/1252.mspx Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Designing Plug-in Systems in Python
mystilleef wrote: > Hello, > > I need to design a plug-in system for a project. The goal is > to allow third party developers interact with an application > via plug-ins in a clean and robust manner. At this point I > am overwhelmed by my inexperience with designing plug-in > systems. One of these might be helpful: http://developer.berlios.de/projects/plugboard/ http://termie.pbwiki.com/SprinklesPy Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Replace
Eric wrote: > I have a string... > > str = "tyrtrbd =ffgtyuf == =tyryr =u=p ff" > > I want to replace the characters after each '=', If you are replacing any char after = with # then re.sub() makes it easy: In [1]: import re In [2]: s = "tyrtrbd =ffgtyuf == =tyryr =u=p ff" In [3]: re.sub('=.', '=#', s) Out[3]: 'tyrtrbd =#fgtyuf =# =#yryr =#=# ff' If the replacement char is not fixed then make the second argument to re.sub() be a callable that computes the replacement. PS str is not a good name for a string, it shadows the built-in str. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: string.find first before location
Gary Wessle wrote: > ps. is there a online doc or web page where one enters a method and it > returns the related docs? The index to the library reference is one place: http://docs.python.org/lib/genindex.html and of course help() in the interactive interpreter... Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: strip newlines and blanks
[EMAIL PROTECTED] wrote: > hi > i have a file test.dat eg > > abcdefgh > ijklmn > <-newline > opqrs > tuvwxyz > > > I wish to print the contents of the file such that it appears: > abcdefgh > ijklmn > opqrs > tuvwxyz > > here is what i did: > f = open("test.dat") > while 1: > line = f.readline().rstrip("\n") > if line == '': > break break terminates the loop, so no more lines will be processed. Use continue, which ends only the current iteration of the loop. (Though you will need a separate test to terminate the loop when there are no more lines.) You can iterate an open file directly; here is a shorter version: for line in open('test.dat'): line = line.rstrip('\n') if line: print line Kent > print line > > but it always give me first 2 lines, ie > abcdefgh > ijklmn > > What can i do to make it print all w/o the newlines..? and what is the > proper way to skip printing blank lines while iterating file contents? > > thanks > -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to determine sequence ordering?
I V wrote: > Incidentally, does python have a built-in to do a binary search on a > sorted list? Obviously it's not too tricky to write one, but it would be > nice if there was one implemented in C. See the bisect module. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression help
Edward Elliott wrote: > [EMAIL PROTECTED] wrote: >> If you are parsing HTML, it may make more sense to use a package >> designed especially for that purpose, like Beautiful Soup. > > I don't know Beautiful Soup, but one advantage regexes have over some > parsers is handling malformed html. Beautiful Soup is intended to handle malformed HTML and seems to do pretty well. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: can this be done without eval/exec?
Schüle Daniel wrote: > and now the obvious one (as I thought at first) > > >>> lst=[] > >>> for i in range(10): > ... lst.append(lambda:i) > ... > >>> lst[0]() > 9 > >>> i > 9 > >>> > > I think I understand where the problem comes from > lambda:i seems not to be fully evalutated > it just binds object with name i and not the value of i > thus lst[0]() is not 0 The problem is that variables in closures are not bound until the variable goes out of scope. So each lambda is bound to the final value of i. > > are there other solutions to this problem > without use of eval or exec? The workaround is to use a default argument to bind the current value of i: In [1]: lst = [] In [2]: for i in range(10): ...: lst.append(lambda i=i: i) ...: ...: In [3]: lst[0]() Out[3]: 0 In [4]: lst[5]() Out[4]: 5 A list comp makes this IMO cleaner: In [5]: lst = [ lambda i=i: i for i in range(10) ] In [6]: lst[0]() Out[6]: 0 In [7]: lst[5]() Out[7]: 5 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: list of functions question
val bykoski wrote: > Hi The List: >I have a modeling app where i'm detecting events (in temporal > dynamics) applying a set of (boolean) functions - kind of: > > event_list = "f1 f2 etc".split() # each fi detects a specific event > i have defs for functions fi, or simple boolean expressions for each, so > that evList is a list of defs or boolean expressions > for ev in evList: > if ev:# this supposedly is a call ev(t) ># doing smth with the event # Make a list of the actual functions, not their names # For the events that are expressions, encapsulate them in functions event_list = [f1, f2, etc] # Call each one: for ev in event_list: if ev(t): # do something Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Thanks from the Java Developer
Alex Martelli wrote: > Ant <[EMAIL PROTECTED]> wrote: > >> Python ruined my life. Python ruined me for Java coding too. > At least in the Bay Area, the jobmarket for Python programmers is wild, > right now -- firms such as Google, Pixar, BitTorrent, IronPort, etc, > etc, all hungry for Pythonistas -- BayPIGgies mailing list bitching over > too many job-offer posts, and the nuisance of all those recruiters > haunting our monthly meetings and how much time they take, ...!!! Hmm...eagerly awaiting this phenomenon to reach the Boston area. Python seems to be mostly used for QA around here. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: send cookie on request with urllib2
itay_k wrote: > Hi, > > I dont understand why this is so complicated, just to add one line of > cookie header on the GET request. > > This is my unworking code: > import time > import Cookie > import cookielib, urllib2 > > c= cookielib.Cookie(1,"Name","Tom", 80,False, "itay", False, False, > "d:\\asddd",False, False,time.time()+1000,False,None,None,None) path is the server path to which the cookie applies. Try '/'. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: how to transfer a python object to other computer?
>> Hey, all.Now I wanna to transfer a object to other computer, Maybe I >> could serialize the object to a file by pickle moudle, then send the file >> and get it from the file.But I think the efficency is awful, because the >> disk io is very slow. >> Someone could do me a favor to give me some idea? Use pickle.dumps() and pickle.loads() to serialize to/from a string. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Method Call in Exception
Carl Banks wrote: > mwt wrote: >> In my latest attempt at some Python code, I've been tempted to write >> something in the form of: >> >> try: >> [...] #doing some internet stuff >> except IOError: >> alternate_method_that_doesnt_need_internet() >> >> This works when I try it, but I feel vaguely uneasy about putting >> method calls in exception blocks. So tell me, Brave Pythoneers, is this >> evil sorcery that I will end up regretting, or is it just plain good >> ol' Python magic? > > It's ok. In fact a lot of Pythonistas recommend this way over the > alternative, even when you don't have to. For example, a lot of people > recommend this: > > try: > name = record.name > except AttributeError: > name = "Freddy" > > instead of this: > > if hasattr(record,"name"): > name = record.name > else: > name = "Freddy" or maybe name = getattr(record, 'name', 'Freddy') Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Confused by Python and nested scoping (2.4.3)
Kelvie Wong wrote: > There are only two scopes in Python -- global scope and function scope. No, Python has local, nested, global and built-in scope. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: extracting a substring
[EMAIL PROTECTED] wrote: > Hi, > I have a bunch of strings like > a53bc_531.txt > a53bc_2285.txt > ... > a53bc_359.txt > > and I want to extract the numbers 531, 2285, ...,359. > > One thing for sure is that these numbers are the ONLY part that is > changing; all the other characters are always fixed. In that case a fixed slice will do what you want: In [1]: s='a53bc_531.txt' In [2]: s[6:-4] Out[2]: '531' Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: http request with cookie sending
itay_k wrote: > Hi, > > I want to send a cookie on some http request (with urllib2), > so I created a Cookie but I cant associate it with CookieJar object. You have to use a cookielib.Cookie, not Cookie.SimpleCookie(): import cookielib, urllib2 cj = cookielib.CookieJar() cookie = cookielib.Cookie(...your cookie data here...) cj.set_cookie(cookie) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) data = urllib2.urlopen(...).read() Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing backwards compatible code - when?
> Bob Greschke wrote: >> Is there a list of all of the Python commands and modules that tell when >> (what version) they were added to Python? I was hoping the new Essential >> Reference would have it, but it doesn't. The Library Reference page for a module or built-in often documents the version when any change was made. You can also read through the What's New documents for each release to see what changed in that release. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: A 'Box' Function
[EMAIL PROTECTED] wrote: > Hey guys. > > I should warn you, first off, that I'm relatively new to Python. > Basically, what I'm trying to do is create a word-wrapping function > with the added complication that it add a character at the beginning > and end of each line, so that it encloses the text in a sort of 'box': > > > | Like this | > > > The word-wrapping function I'm working with is similar to the one given > here: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061 > > Does anyone have any ideas on how it could be modified? Am I > approaching it the right way? Thanks a bunch! Rather than rewriting wrap(), I would suggest wrapping it with a new function, wrap_box(), that adds the header, line endings and trailer to the lines returned from wrap(). Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Missing interfaces in Python...
I V wrote: > To use interfaces in python, just what you would do in Java, except > don't use interfaces. +1 QOTW -- http://mail.python.org/mailman/listinfo/python-list
Re: scanning through page and replacing all instances of 00:00:00.00
Kun wrote: > Fredrik Lundh wrote: >> "Kun" wrote: >> >>> I have a python-cgi file that pulls data from an sql database, i am >>> wondering what is the easiest way to remove all instances of >>> '00:00:00.00' in my date column. >>> >>> how would i write a python script to scan the entire page and delete all >>> instances of '00:00:00.00', would i use regular expressions? >> umm. if you're using a database, why not filter out uninteresting dates >> either >> in the SQL statement, or when you're building the page ? >> >> > because in my sql database, the date is only 'date' (as in -mm-dd), > only when i extract it with my python-cgi does the date turn into > (-mm-dd 00:00:00.00), thus i figured the best way to fix this > problem is to parse it after the matter. It sounds like the problem is with the way you format the date for output. Just omit the time. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Python certification/training
Richard Marsden wrote: > Aahz wrote: >> Then may I suggest that you subscribe to the tutor list? That will give >> you a good place to ask questions; as you learn Python, answering other >> people's questions will give you a good way to hone your own knowledge. > > > Which is? :-) http://mail.python.org/mailman/listinfo/tutor Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem involving sets...
flamesrock wrote: > Kind of a fun but confusing problem... > > I have two lists. Each list contains elements of two-element lists. > l1 = [['c1',1],['c2',2],['c3',4]] > l2 = [['c1',1],['c2',2],['c4',4],['c3',3]] > > Exactly in this format, where > superlist[0][0] is always a string > superlist[0][1] is always an integer > > Now what I would like to do is find the intersect of those two > super-lists based on superlist[0][0] and then compare the integers to > find ultimately: > A list of strings of the intersect of l1/l2, where the l1[x][1] > > l2[x][1] > In the case of the above example, that would be simply: > ['c3'] In [5]: l1 = [['c1',1],['c2',2],['c3',4]] In [6]: l2 = [['c1',1],['c2',2],['c4',4],['c3',3]] In [7]: d=dict(l1) In [10]: [k for k,v in l2 if k in d and v < d[k]] Out[10]: ['c3'] Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode, command-line and idle
Egon Frerich wrote: > -BEGIN PGP SIGNED MESSAGE- > Hash: SHA1 > > What do you have in the IDLE options - General - Default source encoding? UTF-8 > > Egon > > Kent Johnson schrieb am 12.04.2006 12:40: > >> [EMAIL PROTECTED] wrote: >>> Hello again, I've investigated a little bit and this is what I found: >>> >>> If I run IDLE and type >>> >>>>>> import sys >>>>>> sys.stdin.encoding >>> I get >>> >>> 'cp1252' >>> >>> But if I have a whatever.py file (it can even be a blank file), I edit >>> it with IDLE, I press F5 (Run Module) and then type: >>> >>>>>> import sys >>>>>> sys.stdin.encoding >>> I get >>> >>> Traceback (most recent call last): >>> File "", line 1, in ? >>> sys.stdin.encoding >>> AttributeError: PyShell instance has no attribute 'encoding' >>> >>> So when I have the following code in a file: >>> >>> # -*- coding: cp1252 -*- >>> import sys >>> text1 = u'españa' >>> text2 = unicode(raw_input(), sys.stdin.encoding) >>> if text1 == text2: >>> print 'same' >>> else: >>> print 'not same' >>> >>> and I press F5 (Run Module) I get: >>> >>> Traceback (most recent call last): >>> File "C:\test.py", line 4, in ? >>> text2 = unicode(raw_input(), sys.stdin.encoding) >>> AttributeError: PyShell instance has no attribute 'encoding' >>> >>> This same code works if I just double-click it (run it in the windows >>> console) instead of using IDLE. >>> >>> I'm using Python 2.4.3 and IDLE 1.1.3. >> FWIW all of the above give me 'cp1252', not AttributeError, and the type >> of sys.stdin on my system is idlelib.rpc.RPCProxy, not PyShell. >> >> Python 2.4.3 and IDLE 1.1.3 on Win2k >> >> Kent > > - -- > Egon Frerich, Freudenbergstr. 16, 28213 Bremen > > E-Mail: [EMAIL PROTECTED] > -BEGIN PGP SIGNATURE- > Version: GnuPG v1.4.2.2 (MingW32) > Comment: GnuPT 2.7.2 > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iD8DBQFEPOpuuTzybIiyjvURAqKTAJ9omGK03L9p5dHpzjqN9Kz1w6cTYACghO6r > VG30LibkskG9M2boF/lTc0s= > =Xl96 > -END PGP SIGNATURE- > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: requestion regarding regular expression
BartlebyScrivener wrote: > Kent, > > Running > > path = "d:/emacs files/emacsinit.txt" > lines = open(path).readlines() > # my defun lines are lowercase, > # next two lines are all on one > starts = [i for i, line in enumerate(lines) if > line.startswith('(defun')] > for i, start in starts: > while start > 0 and lines[start-1].startswith(';'): > starts[i] = start = start-1 > print starts > > I get > > File "D:\Python\findlines.py", line 7, in __main__ > for i, start in starts: > TypeError: unpack non-sequence Sorry, should be for i, start in enumerate(starts): start is a specific start line, i is the index of that start line in the starts array (so the array can be modified in place). Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: requestion regarding regular expression
Kelie wrote: > Hello, > > I'm trying to analyze some autolisp code with python. In the file to > be analyzed there are many functions. Each function begins with a > "defun" statement. And before that, there may or may not have comment > line(s), which begins with ";". My goal is to export each function > into separate files, with comments, if there is any. Below is the code > that I'm struggling with: > > [code] > > path = "C:\\AutoCAD\\LSP\\Sub.lsp" > string = file(path, 'r').read() > > import re > pat = "\\;+.+\\n\\(DEFUN" > p = re.compile(pat,re.I) > > iterator = p.finditer(string) > spans = [match.span() for match in iterator] > > for i in range(min(15, len(spans))): > print string[spans[i][0]:spans[i][1]] > > [/code] > > The code above runs fine. But it only takes care of the situation in > which there is exactly one comment line above the "defun" statement. ISTM you don't need regex here, a simple line processor will work. Something like this (untested): path = "C:\\AutoCAD\\LSP\\Sub.lsp" lines = open(path).readlines() # Find the starts of all the functions starts = [i for i, line in enumerate(lines) if line.startswith('(DEFUN')] # Check for leading comments for i, start in starts: while start > 0 and lines[start-1].startswith(';'): starts[i] = start = start-1 # Now starts should be a list of line numbers for the start of each function Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: nested functions
[EMAIL PROTECTED] wrote: > hi > just curious , if i have a code like this? > > def a(): > def b(): > print "b" > def c(): > print "c" > > how can i call c() ?? c is a name in the local scope of a(). You can call c from within a, where the name is in scope, or you can return c or in some other way make the value available in some other scope: In [5]: def a(): ...: def c(): ...: print 'called c' ...: c() ...: return c ...: In [6]: cc=a() called c In [7]: cc() called c Kent -- http://mail.python.org/mailman/listinfo/python-list
%g not the same as %e or %f
According to the docs, %g formatting is "Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise." So I would expect that for any num, '%g'%num == '%e'%num or '%g'%num == '%f'%num. But this is not the case in fact: Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. In [1]: num = 1234567898.2345678945 In [2]: print "%g\n%e\n%f" % (num,num,num) 1.23457e+009 1.234568e+009 1234567898.234568 In [3]: num = 1234.456789 In [4]: print "%g\n%e\n%f" % (num,num,num) 1234.46 1.234457e+003 1234.456789 So I'm wondering if the docs are wrong or the implementation is wrong or there's something I don't understand? Thanks, Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: trying to grasp OO : newbie Q?
John Salerno wrote: > Couldn't we also say that this issue of namespace scope is a little more > specific to Python than OOP in general? I could very easily be wrong, > but I wouldn't want the poster to think that this is how OOP works always. No, the confusion in the OP was between class attributes, instance attributes and local variables. This distinction is pretty fundamental to OOP. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Initializing defaults to module variables
Burton Samograd wrote: > Hi, > > I'm writing an app that stores some user configuration variables in a > file ~/.program/config, which it then imports like so: > > import sys > from posix import environ > sys.path.append(environ["HOME"]+"/.program") > import config > > I can then access the configuration through code like: > > login(config.username) > > My question is, how can I setup my program defaults so that they can > be overwritten by the configuration variables in the user file (and so You could use the ConfigParser module instead of putting your config in a Python module. ConfigParser allows specifying defaults. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime: the date of the day one month ago...how?
gabor wrote: > hi, > > i'm trying to get the date of the day one month ago. > > for example: > > today = 12.apr.2006 > one-month-ago = 12.mar.2006 dateutil has one implementation of this: http://labix.org/python-dateutil Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode, command-line and idle
[EMAIL PROTECTED] wrote: > Hello again, I've investigated a little bit and this is what I found: > > If I run IDLE and type > import sys sys.stdin.encoding > > I get > > 'cp1252' > > But if I have a whatever.py file (it can even be a blank file), I edit > it with IDLE, I press F5 (Run Module) and then type: > import sys sys.stdin.encoding > > I get > > Traceback (most recent call last): > File "", line 1, in ? > sys.stdin.encoding > AttributeError: PyShell instance has no attribute 'encoding' > > So when I have the following code in a file: > > # -*- coding: cp1252 -*- > import sys > text1 = u'españa' > text2 = unicode(raw_input(), sys.stdin.encoding) > if text1 == text2: > print 'same' > else: > print 'not same' > > and I press F5 (Run Module) I get: > > Traceback (most recent call last): > File "C:\test.py", line 4, in ? > text2 = unicode(raw_input(), sys.stdin.encoding) > AttributeError: PyShell instance has no attribute 'encoding' > > This same code works if I just double-click it (run it in the windows > console) instead of using IDLE. > > I'm using Python 2.4.3 and IDLE 1.1.3. FWIW all of the above give me 'cp1252', not AttributeError, and the type of sys.stdin on my system is idlelib.rpc.RPCProxy, not PyShell. Python 2.4.3 and IDLE 1.1.3 on Win2k Kent -- http://mail.python.org/mailman/listinfo/python-list