ANNOUNCE: wxPython 2.5.4.1
Announcing -- I'm pleased to announce the 2.5.4.1 release of wxPython, now available for download at http://wxpython.org/download.php What is wxPython? - wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit Microsoft Windows, most Linux or other Unix-like systems using GTK or GTK2, and Apple Macintosh OS X. Changes in 2.5.4.1 -- wx.Sizer Add, Insert, and Prepend functions now return a reference to the wx.SizerItem that was added to the sizer, and the wx.SizerItem has a GetRect accessor to give the position of the item on the parent window. Added wx.Sizer.GetItem method which returns the wx.SizerItem for the given wx.Window, wx.Sizer or position index. wxMSW: wx.RadioButtons in the same group no longer have to be consecutive (there may be intervening controls). Without this fix, an out-of-sync assert is generated when clicking on a radio button and then calling GetValue(). Some XRC changes: - Added 'icon' property to wxFrame and wxDialog - No longer ignores menu bitmaps on non-MSW platforms - Notebook page bitmaps are now supported - added system colours and fonts support (based on patch #1038207) wxMSW: fix for [ 1052989 ] TextCtrl.SetBackgroundColour(wx.NullColour) bug. Added wx.PasswordEntryDialog analagous to wx.TextEntryDialog, allows detecting entering an empty string vs. cancel unlike the wx.GetPasswordFromUser dialog function. OGL patch from Shane Holloway: Two simple problems found in the new python ogl code. First is the patch for _canvas.py. Essentially:: dx = abs(dc.LogicalToDeviceX(x - self._firstDragX)) dy = abs(dc.LogicalToDeviceY(y - self._firstDragY)) was incorrect because (x,y) and (self._firstDragX, self._firstDragY) are both already in Logical coordinates. Therefore the difference between the two is also in logical coordinates, and the conversion call is an error. This bug surfaces when you have OGL on a scrollwin, and you are far from the origin of the canvas. The second change in _composit.py basically removes the assumption that the child is in both self._children and self._divisions. Causes many problems when it's not. ;) Fixed GetSaveData and SetSaveData in wx.lib.multisash to not depend on the default way that class objectss are converted to strings. Fixed problem in StyledTextCtrl.Set[HV]ScrollBar that could leave the internal scrollbar visible. Added wx.StandardPaths which provides methods for determining standard system paths for each platform. wxMSW: The window background is now only erased by default if the background colour or background mode has been changed. This better allows the default system themed behaviour to show through for uncustomized windows. Explicit support added for using the correct theme texture for wx.Notebook pages and their children. wx.Image: Added support for alpha channels in interpolated and non-interpolated image rotation. Added ConvertAlphaToMask helper method for turning shades of grey into shades of alpha and a colour. wxGTK2: Reimplemented DoDrawRotatedText() by way of a rotation of an alpha blended text bitmap. It would be better if Pango could draw directly into an wxImage (as FreeType can,) but that is for later... Added wrappers and a demo for the wx.MediaCtrl class, which can play various forms of audio/video media using native codecs install on the system. So far it is only implemented for Windows and OSX. wxGTK: Patch applied for Freeze()/Thaw() for wxTextCtrtl. Added gravity for splitter window (patch 1046105). Gravity is a floating-point factor between 0.0 and 1.0 which controls position of sash while resizing the wx.SplitterWindow. The gravity specifies how much the left/top window will grow while resizing. wxMSW: wx.Slider's C++ implementation rewritten to be more maintainable and hopefully less buggy. The position of the labels has also been changed in order to better comply with Microsoft's examples of how to use the control. wxMSW: Fix wx.TreeCtrl to end label editing if the control loses focus (a slightly modified patch 1084592.) Added wx.EXEC_NODISABLE flag for wx.Execute, which will prevent all the app's windows being disabled while a synchronous child process is running. wxMSW: Much work to correct painting (or leaving transparent) of control backgrounds, properly using background themes on XP, etc. Fixed a circular reference problem with wx.Timer. It will now completely cleanup after itself when the last reference to the timer is removed. If you
ANN: ElementTree 1.2.6 (march 16, 2005)
The Element type is a simple but flexible container object, designed to store hierarchical data structures, such as simplified XML infosets, in memory. The ElementTree package provides a Python implementation of this type, plus code to serialize element trees to and from XML files. ElementTree 1.2.6 is a maintenance release, consisting of 1.2.5 plus a fix for proper expansion of entities defined in internal DTD:s, minor fixes in the HTML parser, and proper serialization also if Python's default encoding has been changed. You can get the ElementTree package from: http://effbot.org/downloads#elementtree Documentation, code samples, and pointers to articles about the Element- Tree package are available from: http://effbot.org/zone/element.htm enjoy /F -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
ANN: cElementTree 1.0.2 (march 2, 2005)
effbot.org proudly presents release 1.0.2 of the cElementTree library, a fast and very efficient implementation of the ElementTree API, for Python 2.1 and later. On typical documents, it's 15-20 times faster than the Python version of ElementTree, and uses 2-5 times less memory. cElementTree 1.0.2 is 1.0.1 plus the missing iselement function, and a couple of minor tweaks and bug fixes. The library is available as C source code, and as Windows installers for all recent Python versions. Get your copy here: http://effbot.org/downloads#celementtree The cElementTree module uses some support functions from the standard ElementTree library, and will not work properly without it. If you haven't installed it already, you can get it from: http://effbot.org/downloads#elementtree enjoy /F -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
New Mailing List for PyCon 2005 Attendees
The PyCon organizers have created a mailing list for PyCon 2005 attendees: http://mail.python.org/mailman/listinfo/pycon2005-attendees We've subscribed attendees we had email addresses for. If you are attending PyCon and haven't received a welcome message, then we probably don't have your email address and you should subscribe to get last minute information. Alternatively, you can keep an eye on the archives. We'll remove this list a week or two after PyCon. Jim (P.S. The subsciber list for this mailing list is only viewable by the list administrators.) -- Jim Fulton mailto:[EMAIL PROTECTED] Python Powered! CTO (540) 361-1714http://www.python.org Zope Corporation http://www.zope.com http://www.zope.org -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
ANN: Leo 4.3-a4
Leo 4.3 alpha 4 is now available at http://sourceforge.net/projects/leo/ Leo 4.3 is the culmination of more than five months of work. This alpha 4 focuses on plugins: all known plugins are now in leoPlugins.leo. Most plugins now work with the 4.3 code base. This alpha 4 release also adds the frequently-requested Add Comments and Delete Comments commands to Leo's Edit Body menu. The defining features of Leo 4.3: - 1. Leo now stores options in @settings trees, that is, outlines whose headline is '@settings'. When opening a .leo file, Leo looks for @settings trees not only in the outline being opened but also in various leoSettings.leo files. Users can create arbitrarily complex user options with @settings trees. 2. The Preferences command temporarily replaces the outline pane with an outline showing all the @settings trees in effect. The Preferences command also replaces the body pane with a settings pane. This settings pane allows you to change the settings selected in the outline pane using standard gui widgets. 3. Leo's read/write code in leoAtFile.py has been rewritten to support user-defined tangling and untangling. This is a major cleanup of Leo's core. 4. Leo now contains an excellent Plugins Manager plugin. This plugin enables and disables plugins automatically and tells you everything you need to know about each plugin. This plugin also lets you download plugins from Leo's cvs site. 5. You can install third-party extensions in Leo's extensions directory. Leo will attempt to import such extensions from the extensions directory when normal imports fail. The distribution contains Python Mega Widgets in the extensions directory. What people are saying about Leo Word outlines are very useful. But Leo makes Word look like a clunky toy. --Joe Orr Leo is an interactive editor for organizing text fragments hierarchically and sequentially into one or more files and hierarchical folders, without arbitrary limits on the number and size of text fragments and the depth of the hierarchy...Tangle is a tool for combining hierarchically and sequentially organized text fragments into text files, hierarchically grouped into folders, with hierarchical or sequential organization of text within the files, and without arbitrary limits on the size and number of files and the depth of the hierarchy of folders and text nesting within the files. -- Alex Abacus Leo reminds me a great deal of things I loved when I used Userland's Frontier (an outlining cms with a native oodb) - but Frontier wasn't hackable enough for me, and it wasn't oriented towards coding and literate programming, and you couldn't round-trip rendered pages (big Leo win). This is really a super tool - in a matter of days I've started to use it on all my projects and I still haven't figured out how I lived without it. -- John Sequeira Leo is EXACTLY the kind of outliner I was looking for--fantastic job! -- Steve Allen If you are like me, you have a kind of knowledge base with infos gathered over time. And you have projects, where you use some of those infos. Now, with conventional outliners you begin to double these infos, because you want to have the infos needed for the project with your project. With Leo you can do this too, but if you change text in one place IT IS UPDATED IN THE OTHER PLACE TOO! This is a feature I did not see with any other outliner (and I tried a few). Amazing! Leo directly supports the way I work! -- F. Geiger More quotes at: http://webpages.charter.net/edreamleo/testimonials.html What makes Leo special? --- - Leo's outlines add a new dimension to programming. - Leo shows you your code and data the way _you_ want to see them. - Leo extends, completes and simplifies literate programming. - Leo's script buttons bring scripts to data. What is Leo? - A programmer's editor, an outlining editor and a flexible browser. - A literate programming tool, compatible with noweb and CWEB. - A data organizer and project manager. Leo provides multiple views of projects within a single outline. - Fully scriptable using Python. Leo saves its files in XML format. - Portable. leo.py is 100% pure Python. - Open Software, distributed under the Python License. Leo requires Python 2.2.1 or above and tcl/tk 8.4 or above. Leo works on Linux, Windows and MacOs X. Links: -- Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://sourceforge.net/cvs/?group_id=3458 Quotes: http://webpages.charter.net/edreamleo/testimonials.html Edward Edward K. Ream email: [EMAIL PROTECTED] Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html --
[ANN] Boa Constructor 0.4.0
Hi everyone, Boa Constructor 0.4.0 has been released and is available from the SourceForge file download page. http://sourceforge.net/project/showfiles.php?group_id=1909package_id=1856release_id=313481 The main focus of the release is wxPython 2.5 compatibility and source generation for the GUI designer. This release requires wxPython 2.5 to run. wxPython 2.4 is no longer supported, but there is a code upgrading tool provided to help upgrade from wxPython 2.4 to wxPython 2.5. A special thanks to Werner Bruhin for updating the tutorial and the code upgrading tool (started by Paul Sorenson). Enjoy, Riaan. http://boa-constructor.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Is Python like VB?
Mike Cox wrote: As you may or may not know, Microsoft is discontinuing Visual Basic in favor of VB.NET and that means I need to find a new easy programming language. I heard that Python is an interpreted language similar to VB. VB is not interpreted. Sure! You can compile it to P-Code if you want to but most people compile to machine code (like C, C++, Assembler). You are confusing between static linking in C++ etc and mandatory dynamic linking with VB runtimes with interpreted languages. VB needs runtimes but is not interpreted generally. Python is NOT similar to VB. It is much better as a language. VB is optimized to what you are doing currently. Python is a more general purpose language. This means that it doesn't have all the hard stuff like pointers, classes and templates like C, C++ and assembly language. Python has classes. C and Assembly do not have classes and templates. If I remember correctly, VB could have pointers too (Address function?). Where I work we use Microsoft Office with a lot of customization using Visual Basic. I would like to switch to Python to do it since VB is being discontinued. Would Python meet our requirements? I need to make lots of GUI applications (message boxes, forms, etc.) and do the underlying business logic too. You will probably find migrating to VB.NET easier than to Python if you have to do WYSIWYG data bound form design. VB.NET is quite a nice language (I personally prefer C#). Much nicer than VB6. Python is better but it may not meet YOUR needs infrastructure wise. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Mike == Mike Meyer [EMAIL PROTECTED] writes: Mike The real problem is that newbies won't know which features Mike are meta features best left to experts, and which features Mike are ok for everyday programmers to use. I suppose that a typical lazy newbie will just skip metaclasses and descriptors on the grounds of not understanding them immediately. It's the 'quest of guruhood' phase when novices start browsing wikis and obscure python-dev discussions to find out how these things work. All the documentation I've seen regarding these features mentions that the user probably doesn't need to know about them; this is especially true for metaclasses. -- Ville Vainio http://tinyurl.com/2prnb -- http://mail.python.org/mailman/listinfo/python-list
Re: computing a weighted sum
[Christos TZOTZIOY Georgiou] Anyway, a functional equivalent: . from itertools import starmap, izip . import operator . x= [1,2,3,4] . w=[3.0, 6.0, 9.0, 12.0] . sum(starmap(operator.mul, izip(x,w))) 90.0 Gack! starmap() is only for situations where the data is already in tuple form. If it inputs are already distinct, imap() is the preferred form. FWIW, the answer was already in the docs (itertools recipes): def dotproduct(vec1, vec2): return sum(imap(operator.mul, vec1, vec2)) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python like VB?
VB has a much better IDE than the IDE's for Python, although Eric3 is one of the best, and is absolutely free. There is no binary distribution for Eric3 on MS Windows. The OP sounds like he is an exclusively windows programmer. While we are on topic, is there no one in the Python open source community who has a commercial license to Qt for Windows and can make a binary distribution for Eric3 for MS Windows? -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python like VB?
On Wed, 16 Mar 2005 21:33:36 -0800, Mike Cox [EMAIL PROTECTED] wrote: Where I work we use Microsoft Office with a lot of customization using Visual Basic. I would like to switch to Python to do it since VB is being discontinued. Would Python meet our requirements? I need to make lots of GUI applications (message boxes, forms, etc.) and do the underlying business logic too. I wouldn't advise you to switch to Python from VB if... 1. the installer must be downloaded from the Net, so must be kept as small as possible (GUI layers like wxWidgets of PyGTK add several megabytes to your app) 2. you're used to sophisticated GUI designers like VB or Delphi, and want something as polished 3. you expect an IDE as rich as those two proprietary tools (including IntelliSense, intigrated GUI designer, compiler, etc.) 4. your app uses third-party components that are not available to platforms other than VB (or Delphi) After checking out the tools currently available, I got to the conclusion that Python is a very fine tool for text-based apps or moderately-sophisticated GUI apps like BitTorrent. For more demanding GUI apps, I would advise you stick to VB until the .Net framework stabilizes and trickles down to being available on 80% of hosts, at which point you can safely trade horses (VB.Net does solve some of the oddities of VB Classic.) In an ideal world, we'd have open-source development tools as rich as VB or Delphi, but at this point, I haven't found any that doesn't fall short on any of the points above (probably because the work involved is underevaluated, and just not doable without a constant and sufficient revenue stream.) Just my opinion, Joe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Mike Meyer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]... The real problem is that newbies won't know which features are meta features best left to experts, and which features are ok for everyday programmers to use. I think the original contributor to this thread was fairly accurate when he described some of the confusion that newcomers to Python have upon encountering Python's transititonal situation. I recall seeing a thread fairly recently where someone wanted to know if they should be using new-style classes or not, and whilst new-style classes do introduce some desirable behaviour, being told to inherit from object and then seeing lots of older code which doesn't do so raises a certain amount of uncertainty on the part of the newcomer. Everyone likes to criticise Java for additional notation which seems like distracting boilerplate that obstructs the learning process (eg. public static void main), but it would be worse if such notation were optional and if programs still had a main function/method by some other now-unfashionable means. Some of that uncertainty (albeit at less visible levels) does now exist in Python, raising the issue of coding best practices that I never thought would arise with the language. Paul -- http://mail.python.org/mailman/listinfo/python-list
psyco install problem
Hi, I run an ubuntu hoary linux. I have psyco installed as apt-get says, but when I launch python and try import psyco it does not find. I have tried locate psyco to find its source or compiled version without success. Is this a known bug in the python2.4-psyco debian package? - Gergely -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Kay Schluehr [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]... Some people refused properties in Python for exactly this reason. Defining somewhat like: def _get_X(self): return self._X def _set_X(self,X): self._X =3D X X =3D property(_get_X, _set_X ) in a Java-style fashion is indeed awfull and clumsy and that people dismiss such boilerplate code is understandable. The principal advantage of the property function was to permit the definition of active attributes without having a huge if...elif...else statement in the __getattr__ method. So the motivation was seemingly to externalize the usually simple logic in __getattr__ so that one could know a bit more about the supported properties of an object without having to read the source code. Java should be able to support Python-style properties by converting property accesses to accessor method calls before runtime, but with this capability within easy reach (and in all irony), the creators of the language instead decided to force programmers to explicitly call these rigidly-named methods, despite the raw property names actually being exposed to external tools like property editors, JavaServer Pages, and so on. [accessor code cut] class X(object): a = accessor(a) b = accessor(b, types = (tuple,list)) c = accessor(c, check = lambda x:hasattr(x,__len__)) Hmmm, lambda! a,b,c are indeed properties of X ! x = X() x.b = [1,2,3] # o.k x.b [1, 2, 3] x.b = 0 # raises a TypeError, because a tuple/list is expected This is a nice example, but I do wonder why so many examples of Python's dynamicity, especially with many of the newer features, seek to provide static type checking or some other variant on that theme. It would be nice to see more work done at the level of the compiler to achieve those kinds of goals. BRIDGEKEEPER: Stop! Who would cross the Bridge of Death must answer me these questions three, ere the other side he see. THE PYTHONIC KNIGHT: Ask me the questions, bridgekeeper. I am not afraid. BRIDGEKEEPER: What... is your name? THE PYTHONIC KNIGHT: My name is 'The Pythonic Knight'. BRIDGEKEEPER: What... is your quest? THE PYTHONIC KNIGHT: To seek the Holy Grail. BRIDGEKEEPER: What... are decorators for? THE PYTHONIC KNIGHT: Static type checking. No, param-- agh! Or something [1] like that. Paul [1] http://www.mwscomp.com/movies/grail/grail-23.htm -- http://mail.python.org/mailman/listinfo/python-list
Static parameter count
Hi all, This does not feel Pythonic. Is there a better way to do the same? Many TIA T # L = [1,2,3,4,5,6, etc] # L can contain 'n' elements # fmt is made up to each particular specification if len(L) == 0: return '' elif len(L) == 1: return struct.pack(fmt,L[0] ) elif len(L) == 2: return struct.pack(fmt,L[0] , L[1]) elif len(L) == 3: return struct.pack(fmt,L[0] , L[1], L[2]) elif len(L) == 4: return struct.pack(fmt,L[0] , L[1], L[2], L[3]) elif len(L) == 5: return struct.pack(fmt,L[0] , L[1], L[2], L[3], L[4]) elif len(L) == 6: return struct.pack(fmt,L[0] , L[1], L[2], L[3], L[4], L[5]) # etc... etc... etc ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python like VB?
James wrote: You will probably find migrating to VB.NET easier than to Python if you have to do WYSIWYG data bound form design. VB.NET is quite a nice language (I personally prefer C#). Much nicer than VB6. Python is better but it may not meet YOUR needs infrastructure wise. This is more a strategic decision than a technical one. MS has proven that it uses and forces its developers community to maximize their own profits and spread of technologies. Personally I dont want to be forced (Where do you want me to go today?) Who guarantees that VB.NET will not have the same tragic kismet that VB6 had? Open Source is totally different and thats the real difference between VB and python. As long as their are users and working code, there will be a community around an OSS tools project. This is not true for commercial tools, as perfectly proven by MS with VB6. Its users are crying and MS is deaf because of strategic MS considerations. http://news.com.com/Developers+slam+Microsofts+Visual+Basic+plan/2100-1007_3-5615331.html?tag=nl http://news.com.com/Microsoft+walks+VB+tight+rope/2100-1007_3-5620821.html?tag=nefd.lede -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Kay Schluehr schrieb: Some people refused properties in Python for exactly this reason. Defining somewhat like: def _get_X(self): return self._X def _set_X(self,X): self._X = X X = property(_get_X, _set_X ) in a Java-style fashion is indeed awfull and clumsy and that people dismiss such boilerplate code is understandable. This is original Delphi-Style, btw. But why is this boilerplate code? You define a property, and tell how it is read and written. How does your preferred code look like? -- --- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') --- -- http://mail.python.org/mailman/listinfo/python-list
Re: Static parameter count
Tertius Cronje wrote: Hi all, This does not feel Pythonic. Is there a better way to do the same? Many TIA T # L = [1,2,3,4,5,6, etc] # L can contain 'n' elements # fmt is made up to each particular specification if len(L) == 0: return '' elif len(L) == 1: return struct.pack(fmt,L[0] ) elif len(L) == 2: return struct.pack(fmt,L[0] , L[1]) elif len(L) == 3: return struct.pack(fmt,L[0] , L[1], L[2]) elif len(L) == 4: return struct.pack(fmt,L[0] , L[1], L[2], L[3]) elif len(L) == 5: return struct.pack(fmt,L[0] , L[1], L[2], L[3], L[4]) elif len(L) == 6: return struct.pack(fmt,L[0] , L[1], L[2], L[3], L[4], L[5]) # etc... etc... etc ... return struct.pack(fmt, *L) Should do the trick ola -- -- Ola Natvig [EMAIL PROTECTED] infoSense AS / development -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python like VB?
Maybe you should ask : Is VB like Python ( remark the ) On 17 Mar 2005 09:45:22 +0200, Ville Vainio [EMAIL PROTECTED] wrote: Cappy == Cappy2112 [EMAIL PROTECTED] writes: Cappy VB has a much better IDE than the IDE's for Python, Cappy although Eric3 is one of the best, and is absolutely free. Eric3 is not easily available for win32, due to current state of Qt licensing (will change with Qt4 I think). Cappy There are many gui toolkits/frameworks for Python, but the Cappy foreunners are pyQT, wxPython, pyGTK, and TK/Tkinter. On windows it might make sense to choose wxPython, though I've heard some good stuff about new versions of pyGTK as well. People coming from VB background probably also appreciate the ability to draw the UI in pointclick style: http://gazpacho.sicem.biz/ http://wxglade.sourceforge.net/ Unfortunately these seem to still be a tad rough around the edges... -- Ville Vainio http://tinyurl.com/2prnb -- http://mail.python.org/mailman/listinfo/python-list -- Regards, Groleo! .''`. # touch universe : :' : # chmod +rwx universe `. `'` # ./universe `- Debian - when you have better things to do than fix a system -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python like VB?
Before we discuss this any further, I suggest that you guys take a look at OP's posts in comp.os.linux.advocacy. I think we all regulars here know where VB and Python stand. Let's not take bait on this one. -- http://mail.python.org/mailman/listinfo/python-list
RE: Static parameter count
elif len(L) == 5: return struct.pack(fmt,L[0] , L[1], L[2], L[3], L[4]) elif len(L) == 6: return struct.pack(fmt,L[0] , L[1], L[2], L[3], L[4], L[5]) # etc... etc... etc ... return struct.pack(fmt, *L) Should do the trick ola Many thanks! It *did* the trick! T -- http://mail.python.org/mailman/listinfo/python-list
Re: Listbox fill=BOTH expand=YES (Tkinter)
On Thu, 17 Mar 2005 00:54:46 +0300, rumours say that Raseliarison nirinA [EMAIL PROTECTED] might have written: i'll recite 42 times precedence rules before going to bed. but now i'm a bit confused by the -in- operator. as: set(['TRUE','YES']).issubset(set(dir(Tkconstants))) True i expected this to be true, but it's not: set(['TRUE','YES']) in set(dir(Tkconstants)) False the 'in' operator searches for existance of *elements* in a set, not of *subsets*. BTW, only a frozenset can be included in a set. To check for subsets, either use the issubset function, or the '' operator (I believe they both call the same code): . set(['TRUE','YES']).issubset(set(dir(Tkconstants))) True can be expressed as . set(['TRUE','YES']) set(dir(Tkconstants)) True -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Re: Itertools wishlists
On Thu, 17 Mar 2005 06:09:44 GMT, rumours say that Raymond Hettinger [EMAIL PROTECTED] might have written: [snip] Did I make you believe I cared about the fate of any function judged unworthy even for the documentation? No. My note was mainly for the benefit of those who had an interest in what type of ideas had been discussed and the reasoning behind their inclusion/exclusion. It needed to be documented somewhere and the newsgroup discussion on a couple of proposals provided an opportunity to put those notes on record. In that case, I thank you too (like Terry) for the trouble writing down those notes. I'm just whining that putting recipes in the docs as an 'extended toolset' instead of in a module is a joking compromise... Not really. The recipes have several uses and none of them are compromises. Of course they aren't compromises. Who said they were? The subsentence is a joking compromise, to which your Not really applies, has putting as subject, not uses of recipes. It's possible that my lack of fluency in the English language confused you. [snip] By way of comparision, consider the evolution of set()/frozenset() which went through stages as recipes, as a PEP, then as Python module, and finally as C coded built-ins. That multi-stage process was deliberate and resulted in the final version being excellent. Similarly, many new decorators are going to start their lives as wiki entries or recipes. Ultimately, some will make it into the standard library. It would be a mistake to make that transition too quickly. That (long cycle/excellent results) is surely true. And sets are *very* useful as the majority would agree. Thanks about sets, too. The other purpose of the itertool recipes is to serve as a teaching tool showing how to combine the tools and how to integrate them with other Python code. IMO, most of the recipes are more useful in this capacity than as immediate solutions to particular problems. Well, I have to respect your opinion and so I drop the subject... but with my dying breath, re: to serve as a teaching tool showing how to combine the tools and how to integrate them with other Python code. , I cry that's why we hint at people to /read/ the /source/ of the standard library... :) Cheers. -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Re: computing a weighted sum
On Thu, 17 Mar 2005 08:11:11 GMT, rumours say that Raymond Hettinger [EMAIL PROTECTED] might have written: [Christos TZOTZIOY Georgiou] Anyway, a functional equivalent: . from itertools import starmap, izip . import operator . x= [1,2,3,4] . w=[3.0, 6.0, 9.0, 12.0] . sum(starmap(operator.mul, izip(x,w))) 90.0 Gack! starmap() is only for situations where the data is already in tuple form. If it inputs are already distinct, imap() is the preferred form. FWIW, the answer was already in the docs (itertools recipes): def dotproduct(vec1, vec2): return sum(imap(operator.mul, vec1, vec2)) What, you're some kind of expert on itertools now? :-) You are of course absolutely correct. Let my post stand as an example of itertools misuse. -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Re: Why tuple with one item is no tuple
Op 2005-03-16, Diez B. Roggisch schreef [EMAIL PROTECTED]: That ambiguity is only caused because python uses the same characters for very different operations and to be honest I don't like that. As I said: show me which parentheses to use - and keep in mind that: - and are for comparisions and the same ambiguity troubles arise - unicode surely features some usable characters (e.g. the quotation markes that look like , but are one char). But for one that complains that typing and additional comma is too much already, I doubt that having to press some weird multi key stroke is a viable option. Complaints about typing an extra character are not all the same. One can complain about the extra character that is needed on the screen and one can complain about the extra finger work that is needed to get a specific character on the screen. Besides I don't remember complaining about typing an extra character. To me neither, as I prefer my parentheses to be accessed easily, even on a vi running in a console from a tn3270 terminal for instance I have written once somekind of vector class where it was natural for these vectors to be added as well as te be concatenated. Unfortunately python uses + for both so I had no way to have both operators in a natural way in python. And no way in mathematics or any other language either - if you want the same function symbol on the same operators to have _different_ semantics, you're getting pretty non-deterministic. So python choose a non-deterministic direction. To me (2,3) + (4,5) equals (6,8). I don't dispute that having an operator to combine (2,3) and (4,5) in (2,3,4,5) is usefull, but they should never have used the + for that. So that a * would create an ambiguity if items would be silently transformed in a one-item tuple when appropiate is IMO more caused by the design decision to use * for two totally diffent operations then because of the dynamic nature of python. Your opinion is wrong. It's because you seem to not have understood the example: The expression (5 + 4) could be understood as 9 or as (9,). In python (and each and every other dynamically typed language) you can't decide which version to take. So you have to decide on _one_, and as every kid in school learns that (5+4) * 5 is 45, it was a reasonable decision to use the semantics we have today. No my opinion is not wrong, you just don't understand what I'm saying. No it was not reasonable to introduce the semantics that made 2 * (1,2) equal (1,2,1,2) IMO they should have used a differend operator for that and not the *. Soo, in the end it boils down to some explicitness - where IMHO an additional comma is pretty much no problem at all. Another option would of course be the introduction of different parentheses for tuples - but I can't find some on my keyboard. Well I can't find braille on my keyboard, but if I wanted to, it wouldn't be difficult to get it on my screen. So is it with different parentheses. That python can't use these parentheses is again a design decision. For someone who expresses his disliking to type _one_ comma in the few cases of single element tuples in thousands of lines of code, it strikes me odd that you'd go an are willing to add extra trouble entering _each_ and _every_ tuple in your code by using some hitherto unknown character that won't be enterable easily Where did I express this dislike. I'm not denying it because I know I forget such things, but I sure don't remember now. But you showed that strange sense of reasoning before - I remember you wanting to shave off microseconds by optimising constant expressions like 5*4, AFAIR I was just exploring ideas. whilst at the same time arguing in another thread that you'd like to have mutable keys for dicts that needed copying the very same keys - at much greater costs, per case and even more so in general as using dicts is common where pure constant arithmetic expressions aren't. Well it seems you didn't follow that thread thorougly. If you had you would have known that if the objects one had to work with were at the same time mutable and usefull as keys, you have to turn them into an immutable now for use as a key. This is a copy operation. So compared to the situation now, no extra copying would be necessary and no extra costs would be needed. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython vs. pyQt
Has anyone compiled binaries for qt/pyqt/eric3. i'd really like to try it. at the moment i work with wxWindows and BoaConstructor which i'm actually not so happy with. design of gui's with wx is not very efficient... so is there already a binary for qt/pyqt/eric3 available or when can i excpect qt4 to be released? tc -- http://mail.python.org/mailman/listinfo/python-list
Re: ElementTree, how to get the whole content of a tag
Damjan wrote: Is there any way I could get everything between the div and /div tag? div text some other textbr/ and then some more /div gettext(et) '\n text\n some other text\n and then some more\n' I acctually need to get '\n text\n some other textbr/\n and then some more\n' that's not the tree content, that's a serialized XML fragment. the quickest way to do that is to serialize the entire element, and strip off the start and end tags: text = ElementTree.tostring(elem) text = text.split(, 1)[1].rsplit(, 1)[0] alternatively, you can serialize the subelements, and add in properly encoded text and tail attributes: def innersource(elem, encoding=ascii): text = ElementTree._encode(elem.text or , encoding) for subelem in elem: text = text + ElementTree.tostring(subelem) if subelem.tail: text = text + ElementTree._encode(subelem.tail, encoding) return text (but _encode is not an official part of the elementtree API, so this code may not work in post-1.2 releases) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: I can do it in sed...
Damjan == Damjan [EMAIL PROTECTED] writes: Damjan Or, much nicer if line[:5]=='start': printing=1 Damjan if line.startswith('start'): printing=1 if line[:3]=='end': printing=0 Damjan if line.endswith('end'): printing=0 No, it's still line.startswith('end'), not endswith. -- Ville Vainio http://tinyurl.com/2prnb -- http://mail.python.org/mailman/listinfo/python-list
Re: I can do it in sed...
John == John Machin [EMAIL PROTECTED] writes: John You can get gnu Windows versions of awk sed and most other John suchlike goodies off the net ... Yeah, google for 'unxutils'. Cygwin versions of these tools can be a headache sometimes. -- Ville Vainio http://tinyurl.com/2prnb -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Op 2005-03-16, Jeff Shannon schreef [EMAIL PROTECTED]: news.sydney.pipenetworks.com wrote: More in relation to the original topic, why can't people just ignore features they don't understand and may never use directly. Because they may get stuck maintaining code that uses those features. So? You may get stuck maintaining code in an other language. Are you going to complain about the existence of different languages too? Now, I'm generally in agreement with you -- in general, Python features that aren't straightforward (e.g. metaclasses) are clearly advanced features and aren't likely to be in everyday code. I'm okay with just knowing that metaclasses exist, and having a vague idea of how one would use them. But the more features that some people ignore, the more that they tend to write in a customized dialect that's a subset of the full language. And the more people write code in their own personal (or group) dialect, the more fragmented the worldwide codebase becomes, and the harder it is to understand code that doesn't come from the circle of developers who you're directly familiar with. Well that will be a judgement call for all those people, just as life is mostly acting on judgement call. It's true that a given programmer doesn't need to understand every feature of the language, but it's not really fair to say ignore it and it won't affect you -- there's still a cost associated with such features that can't be ignored away. In some cases that cost is well worth bearing (as is the case for metaclasses and descriptors, especially as these two examples are implementation artifacts that would exist whether they were exposed to programmers or not), but in other cases it won't be, so it's important to keep in mind that the cost exists. Well if in some cases the costs are worth bearing, don't bear them. Move on and look out for an other language. Newbees often enough get the advise that with the mindset they currently have, python is not the language they are looking for and they would be happier programming in an other language. Well maybe that can happen to experienced programmers too. Maybe the language will evolve so it no longer fits there mindset. Well too bad, such things happen. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: sgmlop: malformed charrefs?
Magnus Lie Hetland wrote: According to The Sgmlop Module Handbook [1], the handle_entityref() callback is called for malformed character entities. What does that mean, exactly? What is a malformed character entity? I've tried mis-spelling them (e.g., dropping the semicolon), but then they're (quite naturally) treated as text/data, with handle_data(). I've tried to use number that is too great, or (equivalently, it turns out) to use names instead of numbers, such as #foo;. In these cases, I only get an exception, because the number is too high... So -- how can I produce a malformed character entity? with sgmlop 1.1, the following script class entity_handler: def handle_entityref(self, entityref): print ENTITY, repr(entityref) parser = sgmlop.XMLParser() parser.register(entity_handler()) parser.feed(-10;/()=?;) prints: ENTITY '-10' ENTITY '/()=?' And another thing... For the case where a numeric reference is too high (i.e. it can't be translated into a Unicode character) -- is it possible to ignore it (or replace it, as with encode/decode)? if you don't do anything, it is ignored. if you specify a handle_charref hook, the part between # and ; is passed to that method. if you have a handle_entityref hook, but no handle_charref, the part between and ; is passed to handle_entityref. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: I can do it in sed...
On Wed, 16 Mar 2005 19:06:40 -0600, rumours say that Terry Hancock [EMAIL PROTECTED] might have written: snip You mean you have a text file and you want to find all the lines between a line starting with start and one starting with end. snip lines = open('myfile', 'r').readlines() printing = 0 for line in lines: if line[:5]=='start': printing=1 if line[:3]=='end': printing=0 if printing: print line suggested order to mimic sed functionality: if line[:5]=='start': printing=1 if printing: print line if line[:3]=='end': printing=0 and perhaps it's better to use startswith than slicing. -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Re: Why tuple with one item is no tuple
So python choose a non-deterministic direction. To me (2,3) + (4,5) equals (6,8). I don't dispute that having an operator to combine (2,3) and (4,5) in (2,3,4,5) is usefull, but they should never have used the + for that. It certainly did not choose a nondeterministic action - that would mean that it followed _both_ possibilities at the same time. Which clearly is not happening. And we didn't talk about (2,3) + (4,5) not being (6,8) - that's adding two tuples, not having (9) beeing a tuple instead of a simple nine. Of course one could have overloaded tuples that way - component wise addition - but then people would want other kinds of vector algebraic stuff working on them. But they are not vectors, they are tuples. And in general, that is an entirely new discussion about the overloading of operators for tuples, not the syntax of how to create them (which is legitimate, of course - but misleading for this thread.) No my opinion is not wrong, you just don't understand what I'm saying. You alter the subject of discussion (see below), which caused that confusion. No it was not reasonable to introduce the semantics that made 2 * (1,2) equal (1,2,1,2) IMO they should have used a differend operator for that and not the *. Maybe - but thats an alltogether different discussion, as I said before. The point that made me kick into this discussion was: You really, really want (3 + 5) to be an integer, not a one-item tuple. I sometimes do wonder if some impliciteness wouldn't be better here, so that any item could be treated as if it was a one-item tuple. So you wanted (8) to be a tuple, or even more so 3 + 5 being (3,) + (5,). What has that to do with the operator overloading of tuples in general? It's a syntactic question we're discussing, _not_ a semantic one. As I stated before, it could become a question of type semantics if python was statically typed, as then the context of a expression like (8) could determine which type has to be created - tuple of one item, or simple 8. But it's not doable in python. For someone who expresses his disliking to type _one_ comma in the few cases of single element tuples in thousands of lines of code, it strikes me odd that you'd go an are willing to add extra trouble entering _each_ and _every_ tuple in your code by using some hitherto unknown character that won't be enterable easily Where did I express this dislike. I'm not denying it because I know I forget such things, but I sure don't remember now. I showed the quote above - you wanted to have (8) behave as (8,) - so I concluded you either don't like typing that extra comma, or alternatively want introduce a new pair of parentheses to express tuples. Well it seems you didn't follow that thread thorougly. If you had you would have known that if the objects one had to work with were at the same time mutable and usefull as keys, you have to turn them into an immutable now for use as a key. This is a copy operation. So compared to the situation now, no extra copying would be necessary and no extra costs would be needed. I did follow it, and I didn't say that the copying was necessary all the time, even for immutable keys. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple XML-to-Python conversion
[EMAIL PROTECTED] schrieb: I've been searching high and low for a way to simply convert a small XML configuration file to Python data structures. Take a look at Amara (http://uche.ogbuji.net/tech/4Suite/amara/). Lutz -- pub 1024D/6EBDA359 1999-09-20 Lutz Horn [EMAIL PROTECTED] Key fingerprint = 438D 31FC 9300 CED0 1CDE A19D CD0F 9CA2 6EBD A359 http://purl.oclc.org/NET/lutz.horn http://www.spreadfirefox.com/?q=user/registerr=200 -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple XML-to-Python conversion
Amara does indeed make it effortless to transform an XML document into a Python structure. Unfortunately this suggestion requires the 3rd party software, Amara, _and_ a 4Suite installation according to the website. The reason I can't expect users to have 3rd party tools is because this tool will be used in a secure lab environment without Internet access. Asking the admins to place these software packages on the network for users to install is like asking GW to say something semi-intelligent. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple XML-to-Python conversion
[EMAIL PROTECTED] wrote: Amara does indeed make it effortless to transform an XML document into a Python structure. Unfortunately this suggestion requires the 3rd party software, Amara, _and_ a 4Suite installation according to the website. The reason I can't expect users to have 3rd party tools is because this tool will be used in a secure lab environment without Internet access. Asking the admins to place these software packages on the network for users to install is like asking GW to say something semi-intelligent. Why not use distutils to install any additional packages you need? That's what it's there for. Presumably you're going to need to package this thing for distribution anyway. -- Website: www DOT jarmania FULLSTOP com -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple XML-to-Python conversion
A good question... Here's a followup question: Does third-party software compile as well as the built-in modules when using distutils and the py2exe extension module? -- http://mail.python.org/mailman/listinfo/python-list
ConfigParser
Is there an alternative to standard module ConfigParser, which can use delimitier symbol other than : and =, preferaby just space? I need to parse such configs: [Passwords] 2:5020/758 2:5020/794 ConfigParser is not able to work with option names which contain symbol ':' It is not difficult to modify ConfigParser to resolve it, but may be another solution already exists? -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple XML-to-Python conversion
Am Wed, 16 Mar 2005 14:19:49 -0800 schrieb [EMAIL PROTECTED]: I've been searching high and low for a way to simply convert a small XML configuration file to Python data structures. I came across gnosis XML tools, but need a built-in option for doing something similar. My knowledge of DOM and anything beyond simple XML structures is rudimentary at best. Is there a simple way to use SAX handlers to pull attributes and elements into Python lists/dictionaries? Hi, Just write a script which uses xml.sax. It is not difficult. You get an event for every start-tag and for every end-tag. The class which handles the events can build the structure if your XML file. The online version of the python cookbook has some python and SAX examples, Thomas -- Thomas Güttler, http://www.thomas-guettler.de/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple XML-to-Python conversion
[EMAIL PROTECTED] wrote: I've been searching high and low for a way to simply convert a small XML configuration file to Python data structures. I came across gnosis XML tools, but need a built-in option for doing something similar. My knowledge of DOM and anything beyond simple XML structures is rudimentary at best. Is there a simple way to use SAX handlers to pull attributes and elements into Python lists/dictionaries? tools like ElementTree and xmltramp are very easy to use. ElementTree builds a tree of Element objects which behave like lists (of subelements) and contain dictionaries (of attributes). xmltramp builds a tree where both subelements and attributes are mapped to object attributes. http://www.aaronsw.com/2002/xmltramp/ http://www.effbot.org/zone/element-index.htm if you want to ship any of them with your application, you only need a single module (xmltramp.py and ElementTree.py, respectively). API summaries: http://reagle.org/joseph/blog/technology/python/elementtree-model http://reagle.org/joseph/blog/technology/python/xmltramp-model (xmltramp might be a bit easier to use for simple cases, elementtree is a bit more flexible and a bit more efficient, especially if you're using the C implementation) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: ConfigParser
Sergey wrote: Is there an alternative to standard module ConfigParser, which can use delimitier symbol other than : and =, preferaby just space? I need to parse such configs: [Passwords] 2:5020/758 2:5020/794 ConfigParser is not able to work with option names which contain symbol ':' It is not difficult to modify ConfigParser to resolve it, but may be another solution already exists? What you need is an option keyname in front of each password entry in the [Passwords] section: I do this quite a lot: [Passwords] password_001=2:5020/758 password_002=2:5020/794 . . . You can then get a list of passwords from .INI like this: INI=ConfigParser.ConfigParser() INI.read(inifilename) section=Passwords passwordentries=[p for p in INI.options(section) if p.startswith('password_')] passwordentries.sort() # If you want to process them in order or to get list of passwords passwordlist=[INI.get(section, pk) for pk in passwordentries] Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python like VB?
Mike Cox [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]... As you may or may not know, Microsoft is discontinuing Visual Basic in favor of VB.NET and that means I need to find a new easy programming language. I heard that Python is an interpreted language similar to VB. This means that it doesn't have all the hard stuff like pointers, classes and templates like C, C++ and assembly language. Where I work we use Microsoft Office with a lot of customization using Visual Basic. I would like to switch to Python to do it since VB is being discontinued. Would Python meet our requirements? I need to make lots of GUI applications (message boxes, forms, etc.) and do the underlying business logic too. Thanks in advance. The macro language used within Microsoft Office products is called VBA - Visual Basic for Applications. It's similar to but not the same as VB - Visual Basic. You message hinted that it might be VBA, and not VB, that you use. If it really is VBA, then that MAY be unaffected by the drop of support for VB. -- http://mail.python.org/mailman/listinfo/python-list
Re: ConfigParser
Sergey wrote: Is there an alternative to standard module ConfigParser, which can use delimitier symbol other than : and =, preferaby just space? I need to parse such configs: [Passwords] 2:5020/758 2:5020/794 ConfigParser is not able to work with option names which contain symbol ':' It is not difficult to modify ConfigParser to resolve it, but may be another solution already exists? In case you won't get a satisfying answer there is always python package index: http://www.python.org/pypi Go to search and enter config into the keyword field, you'll get seven results, looking at description five of them are configuration file parsers. Serge. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Jeff Shannon [EMAIL PROTECTED] wrote: Because they may get stuck maintaining code that uses those features. Now, I'm generally in agreement with you -- in general, Python features that aren't straightforward (e.g. metaclasses) are clearly advanced features and aren't likely to be in everyday code. I'm okay with just knowing that metaclasses exist, and having a vague idea of how one would use them. But the more features that some people ignore, the more that they tend to write in a customized dialect that's a subset of the full language. And the more people write code in their own personal (or group) dialect, the more fragmented the worldwide codebase becomes, and the harder it is to understand code that doesn't come from the circle of developers who you're directly familiar with. In any non-trivial program, there will be a small language, consisting of functions, classes and data structures, that one need to learn and understand in order to maintain the program. If the implementation language (C, C++, Python, Ada, Pike, ...) is small with few features, that set of functions et.c will be larger, and you must thus take time to learn that instead. And that knowledge will *certainly* not help you with the next program you have to maintain; learning of (say) metaclasses on the other hand may very well do help you understand the next program. One may also note that features in the programming language are likely to be better documented than the small language internal to a large program, and thus easier to learn. It's true that a given programmer doesn't need to understand every feature of the language, but it's not really fair to say ignore it and it won't affect you -- there's still a cost associated with such features that can't be ignored away. There is a local cost with it, for learning Python, but I'm not sure there really is a global cost, when you look at the entire situation. -- Thomas Bellman, Lysator Computer Club, Linköping University, Sweden Too much of a good thing is WONDERFUL. ! bellman @ lysator.liu.se -- Mae West ! Make Love -- Nicht Wahr! -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple XML-to-Python conversion
On Thu, 17 Mar 2005 12:39:42 +0100, Lutz Horn [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] schrieb: I've been searching high and low for a way to simply convert a small XML configuration file to Python data structures. If using XML is not absolutely essential, you might want to take a look at YAML[1, 2]. [1] http://yaml.org/ [2] http://python.yaml.org/dist/ -- Premshree Pillai http://www.livejournal.com/users/premshree/ -- http://mail.python.org/mailman/listinfo/python-list
minidom get Element value
Hi all, Today's embarassingly simple question goes like this. I have a file, testdoc.xml, to parse. Inside the file is an element refrainYo, Ho, Ho/refrain So, starting with [code] from xml.dom import minidom xmldoc = minidom.parse('home\me\testdoc.xml') [/code] therefrain = getTagsByName('refrain') print therefrain.toxml() does print the whole Element What code do I need to merely print the *value* of the element, i.e., I would like to see Yo, Ho, Ho printed out. I can get Attribute values, the whole Element with tags, etc., and could do a substring search on the Element, but surely something exists within minidom to do this. Thanks. Scott -- http://mail.python.org/mailman/listinfo/python-list
Importing package modules from C-extension
Basic problem: If there is a C-extension module in a package and it tries to import another python module in the same package without using the fully qualified path, the import fails. Config: Python 2.4 on Windows 2000 For example: mypackage contains: cextension_example.pyd to_be_imported.py does_an_import.py Where: mypackage is a directory with an empty __init__.py file cextension_example.pyd is a c-extension module to_be_imported.py is a python module used by other python modules does_an_import.py is a python module which imports to_be_imported.py. In other words does_an_import.py looks like this: ---Start code--- import to_be_imported print to_be_imported ---End code--- and to_be_imported.py looks like this: ---Start code--- print 'Importing:', __file__ ---End code--- The c-extension cextension_example.pyd contains a line in its initialisation routine: ---Start code--- PyObject *pToBeImported = PyImport_Import(to_be_imported); ---End code--- Which returns NULL. I'd rather it imported the module from the local package. If at a python prompt I do this: import mypackage.does_an_import it works fine as I would expect from reading the documentation. It starts by looking in the package where it is currently placed before searching the PYTHONPATH. If at a python prompt I do this: import mypackage.cextension_example it fails to import to_be_imported.py which I do not expect. It does not look in the package where it is currently placed. In the past I have used the solution of a fully qualified path: E.g. ---Start code--- PyObject *pToBeImported = PyImport_Import(mypackage.to_be_imported); ---End code--- However this time my application is building library paths at runtime and doesn't know exactly what's going to be where. I can guarantee the directory structure will be like that above. So, how do I get the behaviour of import, rather than the behaviour of what looks more like __import__ ? Guesswork and speculation: From looking at the python source, it seems that in my C extension I need access to the module's dictionary (passed as globals and locals parameters to import functions), so that the parent package's __name__ entry can be used later on. Leading to more questions: If this is the case, how do I get at the current module and its dictionary from a c-extension function that takes no parameters ? Do I have to stash it away internally in the C-code on initialisation, or is there some thread local object I can get it from (either directly, or from the current frame) ? Is it good programming practice to use PyThreadState_Get()-frame ? Thanks for any help, Mark --- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. --- -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython vs. pyQt
tc wrote: Has anyone compiled binaries for qt/pyqt/eric3. i'd really like to try it. at the moment i work with wxWindows and BoaConstructor which i'm actually not so happy with. design of gui's with wx is not very efficient... so is there already a binary for qt/pyqt/eric3 available or when can i excpect qt4 to be released? tc Hi, If you're on a linux fedora3/suse 9.2 platform you can give a try to: pyvm.sourceforge.net regards, antonio -- http://mail.python.org/mailman/listinfo/python-list
Re: super with only one argument
Steven Bethard wrote: When would you call super with only one argument? The only examples I can find of doing this are in the test suite for super. I think it's to allow something like this: class A(B, C): __super = super(A) def foo(self): return self.__super.foo() This allows you to rename A and only have to change one super call to reflect the new name. --- Greg Chapman -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython vs. pyQt
tc wrote: Has anyone compiled binaries for qt/pyqt/eric3. i'd really like to try it. at the moment i work with wxWindows and BoaConstructor which i'm actually not so happy with. design of gui's with wx is not very efficient... so is there already a binary for qt/pyqt/eric3 available or when can i excpect qt4 to be released? tc http://kde-redhat.sourceforge.net/ apt/yum/etc. repositories qt-3.3.3-16.3.3.kde.i386.rpm sip-4.1.1-0.2.3.kde.i386.rpm PyQt-3.13-2.0.3.kde.i386.rpm PyKDE-3.11.3-0.5.3.kde.i386.rpm qscintilla-1.4-0.1.3.kde.i386.rpm eric-3.6.1-0.fdr.1.3.i386.rpm and more -- http://mail.python.org/mailman/listinfo/python-list
How to create datetime object from DbiDate (win32.odbc)?
Hi all I am using odbc from win32 extensions to connect to MS SQL Server. I use mx.DateTime to handle dates. When I select a datetime column from the database, odbc returns something called a DbiDate object. I cannot find out any information on this type, but mx can convert it to a mx.DateTime object using DateTimeFrom(), which is really all that I need. I am looking into changing from mx.DateTime to using the builtin datetime type, but I cannot figure out how to convert a DbiDate object to a datetime object. First prize would be to have a datetime constructor that takes a DbiDate object as input, in the same way that mx does, but this does not seem to exist. Second prize would be to extract the year/month/day elements from the DbiDate object, and construct the datetime object manually. However, if I try dir(d), where d is a DbiDate object, I get an empty list, so I cannot even see how to extract the elements. Does anyone know if this is possible, and if so, how? Many thanks Frank Millman -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python like VB?
Mike Cox wrote: As you may or may not know, Microsoft is discontinuing Visual Basic in favor of VB.NET and that means I need to find a new easy programming language. I heard that Python is an interpreted language similar to VB. This means that it doesn't have all the hard stuff like pointers, classes and templates like C, C++ and assembly language. Where I work we use Microsoft Office with a lot of customization using Visual Basic. I would like to switch to Python to do it since VB is being discontinued. Would Python meet our requirements? I need to make lots of GUI applications (message boxes, forms, etc.) and do the underlying business logic too. I would either stick with the old Visual Basic since plenty of other people will keep using it, or go ahead and switch to VB.NET or C#. Especially if you are used to the Windows Form Designer in Visual Studio, I would not recommend switching to Python. It has no equivalent, and thus Python would be much harder for you to use. We have almost finished Windows form designer support in SharpDevelop IDE for boo, a .NET language similar to Python. But still in your case I'd just use VB.NET since you are familiar with VB and all .NET languages are pretty comparable. -- http://mail.python.org/mailman/listinfo/python-list
PyCon: Request for Video Cameras
Hello, We are needing a couple additional video cameras to ensure that we can capture the presentations at PyCon 2005. MiniDV is the preferred format, but as long as you can capture your video to a common video format on a hard disk, that is acceptable. If you are a candidate participant, please review the discussion on the wiki, and update the page with your information. The wiki is at: http://www.python.org/moin/PyConDC2005/TalkRecording Please include: - Your name - Equipment (e.g. Panasonic GS-14, tripod) - Format (e.g. MiniDV) - Camera connnection (e.g. Firewire) - Arrival/Departure/Where staying - Geographic home Cheers, --ldl -- LD Landis - N0YRQ - from the St Paul side of Minneapolis -- http://mail.python.org/mailman/listinfo/python-list
Re: super with only one argument
Greg Chapman wrote: Steven Bethard wrote: When would you call super with only one argument? The only examples I can find of doing this are in the test suite for super. I think it's to allow something like this: class A(B, C): __super = super(A) def foo(self): return self.__super.foo() This allows you to rename A and only have to change one super call to reflect the new name. Except that doesn't work unless you use something like the autosuper metaclass trick from test_descr.py (since the class A does not yet exist where I put that super call). And autosuper has a comment that it only works for dynamic classes -- not sure that I understand what dynamic means there. In case you haven't guessed by now, I've only used two-arg super in my own code. --- Greg Chapman -- http://mail.python.org/mailman/listinfo/python-list
Re: Splitting with Regular Expressions
Am Thu, 17 Mar 2005 06:51:19 -0800 schrieb qwweeeit: Splitting with RE has (for me!) misterious behaviour! I want to get the words from this string: s= 'This+(that)= a.string!!!' in a list like that ['This', 'that', 'a.string'] considering a.string as a word. Hi, try this: re.findall(r'[\w\.]+', s) ['This', 'that', 'a.string'] If you use r'...' you don't need to use \\ if you mean \ \w matches a-zA-Z0-9_ \W matches all except \w Thomas -- Thomas Güttler, http://www.thomas-guettler.de/ -- http://mail.python.org/mailman/listinfo/python-list
tkinter: call root.after from a thread?
Let's say we have root = Tk() ... layout gui, spawn thread etc root.mainloop() Is a safe to call the method root.after(...) from a separate thread? (The registered callback updates the GUI). I know you're supposed to avoid calling methods such as pack(), etc. from a thread, but I was wondering if calling root.after() would be safe? I'm doing this in a GUI without any problems, so far. Thanks, -- Benjamin Rutt -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI toolkit question
[EMAIL PROTECTED] writes: I'm building an app that operates on tuples (typically pairs) of hierarchical structures, and i'd like to add a GUI to display my internal representation of them, and simplify manipulations/operations on them. My requirements are: 1) Draw a single 3D representation of the hierarchies, and the connections between them. 2) All objects must be interactive. That is, they should have left/middle/rightClick behavior; they must be draggable (with rubber band behavior of their conncections); the user should be able to highlight a set of them, associate them as a group, then execute some group operation. 3) I don't need very fancy stuff from the normal widgets. Just menus, a few buttons, dialog boxes, etc. 4) Don't need complex 3D behavior. 5) Don't need to ever run on Windows, just *nix. 6) May eventually need to either compile the Python, or port part/all of it to C++. I started looking into Qt, Wx, Blender, etc, but don't even know if i have the right questions in mind. Any thoughts, considerations, recommendations would be much appreciated. thanks in advance, Eric The GUI toolkits (gtk, qt, wx, fltk, etc) generally give you a 3D window, and then you are on your own. In the window you could use VRML, X3D, or your own homegrown OpenGL treatment. Next up the foodchain, there are visualization tools which can link together lots of nodes and arcs. See: http://www.opendx.org/index2.php -- [EMAIL PROTECTED] 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 -- http://mail.python.org/mailman/listinfo/python-list
Re: ConfigParser
Hmm interesting situation. The following will work with ConfigObj : [Passwords] 2:5020/758 2:5020/794 http://www.voidspace.org.uk/python/configobj.html Regards, Fuzzy -- http://mail.python.org/mailman/listinfo/python-list
Re: sgmlop: malformed charrefs?
In article [EMAIL PROTECTED], Fredrik Lundh wrote: Magnus Lie Hetland wrote: [snip] with sgmlop 1.1, the following script class entity_handler: def handle_entityref(self, entityref): print ENTITY, repr(entityref) parser = sgmlop.XMLParser() parser.register(entity_handler()) parser.feed(-10;/()=?;) prints: ENTITY '-10' ENTITY '/()=?' OK, thanks. I guess I just wasn't creative enough in my entity naming :) And another thing... For the case where a numeric reference is too high (i.e. it can't be translated into a Unicode character) -- is it possible to ignore it (or replace it, as with encode/decode)? if you don't do anything, it is ignored. if you specify a handle_charref hook, the part between # and ; is passed to that method. I see -- it's just if the default behaviour of transforming it to text kicks in that there is trouble? (That makes sense, of course.) if you have a handle_entityref hook, but no handle_charref, the part between and ; is passed to handle_entityref. Strange. It doesn't seem to work that way for me... Here is an example: .. from xml.parsers.sgmlop import SGMLParser, XMLParser, XMLUnicodeParser class Handler: def handle_data(self, data): print 'DATA', data def handle_entityref(self, data): print 'ENTITY', data for parser in [SGMLParser(), XMLParser(), XMLUnicodeParser()]: parser.register(Handler()) try: parser.feed('#99;') except Exception, e: print e .. When I run this, I get: character reference #x540be3ff; exceeds ASCII range character reference #x540be3ff; exceeds ASCII range character reference #x540be3ff; exceeds sys.maxunicode (0x) If I remove the handle_data, nothing happens. /F -- Magnus Lie Hetland Time flies like the wind. Fruit flies http://hetland.org like bananas. -- Groucho Marx -- http://mail.python.org/mailman/listinfo/python-list
Re: Splitting with Regular Expressions
A pyparsing example may be less mysterious. You can define words to be any group of alphas, or you can define a word to be alphas concatenated by '.'s. scanString is a generator that scans for matches in the input string and returns the matching token list, and the start and end location of the match within the input string. (Because it returns a list, this is why we have to peel of element 0 of each match to get the word.) See the sample code attached. -- Paul (get pyparsing at http://pyparsing.sourceforge.net) from pyparsing import Word,alphas,delimitedList test= 'This+(that)= a.string!!! This... is .just.a sentence.' word = Word(alphas) print [ wd[0] for wd,s,e in word.scanString(test) ] # prints ['This', 'that', 'a', 'string', 'This', 'is', 'just', 'a', 'sentence'] word = delimitedList(Word(alphas), delim=.,combine=True) print [ wd[0] for wd,s,e in word.scanString(test) ] # prints ['This', 'that', 'a.string', 'This', 'is', 'just.a', 'sentence'] -- http://mail.python.org/mailman/listinfo/python-list
Re: Splitting with Regular Expressions
qwweeeit [EMAIL PROTECTED] wrote: Splitting with RE has (for me!) misterious behaviour! I want to get the words from this string: s= 'This+(that)= a.string!!!' in a list like that ['This', 'that', 'a.string'] considering a.string as a word. print re.findall([\w.]+, s) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: I can do it in sed...
Kotlin Sam wrote: Also, I frequently use something like s/^[A-Z]/~/ to pre-pend a tilde or some other string to the beginning of the matched string. I know how to find the matched string, but I don't know how to change the beginning of it while still keeping the matched part. Something like re.sub(r'^([A-Z])', r'~\1', target) should do it. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Obfuscated Python: fun with shadowing builtins
very good. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: super with only one argument
``super`` with only one argument (bound super) is a mess. AFAICT ``super(C)`` is intended to be used as an attribute in other classes. Then the descriptor magic will automatically convert the unbound syntax in the bound syntax. For instance: class B(object): ... a = 1 class C(B): ... pass class D(C): ... sup = super(C) d = D() d.sup.a 1 This works since ``d.sup.a`` calls ``super(C).__get__(d,D).a`` which is converted to ``super(C, d).a`` and retrieves ``B.a``. There is a single use case for the single argument syntax of ``super`` that I am aware of, but I think it gives more troubles than advantages. The use case is the implementation of autosuper made by Guido on his essay about new-style classes (the one Grep Chapman is citing). The idea there is to use the unbound super objects as private attributes. For instance, in our example, we could define the private attribute ``__sup`` in the class ``C`` as the unbound super object ``super(C)``: C._C__sup = super(C) With this definition inside the methods the syntax ``self.__sup.meth(arg)`` can be used as an alternative to ``super(C, self).meth(arg)``, and the advantage is that you avoid to repeat the name of the class in the calling syntax, since that name is hidden in the mangling mechanism of private names. The creation of the ``__sup`` attributes can be hidden in a metaclass and made automatic. So, all this seems to work: but actually this is *not* the case. Things may wrong in various case, for instance for classmethods, as in this example:: #ex1.py class B(object): def __repr__(self): return 'instance of %s' % self.__class__.__name__ @classmethod def meth(cls): print B.meth(%s) % cls class C(B): @classmethod def meth(cls): print C.meth(%s) % cls cls.__super.meth() C._C__super = super(C) class D(C): pass D._D__super = super(D) d=D() d.meth() #/ex1.py The last line raises an ``AttributeError: 'super' object has no attribute 'meth'.`` So, using a ``__super`` unbound super object is not a robust solution (notice that everything would work by substituting ``self.__super.meth()`` with ``super(C,self).meth()``. There are other ways to avoid repeating the class name, see for instance my cookbook recipe, which will also be in the printed version. If it was me, I would just remove the single argument syntax of ``super``, making it illegal. But this would probably break someone code, so I don't think it will ever happen. Another solution would be just to deprecate it. There is no need for this syntax, one can always circumvent it. Also, notice that the unbound form of ``super`` does not play well with pydoc. The problems is still there in Python 2.4 (see bug report SF729103) class B(object): pass ... class C(B): ... s=super(B) ... help(C) Traceback (most recent call last): ... ... lots of stuff here ... File /usr/lib/python2.4/pydoc.py, line 1290, in docother chop = maxlen - len(line) TypeError: unsupported operand type(s) for -: 'type' and 'int' Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
A Q. on pop().
Hi, The code. def buildStackMajor(): for node in dirStackMinor: #print 's is the node...', node dirStackMajor.append(node) dirStackMinor.pop() print 'POP the stack...', len(dirStackMinor) print 'after pop...', dirStackMinor When I start the for loop I have 11 members in the stack- a list. The pop() is poping member from the back, as though it's deal with a LIFO stack instead of LIFO. I never get pass a length of 5. first Q.. Why is pop() starting from the back back of the stack? second Q.. Why can't I never empty the stack? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python like VB?
We have almost finished Windows form designer support in SharpDevelop IDE for boo, a .NET language similar to Python. But still in your case I'd just use VB.NET since you are familiar with VB and all .NET languages are pretty comparable. Wow! That's great news. I saw a few days ago an old post that said you guys were waiting for the new .NET as implementing this kind of thing is simpler in it. Anyway. Great work. This probably makes Boo the first non-MS .NET language to have form designer support. Correct? -- http://mail.python.org/mailman/listinfo/python-list
MySQL problem
I have the following program( only insert a record) import MySQLdb conn = MySQLdb.connect (host = localhost,user = , passwd = ,db=dilynamobily) cursor = conn.cursor () cursor.execute(CREATE TABLE produkt1 ( id int(10) unsigned NOT NULL auto_increment, MyNumber varchar(30) NOT NULL default '', PRIMARY KEY (id)) ) #MyValue=111 cursor.execute (INSERT INTO produkt1 (MyNumber) VALUES(111) ) # It works. But If I change the program like the following ( only use a variable MyValue in INSERT statement it does not work. ##THIS DOES NOT WORK import MySQLdb,re,string conn = MySQLdb.connect (host = localhost,user = , passwd = ,db=dilynamobily) cursor = conn.cursor () cursor.execute(CREATE TABLE produkt1 ( id int(10) unsigned NOT NULL auto_increment, MyNumber varchar(30) NOT NULL default '', PRIMARY KEY (id)) ) MyValue=111 cursor.execute (INSERT INTO produkt1 (MyNumber) VALUES(MyValue) ) # Program says OperationalError: (1054, Unknown column 'MyValue' in 'field list') Where is a problem. Thanks for help Lad. -- http://mail.python.org/mailman/listinfo/python-list
Re: Obfuscated Python: fun with shadowing builtins
Michael Hoffman wrote: Enjoy ;) That's not the exact word that first came to my mind :) -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQL problem
Lad wrote: I have the following program( only insert a record) import MySQLdb conn = MySQLdb.connect (host = localhost,user = , passwd = ,db=dilynamobily) cursor = conn.cursor () cursor.execute(CREATE TABLE produkt1 ( id int(10) unsigned NOT NULL auto_increment, MyNumber varchar(30) NOT NULL default '', PRIMARY KEY (id)) ) #MyValue=111 cursor.execute (INSERT INTO produkt1 (MyNumber) VALUES(111) ) # It works. But If I change the program like the following ( only use a variable MyValue in INSERT statement it does not work. ##THIS DOES NOT WORK import MySQLdb,re,string conn = MySQLdb.connect (host = localhost,user = , passwd = ,db=dilynamobily) cursor = conn.cursor () cursor.execute(CREATE TABLE produkt1 ( id int(10) unsigned NOT NULL auto_increment, MyNumber varchar(30) NOT NULL default '', PRIMARY KEY (id)) ) MyValue=111 cursor.execute (INSERT INTO produkt1 (MyNumber) VALUES(MyValue) ) # Program says OperationalError: (1054, Unknown column 'MyValue' in 'field list') Where is a problem. Thanks for help Lad. Lad, Try str = INSERT INTO produkt1 (MyNumber) VALUES(%d) % (MyNumber) cursor.execute(str) wes -- http://mail.python.org/mailman/listinfo/python-list
Re: A Q. on pop().
spencer wrote: first Q.. Why is pop() starting from the back back of the stack? Because that is what it does. Try reading the documentation: help(list.pop) Help on method_descriptor: pop(...) L.pop([index]) - item -- remove and return item at index (default last) second Q.. Why can't I never empty the stack? Because you are modifying a list while iterating over it which is never a good idea. What you have now pops items from the end of the loop so it stops about half way along. If you change it to pop item 0 then it will shift the items down and your iteration will end up skipping over about half of them. Try something like this: def buildStackMajor(): while dirStackMinor: dirStackMajor.append(dirStackMinor.pop(0)) although in that case you might just as well get rid of the loop entirely: dirStackMajor += dirStackMinor del dirStackMinor[:] -- http://mail.python.org/mailman/listinfo/python-list
Re: sgmlop: malformed charrefs?
Magnus Lie Hetland wrote: if you have a handle_entityref hook, but no handle_charref, the part between and ; is passed to handle_entityref. Strange. It doesn't seem to work that way for me... Here is an example: from xml.parsers.sgmlop import SGMLParser, XMLParser, XMLUnicodeParser are the PyXML folks shipping the latest sgmlop? I'm pretty sure they've forked the code (there's no UnicodeParser in the effbot.org edition), and I have no idea how things work in the fork. /F -- http://mail.python.org/mailman/listinfo/python-list
REPOST: Re: Python becoming less Lisp-like
Tim == Tim Daneliuk [EMAIL PROTECTED] writes: Tim Except that in this case, removal will also complicate code Tim in some cases. Consider this fragment of Tkinter logic: Tim UI.CmdBtn.menu.add_command(label=MyLabel, Tim command=lambda cmd=cmdkey: CommandMenuSelection(cmd)) Tim Would it not be the case that, without lambda, we will need Tim to pollute the name space with a bunch of specialized little Tim functions for each and every construct like this? You can reuse the same name for all those little functions to avoid polluting the namespace. Choose 'L' if it gives you that cozy lambda-ish feel. -- Ville Vainio http://tinyurl.com/2prnb -- http://mail.python.org/mailman/listinfo/python-list
REPOST: Re: Python becoming less Lisp-like
Torsten == Torsten Bronger [EMAIL PROTECTED] writes: There would be keywords for static and class methods, no distinction between Unicode and non-Unicode You couldn't do that 15 years ago because there were no Unicode that time. Torsten I've never said that Guido was just too stupid at that Torsten time. I only said but you can definitely see that it's Torsten the oldest one. In other words, a Ruby six years older Torsten than the real one would have the same problem. And who Torsten knows how C# looks like in 10 years. http://c2.com/cgi/wiki?PythonVsRuby seems to suggest that Python has better Unicode support than Ruby. -- Ville Vainio http://tinyurl.com/2prnb -- http://mail.python.org/mailman/listinfo/python-list
Simple account program
Hello all, I am still needing some help on this code, I have gone a bit further on it. Thank you for the help. I am trying to understand how to make the file searchable and how I am to make the deposit and withdrawl interact with the transaction class. I need to just search the file only for the deposits and withdrawls and the amount in the account with a time stamp. Thank you for your assistance. class Account: def __init__(self, initial): self.balance = initial def deposit(self, amt): self.balance = self.balance + amt def withdraw(self, amt): self.balance = self.balance - amt def getbalance(self): return self.balance class Transactoin: def transaction(self, self.transaction = import time time.asctime() raw_input(Is this a deposit or withdrawl?) if withdrawl: elif raw_input(Please enter amount here.) class Deposit(Transaction): def deposit(self, amt): self.balance = self.balance + amt def getbalance(self): return self.balance class Withdrawl(Trasaction): def withdrawl(self, amt): self.balance = self.balance - amt def getbalance(self): return self.balance import pickle pickle.dump ((withdrawl), file ('account.pickle', 'w')) pickle.dump ((deposit), file ('account.pickle', 'w')) print Your current account total is., self.balance -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting current variable name
Ron wrote: def getvinfo(vars, v): vars is locals() v is [varable] Use an one item list to pass single varables by reference. for n in vars.keys(): if vars[n] is v[0]: return n, v[0], type(v[0]) a = 101 b = 2.3 c = True print getvinfo(locals(), [a]) print getvinfo(locals(), [b]) print getvinfo(locals(), [c]) ('a', 101, type 'int') ('b', 2.2998, type 'float') ('c', True, type 'bool') Are you sure that you really need that single-element list? def getvinfo2(vars, v): ... for n in vars.keys(): ... if vars[n] is v: ... return n, v, type(v) ... getvinfo2(locals(), a) ('a', 1, type 'int') getvinfo2(locals(), b) ('b', 2.2998, type 'float') Now, making that second parameter a list would enable you to do this for multiple local names with a single call, but getvinfo() doesn't try to do that... Don't forget, in Python, all names are references. You only have to be careful when you start re-binding names... Jeff Shannon -- http://mail.python.org/mailman/listinfo/python-list
Memory mapped File (Python win32 extensions)
Hello, I see that it is possible to use mmapfile.pyd of win32all. The same is mentioned in http://www.python.org/windows/win32/#mmapfile. Unfortunately I could not trace any example using mmapfile. Any example or link to an example will be of help. I am interested to learn how to achieve efficient sharing of data between separate processes using mmapfile. Regards, /Srijit -- http://mail.python.org/mailman/listinfo/python-list
Re: sgmlop: malformed charrefs?
In article [EMAIL PROTECTED], Fredrik Lundh wrote: [snip] are the PyXML folks shipping the latest sgmlop? I don't know. The last history entry marked fl is from 2000-07-05... Perhaps I should just get the effbot version. (And perhaps file a bug report about this behaviour in PyXML.) I'm pretty sure they've forked the code (there's no UnicodeParser in the effbot.org edition), Does it deal with Unicode at all? I.e., can I, for example, feed it a Unicode object? and I have no idea how things work in the fork. I see. -- Magnus Lie Hetland Time flies like the wind. Fruit flies http://hetland.org like bananas. -- Groucho Marx -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting current variable name
There should be an easier way that doesn't require stepping though the name list. Trying to find names bound to a particular object is a /very/ strange thing to want to do in Python. If this is for anything more than debugging diagnostics, it's probably better to use a dictionary explicitly for your variables and not muck around with global or local namespace. -- http://mail.python.org/mailman/listinfo/python-list
RE: How to create datetime object from DbiDate (win32.odbc)?
Frank Millman wrote: I am using odbc from win32 extensions to connect to MS SQL Server. I use mx.DateTime to handle dates. When I select a datetime column from the database, odbc returns something called a DbiDate object. I cannot find out any information on this type, but mx can convert it to a mx.DateTime object using DateTimeFrom(), which is really all that I need. I am looking into changing from mx.DateTime to using the builtin datetime type, but I cannot figure out how to convert a DbiDate object to a datetime object. First prize would be to have a datetime constructor that takes a DbiDate object as input, in the same way that mx does, but this does not seem to exist. Try: datetime.datetime.utcfromtimestamp(int(value)) I gave up on dbiDates completely, however, (since their range is so limited) and use strings instead. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] No virus found in this outgoing message, because: 1) it's plain text, and 2) doesn't have an attachment. Checked by Common-Sense Anti-Virus, Version: 0.0.001 -- http://mail.python.org/mailman/listinfo/python-list
newbie:unique problem
I have a function uniqueList that is below : Def uniqueList(origList): nodups= {} for temp in origList: nodups[temp] = None returns nodups.keys() When used in the following context : industryList = uniqueList(jpbarradata[group]) where jpbarradata[group] might look like [AAA BC,BBB KK,CCC TD,AAA KP,CCC TD] ,the function works in the sense that it would return [AAA BC,BBB KK,CCC TD,AAA KP] because CCC TD is duplicated. But, I also want it to get rid of the AAA KP because there are two AAAs even though the last two letters are different. It doesnt matter to me which one is gotten rid of but I dont know how to change the function to handle this ? I have a feeling its not that hard though ? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Memory mapped File (Python win32 extensions)
Srijit Kumar Bhadra [EMAIL PROTECTED] writes: Hello, I see that it is possible to use mmapfile.pyd of win32all. The same is mentioned in http://www.python.org/windows/win32/#mmapfile. Unfortunately I could not trace any example using mmapfile. Any example or link to an example will be of help. I am interested to learn how to achieve efficient sharing of data between separate processes using mmapfile. You can even create a shared memory mapped file for sharing data between processes on Windows in pure Python. It's not really obvious from the mmap description, but calling shmem = mmap.mmap(0, 32000, spam) creates (or opens, if it already exists) a shared memory block, not based an any existing file. In other words, the fileno (first parameters) must be 0, and the last one specifies the system wide name of the shared memory block. Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python like VB?
Eric3 has been compiled for Windows, without Cygwin and Without a commercial license -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython vs. pyQt
so is there already a binary for qt/pyqt/eric3 available or when can i excpect qt4 to be released? I think that pyqt4 is going to be a long way off, obviously further away than qt4. i have compiled qt 3.3.3/pyqt 3.1.3 using mingw/vcc6 for windows using the instructions i linked to in my previous post, both for python 2.3 and 2.4, when the kde-cygwin guys finish porting qt 3.3.4, i'm going to have a go at pyqt 3.1.4 -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting current variable name
Jeff Shannon wrote: Are you sure that you really need that single-element list? No I'm not sure, I thought I found a concdition where it made a difference while playing with it, but I don't recall just what circumstance it was? Don't forget, in Python, all names are references. You only have to be careful when you start re-binding names... Since more than one name can bind to an object, this would be better. def getvinfo( vars, v ): names = [] for n in vars.keys(): if vars[n] is v: names.append(n) return names, v, type(v) a = [2] b = [2] c = b print getvinfo( locals(), a ) print getvinfo( locals(), b ) print getvinfo( locals(), c ) (['a'], [2], type 'list') (['b', 'c'], [2], type 'list') (['b', 'c'], [2], type 'list') -- http://mail.python.org/mailman/listinfo/python-list
Experienced Programmer needed to work on Python related projects
Internet/Web Application Developers Our client is a fast-growing and very successful player in the Internet space. Their particular expertise is with on-demand email hosting. They are looking for several excellent software engineers to help create the next generation of messaging solutions. Ideal candidate will LOVE to codeespecially new development. This is a multi-platform environment, but Unix and /or Linux as well as Python are required. Individual must also have a proven background in building Internet or web-based applications. This is a great opportunity for those programmers who like to play with the latest and greatest development tools and applications. Location is in the Blacksburg area and compensation and benefits package is excellent. These are for immediate hire and are permanent positions. If you are interested or know anyone who may be, please contact: Marisa Sano Market Research Analyst MBA Management, Inc 540-998-8954 [EMAIL PROTECTED] Marisa Sano MBA Management, Inc. Blacksburg, VA 540-998-8954 [EMAIL PROTECTED] Visit our website ~~ APPLY ONLINE! www.mbamgmt.com -- http://mail.python.org/mailman/listinfo/python-list
list of unique non-subset sets
Hi, I have many set objects some of which can contain same group of object while others can be subset of the other. Given a list of sets, I need to get a list of unique sets such that non of the set is an subset of another or contain exactly the same members. Tried to do the following: s1=set(['a','b','c']) s2=set(['a','c']) s3=set(['a','d','e','f']) s4=set(['r','k','l']) s5=set(['r','k','l']) L=[s1,s2,s3,s4,s5] --- cleaned-up list should contain s1, s3, s5 Lu=[] # unique list of sets Lu.append( L[0] ) for i in range(1,len(L)): s=L[i] # check for equality if s in L: continue # check for subseting for j in len(Lu): s1=Lu[j] if len (s-s1)==0: continue elif len(s1-s)==0: Lu[i]=s1 # replace with the bigger But this does not work since I get Lu=[set(['a', 'c', 'b'])] What am I doing wrong? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python like VB?
Hi! People coming from VB background probably also appreciate the ability to draw the UI in pointclick style: http://gazpacho.sicem.biz/ http://wxglade.sourceforge.net/ Unfortunately these seem to still be a tad rough around the edges... wxGlade is a port of Glade (which is designed for GTK+) to wx. But Glade is still the best and can be used very well with PyGTK (I prefer using PyGTK on Windows than wxPython). http://glade.gnome.org greets, Marek -- http://mail.python.org/mailman/listinfo/python-list
Re: list of unique non-subset sets
[EMAIL PROTECTED] wrote: Hi, I have many set objects some of which can contain same group of object while others can be subset of the other. Given a list of sets, I need to get a list of unique sets such that non of the set is an subset of another or contain exactly the same members. Tried to do the following: s1=set(['a','b','c']) s2=set(['a','c']) s3=set(['a','d','e','f']) s4=set(['r','k','l']) s5=set(['r','k','l']) L=[s1,s2,s3,s4,s5] --- cleaned-up list should contain s1, s3, s5 py s1 = set(['a','b','c']) py s2 = set(['a','c']) py s3 = set(['a','d','e','f']) py s4 = set(['r','k','l']) py s5 = set(['r','k','l']) py lst = [s1, s2, s3, s4, s5] py uniqlst = [] py for lstset in lst: ... for uniqlstset in uniqlst: ... if lstset.issubset(uniqlstset): ... break ... else: ... uniqlst.append(lstset) ... py uniqlst [set(['a', 'c', 'b']), set(['a', 'e', 'd', 'f']), set(['k', 'r', 'l'])] Not horribly efficient, mind you. But I believe it's correct. I basically took your description Given a list of sets, I need to get a list of unique sets such that non[e] of the set[s] is an subset of another and translated that to code. So I iterate through each element in lst, and and only add that element to uniqlst if it's not a subset of any of the items already in uniqlst. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: list of unique non-subset sets
[EMAIL PROTECTED] I have many set objects some of which can contain same group of object while others can be subset of the other. Given a list of sets, I need to get a list of unique sets such that non of the set is an subset of another or contain exactly the same members. Tried to do the following: s1=set(['a','b','c']) s2=set(['a','c']) s3=set(['a','d','e','f']) s4=set(['r','k','l']) s5=set(['r','k','l']) L=[s1,s2,s3,s4,s5] --- cleaned-up list should contain s1, s3, s5 This should do the trick: result = [] for s1 in L: for s2 in result: if s1 = s2: break else: result.append(s1) print result Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list
metaclass error
dear readers, i have a very simple package organized as follows: !-! bgp/ __init__.py managers/ __init__.py ManagerInterface.py TestManager.py !-! and here's ManagerInterface.py and TestManager.py: !-! # ManagerInterface.py class ManagerInterface(object): def __init__(self): pass def process(self, recset, operation): print 'In ManagerInterface.process()...' # TestManager.py import ManagerInterface class TestManager(ManagerInterface): def process(self, recset, operation): print 'In TestManager.process()...' super(TestManager,self).process(recset,operation) !---! when i try to import the TestManager module via the interpreter, i get the following error: !---! $ python Python 2.4.1c1 (#1, Mar 14 2005, 10:28:18) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-49)] on linux2 import bgp.managers.TestManager Traceback (most recent call last): File stdin, line 1, in ? File bgp/managers/TestManager.py, line 2, in ? class TestManager(ManagerInterface): TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) !---! any thoughts? i think that when python executes the TestManager class statement, it collects the base class (ManagerInterface) into a tuple and then executes the class body in a dictionary... is this where the error is happening? thanks! aaron -- http://mail.python.org/mailman/listinfo/python-list
Re: metaclass error
Le 17 Mar 2005 12:27:07 -0800, [EMAIL PROTECTED] a écrit : dear readers, i have a very simple package organized as follows: !-! bgp/ __init__.py managers/ __init__.py ManagerInterface.py TestManager.py !-! and here's ManagerInterface.py and TestManager.py: !-! # ManagerInterface.py class ManagerInterface(object): def __init__(self): pass def process(self, recset, operation): print 'In ManagerInterface.process()...' # TestManager.py import ManagerInterface # ManagerInterface is a module not a class ! # try from ManagerInterface import ManagerInterface class TestManager(ManagerInterface): # you can also define __init__ method with a super call def process(self, recset, operation): print 'In TestManager.process()...' super(TestManager,self).process(recset,operation) !---! thanks! aaron -- http://mail.python.org/mailman/listinfo/python-list
metaclass error
hi, i have a very simple package organized as follows: !-! bgp/ __init__.py managers/ __init__.py ManagerInterface.py TestManager.py !-! and here's ManagerInterface.py and TestManager.py: !-! # ManagerInterface.py class ManagerInterface(object): def __init__(self): pass def process(self, recset, operation): print 'In ManagerInterface.process()...' # TestManager.py import ManagerInterface class TestManager(ManagerInterface): def process(self, recset, operation): print 'In TestManager.process()...' super(TestManager,self).process(recset,operation) !---! when i try to import the TestManager module via the interpreter, i get the following error: !---! $ python Python 2.4.1c1 (#1, Mar 14 2005, 10:28:18) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-49)] on linux2 import bgp.managers.TestManager Traceback (most recent call last): File stdin, line 1, in ? File bgp/managers/TestManager.py, line 2, in ? class TestManager(ManagerInterface): TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) !---! any thoughts? i think that when python executes the TestManager class statement, it collects the base class (ManagerInterface) into a tuple and then executes the class body in a dictionary... is this where the error is happening? thanks! aaron -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie:unique problem
Leeds, Mark said unto the world upon 2005-03-17 14:08: I have a function uniqueList that is below : Def uniqueList(origList): nodups= {} for temp in origList: nodups[temp] = None returns nodups.keys() When used in the following context : industryList = uniqueList(jpbarradata[group]) where jpbarradata[group] might look like [AAA BC,BBB KK,CCC TD,AAA KP,CCC TD] ,the function works in the sense that it would return [AAA BC,BBB KK,CCC TD,AAA KP] because CCC TD is duplicated. But, I also want it to get rid of the AAA KP because there are two AAA's even though the last two letters are different. It doesn't matter to me which one is gotten rid of but I don't know how to change the function to handle this ? I have a feeling it's not that hard though ? Thanks. Hi Mark, please turn off the HTML formatting when posting. It makes your message quite a lot bigger than need be, and, in this case anyway, makes the plain text version doubled spaced (as above) and thus a bit nasty to read. Thanks. For the question: Is order in your output important? If so, I wouldn't use a dictionary to store the unique items. I see why you did it, but since dictionaries don't have order, your output might get permuted. How about this (don't take the naming as a model!): def unique_up_to_n_char(orig_list, n): '''- list of elements where each is unique up to the first n chars. ''' # Needs Python 2.4 for set type. You could use a list, too. seen_leading_chars = set() output_list = [] for member in orig_list: if member[:n] not in seen_leading_chars: seen_leading_chars.add(member[:n]) output_list.append(member) return output_list test_list = [AAA BC, BBB KK, CCC TD, AAA KP, CCC TD, AAB KP] print unique_up_to_n_char(test_list, 3) print unique_up_to_n_char(test_list, 2) which produces: ['AAA BC', 'BBB KK', 'CCC TD', 'AAB KP'] ['AAA BC', 'BBB KK', 'CCC TD'] There may be still better ways. But, this is general and preserves order. Best, Brian vdB -- http://mail.python.org/mailman/listinfo/python-list
Re: metaclass error
doh, that was the problem. :} thanks for the help! aaron -- http://mail.python.org/mailman/listinfo/python-list
Re: list of unique non-subset sets
Raymond Hettinger wrote: [EMAIL PROTECTED] I have many set objects some of which can contain same group of object while others can be subset of the other. Given a list of sets, I need to get a list of unique sets such that non of the set is an subset of another or contain exactly the same members. Tried to do the following: s1=set(['a','b','c']) s2=set(['a','c']) s3=set(['a','d','e','f']) s4=set(['r','k','l']) s5=set(['r','k','l']) L=[s1,s2,s3,s4,s5] --- cleaned-up list should contain s1, s3, s5 This should do the trick: result = [] for s1 in L: for s2 in result: if s1 = s2: break else: result.append(s1) print result If I understand the original post correctly, you also need to check for an existing set being a subset of the set you are adding. A better test case is s1=set(['a','b','c']) s2=set(['a','c']) s3=set(['a','d','e','f']) s4=set(['r','k','l']) s5=set(['r','k','l']) s6=set(['g', 'h']) s7=set(['h', 'i']) s8=set(['g', 'h', 'i']) L=[s1,s2,s3,s4,s5,s6,s7,s8] # --- cleaned-up list should contain s1, s3, s5, s8 which both Raymond and STeVe's proposals fail. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create datetime object from DbiDate (win32.odbc)?
Frank Millman wrote: Hi all I am using odbc from win32 extensions to connect to MS SQL Server. I use mx.DateTime to handle dates. When I select a datetime column from the database, odbc returns something called a DbiDate object. I cannot find out any information on this type, but mx can convert it to a mx.DateTime object using DateTimeFrom(), which is really all that I need. I am looking into changing from mx.DateTime to using the builtin datetime type, but I cannot figure out how to convert a DbiDate object to a datetime object. First prize would be to have a datetime constructor that takes a DbiDate object as input, in the same way that mx does, but this does not seem to exist. Second prize would be to extract the year/month/day elements from the DbiDate object, and construct the datetime object manually. However, if I try dir(d), where d is a DbiDate object, I get an empty list, so I cannot even see how to extract the elements. Does anyone know if this is possible, and if so, how? Many thanks Frank Millman I've always used from mx.DateTime import DateTimeFromCOMDate t=DateTimeFromCOMDate(dbidate) Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing C readable bitfield structs?
Anyone have any idea? [EMAIL PROTECTED] wrote: Roy Smith wrote: In article [EMAIL PROTECTED], Cappy2112 [EMAIL PROTECTED] wrote: there is a bitfiled mainpulator class inthe Cookbook, but I don't understand his explanation, and the example given doesn't really show off the features of the class. I assume you're talking about the struct module? If you give an example of the C struct you're trying to read/write, I could come up with some sample code to do it. struct S { unsigned int a : 1; unsigned int b : 1; unsigned int c : 1; unsigned int d : 1; }; fread(from file (file written by Python app) into an instance of struct S) then I want it to be used as follows: if (instance.a) f(); if (instance.b) g(); struct S comes out to 4 on my arch. I do not want to use a new int for every member of struct S. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple account program
Igorati, I wished I could give you a simple fix, BUT... You need to really re-read the docs and do some tutors first . Your understanding of classes and namespaces is flawed and will not become clear without futher study. search strategy: python namespaces python class python tutor Classes are like containers. Classes have there own namespace, self. Multiple classes do not share namespaces. Stay away from inheritance till you have an understanding of namespace, no need in getting mixed up. Withdrawl, Deposit, Transaction should be members of the account class. That way they can share a namespace and simplify your design. Why do you need to search a pickle? Pickle an instance of the class and unpickle it when needed and your data will be however it was in your instance. If you have real code post it because this code does not work and never will. Quit posting homework, you can ask for occasional help, but this is the third time i have seen this, it is getting worse and you have been warned before ;) Surely in the month since you first asked you could have read a bit of documentation. # this is not complete or even tested it is just an example ( based on your code ) import time class Account: def __init__(self, initial): self.balance = initial self.history = {} def deposit(self, amt): self.balance = self.balance + amt self.save('deposit',amt) def withdraw(self, amt): self.balance = self.balance - amt self.save('withdrawl', amt) def getbalance(self): return self.balance def gethistory(self): return self.history def save(self,trans,amount): # store the transaction type, amount, balance self.history[self.timestamp()] = (trans,amount,self.balance) def timestamp(self): return time.asctime() def transaction(self): withdrawl = raw_input(Is this a deposit or withdrawl?) amount = raw_input(Please enter amount here.) if withdrawl.lower() in [withdrawl,w]: self.withdraw(amount) else: self.deposit(amount) hth, M.E.Farmer -- http://mail.python.org/mailman/listinfo/python-list
Re: list of unique non-subset sets
Kent Johnson wrote: Raymond Hettinger wrote: [EMAIL PROTECTED] I have many set objects some of which can contain same group of object while others can be subset of the other. Given a list of sets, I need to get a list of unique sets such that non of the set is an subset of another or contain exactly the same members. Tried to do the following: s1=set(['a','b','c']) s2=set(['a','c']) s3=set(['a','d','e','f']) s4=set(['r','k','l']) s5=set(['r','k','l']) L=[s1,s2,s3,s4,s5] --- cleaned-up list should contain s1, s3, s5 This should do the trick: result = [] for s1 in L: for s2 in result: if s1 = s2: break else: result.append(s1) print result If I understand the original post correctly, you also need to check for an existing set being a subset of the set you are adding. A better test case is s1=set(['a','b','c']) s2=set(['a','c']) s3=set(['a','d','e','f']) s4=set(['r','k','l']) s5=set(['r','k','l']) s6=set(['g', 'h']) s7=set(['h', 'i']) s8=set(['g', 'h', 'i']) L=[s1,s2,s3,s4,s5,s6,s7,s8] # --- cleaned-up list should contain s1, s3, s5, s8 which both Raymond and STeVe's proposals fail. Can you just do: py def uniq(lst): ... result = [] ... for s1 in sorted(lst, reverse=True): ... for s2 in result: ... if s1 = s2: ... break ... else: ... result.append(s1) ... return result ... py lst = [set(['a','b','c']), ...set(['a','c']), ...set(['a','d','e','f']), ...set(['r','k','l']), ...set(['r','k','l']), ...set(['g', 'h']), ...set(['h', 'i']), ...set(['g', 'h', 'i'])] py uniq(lst) [set(['a', 'c', 'b']), set(['a', 'e', 'd', 'f']), set(['k', 'r', 'l']), set(['i', 'h', 'g'])] Haven't thought about it too hard though... STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie:unique problem
On Thursday 17 March 2005 20:08, Leeds, Mark wrote: But, I also want it to get rid of the AAA KP because there are two AAA's even though the last two letters are different. It doesn't matter to me which one is gotten rid of but I don't know how to change the function to handle this ? I have a feeling it's not that hard though ? Thanks. Doing the same thing Brian van den Brook did with sets (also for 2.4 only): def uniqueItems(oldlist,comppos=3): rv = {} for i in reversed(oldlist): rv[i[:comppos]] = i return rv.values() uniqueItems([AAA BC,BBB KK,CCC TD,AAA KP,CCC TD]) ['AAA BC', 'BBB KK', 'CCC TD'] [EMAIL PROTECTED] ~ $ python2.4 /usr/local/lib/python2.4/timeit.py -s import test; uniqueItems = test.uniqueItems; uniqueItemsBrian = test.uniqueItemsBrian uniqueItemsBrian(uniqueItems) 10 loops, best of 3: 13.8 usec per loop [EMAIL PROTECTED] ~ $ python2.4 /usr/local/lib/python2.4/timeit.py -s import test; uniqueItems = test.uniqueItems; uniqueItemsHeiko = test.uniqueItemsHeiko uniqueItemsHeiko(uniqueItems) 10 loops, best of 3: 9.28 usec per loop Seems like the dictionary solution is faster, at least for n=3. Do your own tests... ;) -- --- Heiko. pgp7Ajb86UhaT.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list