CodeInvestigator version 0.7.3
CodeInvestigator version 0.7.3 was released on February 21. This release fixes a bug. When a user views code and closes the view of a variable value, the marker-bar on the right side of the window shows. This bar should only show when a user scrolls away from code. CodeInvestigator is a tracing tool for Python programs. Running a program through CodeInvestigator creates a recording. Program flow, function calls, variable values and conditions are all stored for every line the program executes. The recording is then viewed with an interface consisting of the code. The code can be clicked: A clicked variable displays its value, a clicked loop displays its iterations. You read code, and have at your disposal all the run time details of that code. A computerized desk check tool and another way to learn about your program. http://sourceforge.net/project/showfiles.php?group_id=183942 -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Python Bug Day on Feb. 23
After the success of January's bug day, which closed 37 issues, we're having another one this Saturday, February 23 2008. We'll all meet in the #python-dev IRC channel on irc.freenode.net and help improve Python. For more information, see http://wiki.python.org/moin/PythonBugDay . This is a good opportunity to get your feet wet in developing the Python core. --amk -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Is there a way to link a python program from several files?
On Feb 21, 1:58 am, [EMAIL PROTECTED] (Edward A. Falk) wrote: In article [EMAIL PROTECTED], BlueBird [EMAIL PROTECTED] wrote: I wrote a small wiki page to sum-up my findings about such typical problem: http://www.freehackers.org/Packaging_a_python_program Excellent references, but maybe a bit of overkill. Everybody in my target audience has python on their systems, I just want to send a single .py (or .pyc) file so there's no complicated install procedure. What's so complicated about python setup.py install ? Even that is not strictly necessary for pure python packages; a user may just unpack the archive, cd to the extracted directory and execute the appropriate .py file(s). George -- http://mail.python.org/mailman/listinfo/python-list
Re: is this data structure build-in or I'll have to write my own class?
mkPyVS wrote: This isn't so optimal but I think accomplishes what you desire to some extent... I *think* there is some hidden gem in inheriting from dict or an mapping type that is cleaner than what I've shown below though. class dum_struct: def __init__(self,keyList,valList): self.__orderedKeys = keyList self.__orderedValList = valList def __getattr__(self,name): return self.__orderedValList[self.__orderedKeys.index(name)] keys = ['foo','baz'] vals = ['bar','bal'] m = dum_struct(keys,vals) print m.foo Let's add: __getitem__(self, key): return self.__orderedValList[key] in order to have: m.foo == m[0] RB -- http://mail.python.org/mailman/listinfo/python-list
Re: Double underscores -- ugly?
On Feb 21, 3:31 am, [EMAIL PROTECTED] wrote: On Feb 19, 8:20 pm, Steve Holden [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: On Feb 19, 10:26 am, Wildemar Wildenburger [EMAIL PROTECTED] wrote: Jason wrote: Hmm. I must be the only person who doesn't think the double underscores are ugly. Nope. I like them too. :) Frankly, I think it's just a matter of adaption. I too found it rather ugly in the beginning, but with anything, I've gotten used to it. (And I wholeheartedly support your looks like underlined / is unintrusive like whitespace argument.) /W My editor actually renders them as miniature chess pieces. The bartender said she runs a pre-execution step, that searches and replaces a double-colon with the underscores. If you're taking programming advice from a bartender your postings suddenly start to make sense (though not, unfortunately, as comments about programming). Do you think perhaps yo might be trying just a little too hard? regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/-Hide quoted text - - Show quoted text - It's definitely possible. I've been hacking the code for some time, and so far, the furthest I've gotten is: bartender.think() Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'Bartender' object has no attribute 'think' Any ideas? You need to pass it a parameter for .drink() which in turn calls the .pay() function, before it can .think() -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to link a python program from several files?
Edward A. Falk schrieb: In article [EMAIL PROTECTED], BlueBird [EMAIL PROTECTED] wrote: I wrote a small wiki page to sum-up my findings about such typical problem: http://www.freehackers.org/Packaging_a_python_program Excellent references, but maybe a bit of overkill. Everybody in my target audience has python on their systems, I just want to send a single .py (or .pyc) file so there's no complicated install procedure. I mean, how *are* large python programs normally distributed under Linux? By means of their package management. At least that's what many people prefer. But I don't get what's wrong with you: python setup.py bdist_egg your client: easy_install the.egg Diez -- http://mail.python.org/mailman/listinfo/python-list
wxPython Plot always comes to focus on redraw
Hi. I am using wxPython, and I have a frame that has a notebook in it. there are 3 pages in the notebook, 2 of which are Panels and 1 of which is a PlotCanvas. The data for the plot changes when I press a button that is in the frame, but not in the notebook (as designed). the button also makes the plot draw again, since the data has changed. The problem is that whenever I press my button, the focus of the notebook view area (as opposed to the tabs) changes focus to the plot. if I have multiple plots, the focus goes to that plot which was drawn last in the code. however, if I click anywhere on the panel, the page of the notebook that is supposed to be in focus is now shown in the view area of the notebook. will try to make a sample .py if anybody needs a visual, let me know pls. Thanks for any help! Jake -- http://mail.python.org/mailman/listinfo/python-list
Re: using PIL for PCA analysis
Hi, You should convert your data to numpy and make it 1D (for the moment, it is 3D) by calling the ravel() method. Then you can create your covariance matrix ;) Matthieu 2008/2/21, [EMAIL PROTECTED] [EMAIL PROTECTED]: hi guys i am trying out PCA analysis using python.I have a set of jpeg(rgbcolor) images whose pixel data i need to extract and make a matrix .( rows =num of images and cols=num of pixels) For this i need to represent an image as an array. i was able to do this using java's BufferedImage as below javacode int[] rgbdata = new int[width * height]; image.getRGB(0,0,width,height,rgbdata,0,width); doubles = new double[rgbdata.length]; int i; for ( i = 0; i bytes.length; i++) { doubles[i] = (double)(rgbdata[i]); } /javacode this doubles[] now represent a single image's pixels then i can get a matrix of say 4 images ..(each of 4X3 size) sampledata images[][] rows=4,cols=12 [ [-4413029.0, -1.0463919E7,... -5201255.0] [-5399916.0, -9411231.0, ... -6583163.0] [-3886937.0, -1.0202292E7,... -6648444.0] [-5597295.0, -7901339.0,... -5989995.0] ] /sampledata i can normalise the above matrix to zeromean and then find covariance matrix by images * transpose(images) my problem is how i can use PIL to do the same thing..if i extract imagedata using im.getdata() i will get sampledata [ [(188, 169, 155), (96, 85, 81),.. (176, 162, 153)] [(173, 154, 148), (112, 101, 97),.. (155, 140, 133)] [(196, 176, 167), (100, 83, 76), ... (154, 141, 132)] [(170, 151, 145), (135, 111, 101), ... (164, 153, 149)] ] /sampledata i donot know how to find covariance matrix from such a matrix..it would'v been ideal if they were single values instead of tuples..i can't use greyscale images since the unput images are all rgb jpeg can someone suggest a solution? thanks dn -- http://mail.python.org/mailman/listinfo/python-list -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -- http://mail.python.org/mailman/listinfo/python-list
Replacing 'if __name__ == __main__' with decorator (was: Double underscores -- ugly?)
On Feb 19, 10:01 am, Duncan Booth [EMAIL PROTECTED] wrote: Berwyn [EMAIL PROTECTED] wrote: Is it just me that thinks __init__ is rather ugly? Not to mention if __name__ == '__main__': ...? That ugliness has long been my biggest bugbear with python, too. The __name__ == '__main__' thing is something I always have to look up, every time I use it, too ... awkward. I'd settle for: hidden def init(self): # which could be extended to work for everything hidden x=3 ... And for __name__ == '__main__' how about: if sys.main(): ... Or even: @hidden def init(self): ... @main def mymainfunc(): ... The first of those probably wants some metaclass support to make it work cleanly, but here's a sample implementation for the second one: import sys, atexit def main(f): Decorator for main function def runner(): sys.exit(f()) if f.func_globals['__name__']=='__main__': atexit.register(runner) return f print define mymainfunc @main def mymainfunc(args=sys.argv): print Got args, args return 3 print end of script If you have multiple functions marked as main that will run them in reverse order, so it might be better to put them on a list and use a single runner to clear the list. Also, I have no idea what happens to the exit code if you use this decorator more than once. BTW, should anyone be wondering, you can still use atexit inside a function called from atexit and any registered functions are then called when the first one returns. I liked the idea, thanks. But I also wanted to be able to pass options to the decorator, for example optparser.OptionParser instances, so (after wrestling with nested functions for half a day!) I ended up with the class below, FWIW. Getting the interplay between __new__, __init__ and __call__ was somewhat trial-and-error, and maybe I just painted myself into a corner, but (slightly academic question) is it the case that if you want to be able to use a decorator both with and without options, ie. like this: @mainmethod def main(...) and like this: @mainmethod(parser=myparser) def main(...) then you cannot use that decorator for a function that expects or allows a function as its first argument? Because how and when can you decide whether that function is the decorated one or the function parameter? Anyway, thanks again. [code] class mainmethod(object): _parser = None kwargs = {} args =() def _getparser(self): if self._parser is None: self._parser = CommonOptionParser() return self._parser parser = property(_getparser) def __new__(cls, *args, **kw): obj = super(mainmethod, cls).__new__(cls, *args, **kw) if len(args) == 1 and inspect.isfunction(args[0]): #we assume that the decorator has been declared with no arguments, #so go to straight to __call__, don't need __init__ #if it's the case that the wrapped 'main' method allows or #expects a function as its first (and only) positional argument #then you can't use this decorator return obj(args[0]) else: return obj def __init__(self, *args, **kw): self.args = args self._parser = kw.pop('parser', None) self.kwargs = kw def _updatekwargs(self, dict): #don't want default null values of parser to overwrite anything #passed to `mainmethod` itself for k,v in dict.iteritems(): #can't do 'if v: ...' because empty configobj evaluates False if v is None or v == '': continue self.kwargs[k] = v def exit(self): try: log.end() except: pass def run(self): options, args = self.parser.parse_args() #the following so that command line options are made available #to the decorated function as **kwargs self._updatekwargs(self.parser.values.__dict__) logargs = ( self.kwargs.get(OPTLOGFILE, None), self.kwargs.get(OPTLOGDIR, None), self.kwargs.get(OPTLOGPREFIX, ''), ) self.kwargs[OPTLOGFILE] = logstart(*logargs) log.info(SCRIPT: + sys.argv[0]) conf = self.kwargs.get(OPTCONFIG, None) if conf: log.info(%s: %s % (OPTCONFIG.upper(), conf.filename)) for k,v in self.kwargs.iteritems(): if v and k not in COMMONOPTS: log.info(%s = %s % (k, v)) log.divider() return sys.exit(self.func(*self.args, **self.kwargs)) def __call__(self, f): if f.func_globals['__name__'] == '__main__': self.func = f import atexit atexit.register(self.exit) atexit.register(self.run) return f [/code] Gerard -- http://mail.python.org/mailman/listinfo/python-list
Re: Article of interest: Python pros/cons for the enterprise
Carl Banks a écrit : On Feb 20, 8:58 am, Tim Chase [EMAIL PROTECTED] wrote: You Used Python to Write WHAT? http://www.cio.com/article/185350 Furthermore, the power and expressivity that Python offers means that it may require more skilled developers. [...down to the summary...] Python may not be an appropriate choice if you: [...] * Rely on teams of less-experienced programmers. These developers may benefit from the wider availability of training for languages like Java and are less likely to make mistakes with a compile-time, type-checked language. (snip) C++ is a compile-time, type-checked language, which means it is totally safer for newbies than Python. Yep, your big company is totally safe with newbie C++ programmers. Mouarf ! Brillant demonstration, thanks Carl !-) (and BTW, +1 QOTW) -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie in python
-On [20080221 11:56], [EMAIL PROTECTED] ([EMAIL PROTECTED]) wrote: Can someone help me to get in the right track, and get a good move? http://wiki.python.org/moin/BeginnersGuide -- Jeroen Ruigrok van der Werven asmodai(-at-)in-nomine.org / asmodai イェルーン ラウフロック ヴァン デル ウェルヴェン http://www.in-nomine.org/ | http://www.rangaku.org/ E pluribus unum... -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie in python
Can someone help me to get in the right track, and get a good move? http://wiki.python.org/moin/BeginnersGuide http://www.diveintopython.org/ -- http://mail.python.org/mailman/listinfo/python-list
newbie in python
Hi anyone I'm very interesed to learn python and really willing to do so,but unfortunately dont know where to start, or what programs need to install to start. Can someone help me to get in the right track, and get a good move? Thanks for all help pls reply on [EMAIL PROTECTED] or [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Backup Script over ssh
Hey all I am new to python and the list. I want to create backup script for my windows PC and upload to Linux server over ssh but whats the best way to go about this. Just want to copy the modified and new files up to server in folder that has Month/Year so every month new sync is created, but every day new files at midnight are uploaded. Can anyone help? Thanks -- Christian Kortenhorst -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie in python
[EMAIL PROTECTED] wrote: Hi anyone I'm very interesed to learn python and really willing to do so,but unfortunately dont know where to start, or what programs need to install to start. Can someone help me to get in the right track, and get a good move? Thanks for all help If you're a good student or you have prior programming experience, get the book 'Learning Python', which just came out with a 3rd edition, so it is the most up to date book. If you are not such a good student or have no prior programming experience, and you want a gentler introduction to python, check out the book 'Python Programming for the Absolute Beginner(2nd Ed.)' -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux/Python Issues
re being serious I am serious. I am seriously trying to develop a nice language for beginners. I was at Dartmouth in 1965 when BASIC was new. It let me use the computer without learning Fortran. It was very successful. I think it's past time for another one. I think we could have a lot more capability with more simplicity than you find in Visual Basic. re DLing source As a solution to the problem of wanting a program on my computer, it sucks. On Windows I'll DL an install package, accept a license agreement, click Next a few times (no, I can't make a cup of coffee because the minute I step away the Wizard will ask a question), ... With CNR the commitment is that I CAN walk away. I do not know who should be responsible for putting things in the warehouse. I do wish that the *n*x community would create some sensible standards so the 'our distro doesn't put things where others do' would stop being an issue. Looking in /usr/bin and its brethren makes c:\Program Files seem organized. re changing distros because apt-get could do the job I'll take your words for the superiority of Ubuntu. But I'll not change from one problem (can't find the python-devel that python.org says I need) to another (installing a new OS). I bought my Linspire computer with the OS installed. I've no interest in mastering the art of installing Linux. I'm a big fan of KDE, KATE and Konqueror and having a dozen desktops for a dozen projects. I do not miss crashes and viruses. I do not miss shelling out hundreds of bucks for an office suite. So for now I'll just pretend that Windows is desktop 13. A KVM helps. I'll remember that you don't type uptime in the DOS window. Oh, yeah. I'll remember that my NAV subscription expired. Gotta renew. -- http://mail.python.org/mailman/listinfo/python-list
Globals or objects?
I had a global variable holding a count. One source Google found suggested that I wouldn't need the global if I used an object. So I created a Singleton class that now holds the former global as an instance attribute. Bye, bye, global. But later I thought about it. I cannot see a single advantage to the object approach. Am I missing something? Or was the original global a better, cleaner solution to the I need a value I can read/write from several places problem? -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython Plot always comes to focus on redraw
Jacob Davis wrote: Hi. I am using wxPython, and I have a frame that has a notebook in it. there are 3 pages in the notebook, 2 of which are Panels and 1 of which is a PlotCanvas. The data for the plot changes when I press a button that is in the frame, but not in the notebook (as designed). the button also makes the plot draw again, since the data has changed. The problem is that whenever I press my button, the focus of the notebook view area (as opposed to the tabs) changes focus to the plot. if I have multiple plots, the focus goes to that plot which was drawn last in the code. however, if I click anywhere on the panel, the page of the notebook that is supposed to be in focus is now shown in the view area of the notebook. will try to make a sample .py if anybody needs a visual, let me know pls. Thanks for any help! Jake All wxWindow objects have a SetFocus() method. I am unsure why the system should be changing the focus (it's almost certainly something you are asking it to do without realizing), but the easiest way to proceed if you can't stop the focus from changing (i.e. remove the problem) is to call SetFocus() on the widget that you want to have the focus after you've finished (i.e. cure the symptom). Or perhaps it's just that I haven't understood the problem correctly. You probably didn't post the code because it's large (which is good). The correct action is to pare the program down to the smallest one you can make that demonstrates the problem, then post that. often during this process it becomes clear what the problem is! It may be that your widget relationships aren't as clean as they might be: did you produce your layout with an automated tool like wxDesigner or BoaConstrictor, or did you hack it together by hand? regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Globals or objects?
[EMAIL PROTECTED] wrote: I had a global variable holding a count. One source Google found suggested that I wouldn't need the global if I used an object. So I created a Singleton class that now holds the former global as an instance attribute. Bye, bye, global. But later I thought about it. I cannot see a single advantage to the object approach. Am I missing something? Or was the original global a better, cleaner solution to the I need a value I can read/write from several places problem? Look up coupling and cohesion in Wikipedia or similar, and you will find out that global variables are bad because they introduce tight coupling between different pieces of functionality in your code. If a function uses a global variable then you have to initialize the same global variable in another program that uses it: yet another piece of setup you will forget to do. Having said that, where are you storing the reference to the singleton instance? It wouldn't be a global, would it? regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: usenet problem
Jacob Davis [EMAIL PROTECTED] writes: Hi. I am a newbie to usenet. I am using mac and have downloaded a free usenet client, MT-NewsWatcher. I put in comp.lang.python but it says that it cannot get the address of the news server host. 'comp.lang.python' is the name of the newsgroup, not the name of a host (machine). Usenet newsgroups are accessible from many different machines worldwide, all of which propagate the messages to each other so that (ideally) any one group can be treated as a single group distributed across the world. URL:http://en.wikipedia.org/wiki/Usenet You need to access the newsgroup via one of those servers, called a news feed or Usenet provider. That server's hostname is what you need to configure your software to connect with. -- \ Rommel: Don't move, or I'll turn the key on this can of Spam! | `\ -- The Goon Show, _Rommel's Treasure_ | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux/Python Issues
On 21 Feb, 13:04, [EMAIL PROTECTED] wrote: re DLing source As a solution to the problem of wanting a program on my computer, it sucks. It doesn't suck if you're just installing one program, but if there are a lot of dependencies it can quickly suck, yes. Even with systems that comprehensively manage dependencies like Gentoo's Portage (and unlike language-specific solutions such as easy_install and the CPAN tools) the convenience can become quickly overwhelmed by practical concerns such as whether your computer has enough CPU time available to compile all the updates coming in. On Windows I'll DL an install package, accept a license agreement, click Next a few times (no, I can't make a cup of coffee because the minute I step away the Wizard will ask a question), ... With CNR the commitment is that I CAN walk away. I do not know who should be responsible for putting things in the warehouse. I do wish that the *n*x community would create some sensible standards so the 'our distro doesn't put things where others do' would stop being an issue. Looking in /usr/bin and its brethren makes c:\Program Files seem organized. You aren't supposed to look in those directories. ;-) There are proposals for application directories such as the one proposed by the author of ROX Desktop, but on Debian-based distributions, the warehouse is the sum of the available repositories. I'll agree that the interfaces to the warehouse aren't very good, however: for a while, the Kynaptic application (a simple version of Synaptic for Kubuntu) was a fairly simple but convenient tool to retrieve packages, but then the developers got feature envy and added the bloat from Synaptic in order to forge the Adept application: a tool whose usability is now regarded as suspect even by those involved in pushing it into Kubuntu in the first place. I think that the best way of promoting packages would be to adopt a Web-like paradigm, allowing people to surf around the warehouse, presumably like what CNR does now, but just browsing the available packages from standard repositories (and without all the shopping cart nonsense). This way, at least users would get their exciting surfing and downloading experience (although they'd really be selecting, not downloading as such) whilst not downloading possibly dubious binaries from arbitrary sites on the Internet. Indeed, alongside the dependency management, the whole trust aspect of distribution repositories is arguably their greatest strength, since people continue to believe that it's alright to just download and e-mail stuff to each other as long as my virus scanner is running - a foolish attitude that caused numerous problems in at least one environment I've worked in, presumably because everyone clicked on the funny program in the e- mail message that got sent round. re changing distros because apt-get could do the job I'll take your words for the superiority of Ubuntu. But I'll not change from one problem (can't find the python-devel that python.org says I need) to another (installing a new OS). I bought my Linspire computer with the OS installed. I've no interest in mastering the art of installing Linux. I'm a big fan of KDE, KATE and Konqueror and having a dozen desktops for a dozen projects. I do not miss crashes and viruses. I do not miss shelling out hundreds of bucks for an office suite. I think you've either got to find the direct line to the underlying repositories (and hope that they're more up-to-date than CNR), or you've got to face the problem that your distribution isn't going to provide packages of recent versions of Python and other things. Not that long ago, I was still happily running a distribution from 2005, but it was ultimately a case of either backporting steadily larger numbers of packages, or installing everything from source, and outside the Python scene there are a number of packages that you really don't want to be installing from source unless you're willing to make a large investment of time, with frustration being the most typical reward. Maybe there's room for a Python backports project for older distributions, like the proposal for making Windows installers for third-party extensions, but this requires a certain amount of infrastructure and isn't a one-person job. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Globals or objects?
Steve Holden [EMAIL PROTECTED] writes: If a function uses a global variable then you have to initialize the same global variable in another program that uses it: yet another piece of setup you will forget to do. If the global variable belongs to the module, then it is up to the module to initialize it. A different program program will simply import the same module and automatically get the same variable, properly initialized. One reason why a singleton's attribute may be better than a global variable is that it's easier to later add a callback when the value is changed without breaking the interface. A module cannot react to module.somevar = value; on the other hand, a singleton can implement __setattr__ that reacts to module.singleton.attr = value. -- http://mail.python.org/mailman/listinfo/python-list
Sending key-presses to other programs on Windows, and settings of controls?
Hi, I'm looking for ways to send keypresses to another application on Windows XP, and to set values of Windows Controls (all of them text-boxes). This is to try automate testing of the application. I think I've done things like that before from Python, but I don't remember for sure. Can this be done? Using the Win32-all extensions perhaps? Or perhaps with the CTypes module? Any pointers are appreciated! Kind regards, --Tim van der Leeuw -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding Priority Scheduling feature to the subprocess
On Feb 20, 10:15 pm, Terry Reedy [EMAIL PROTECTED] wrote: | Because UNIX uses priorities between +20 and -20 and Windows, via | Process and Thread priorities, allows settings between 0 and 31, a | uniform setting for each system should be derived. This would be | accomplished by giving process priority in terms of a floating-point | value between 0.0 and 1.0 for lowest and highest possible priority, | respectively. I would rather that the feature use the -20 to 20 priorities and map that appropriately to the Windows range on Windows. The problem as I see it is that -20 to +20 is only just over 5 bits of precision and I can easily imagine an OS with many more than just 5 bits to specify a process priority. Of course, the os.getpriority and os.setpriority, being specific to UNIX, WOULD use the -20 to +20 scale, it's just the generic subprocess that would not. But for a generic priority, I like floating point because it gives 52 bits of precision on most platforms. This would allow for the most flexibility. Also, 0.0 to 1.0 is in some ways more intuitive to new programmers because it can be modeled as ~0% CPU usage vs. ~100% CPU usage, theoretically. Users not familiar with UNIX might OTHO be confused by the idea that a lower priority number constitutes a higher priority. Of course, the scale used for p in Popen(...).setPriority(p) is really not an important issue to me as long as it makes sense in the context of priorities. Given that os.setpriority and Popen(...).setPriority have virtually the same name, it would probably be better to rename the later to something a bit less prone to confusion. Alternatively, it would not be unreasonable to design setPriority (and getPriority correspondingly) such that under UNIX it takes 1 parameter, -20 to +20 and under Windows it takes 2 parameters, second one optional, where the Windows API priorities are directly passed to it (for getPriority, Windows would return a Tuple pair corresponding to Priority Class and Main Thread Priority). However, I personally prefer a unified definition for subprocess.py's Priority since there already is or will be direct os-level methods to accomplish the same thing in the os- native scale. Anyway, thanks for the input and I will make a note of it in the PEP. Other than the generic Property ranges, do you see any other issues with my proposal? Jeffrey. -- http://mail.python.org/mailman/listinfo/python-list
Re: Article of interest: Python pros/cons for the enterprise
On Feb 21, 10:55 am, Bruno Desthuilliers bruno. [EMAIL PROTECTED] wrote: Carl Banks a écrit : [...] C++ is a compile-time, type-checked language, which means it is totally safer for newbies than Python. Yep, your big company is totally safe with newbie C++ programmers. Mouarf ! Brillant demonstration, thanks Carl !-) (and BTW, +1 QOTW) Newbies learn, and the fundamental C++ lessons are usually learnt quite easily. Unless we're talking about idiots, that is, but in this case at least C++ is likely to make their deficiencies evident sooner than most other programming languages. So, yes, your big company is likely to be safer with newbie C++ programmers than with Python newbie programmers. Had we been speaking of productivity... but we weren't, were we? Cheers, Nicola Musatti -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter OSX and lift
Miki wrote: Hello, Tk.lift doesn't seem to work on OSX (Python 2.5.1). The below starts OK, but the window is the behind all other windows. from Tkinter import * root = Tk() Button(root, text=OK, command=root.quit).pack() root.lift() root.mainloop() Any ideas how to tell the window to start as the topmost window? Thanks, -- Miki [EMAIL PROTECTED] http://pythonwise.blogspot.com If you click on the PythonLauncher application that runs in your dock when this script is executed, the window comes into focus fine. -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
understaning self
I've been searching online to try get a better understanding of what self does when I define this parameter in my class functions. All I'm finding is debates on whether self has any value to the language but that doesn't help me in my newbie question. So the code excerpt below is from Beginning Python Norton, Samuel, Aitel, Foster-Johnson, Richardson, Diamon, Parker, and Roberts. What I think self is doing is limiting the function call to only function in this class. So in the function below has calls self.has_various(), if I had a function called has_various in my program or another included class using self insures that the has_various below is the one used. Am I correct in my understanding? thanks, Zach- def has(self, food_name, quantity=1): has(food_name, [quantity]) - checks if the string food_name is in the fridge. quantity defaults to 1 returns True if there is enough, false otherwise. return self.has_various({food_name:quantity}) def has_various(self, foods): has various(foods) determines if the dictionary food_name has enough of every element to satisfy a request. returns true if there's enough, Fasle if there's not or if an element does not exist. try: for food in foods.keys(): if self.items[food] foods[food]: return False return True except KeyError: return False -- http://mail.python.org/mailman/listinfo/python-list
Re: Globals or objects?
Steve Holden [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: I had a global variable holding a count. One source Google found suggested that I wouldn't need the global if I used an object. So I created a Singleton class that now holds the former global as an instance attribute. Bye, bye, global. But later I thought about it. I cannot see a single advantage to the object approach. Am I missing something? Or was the original global a better, cleaner solution to the I need a value I can read/write from several places problem? Look up coupling and cohesion in Wikipedia or similar, and you will find out that global variables are bad because they introduce tight coupling between different pieces of functionality in your code. I think the OP was asking rather how the Object is any different from the global if it's simply used as a wrapper for a single value. In usage, philosophy or whatever it's effectively identical and introduces all the same problems as a global does, it just gives it a longer name. Objects only become useful when the encapsulate more than on thing. -- Chris Green -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter OSX and lift
Hello Kevin, Tk.lift doesn't seem to work on OSX (Python 2.5.1). If you click on the PythonLauncher application that runs in your dock when this script is executed, the window comes into focus fine. You're right, but I want to window to be initially in focus (without the user clicking on the python launcher icon). All the best, -- Miki [EMAIL PROTECTED] http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Globals or objects?
Aahz [EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], [EMAIL PROTECTED] wrote: I had a global variable holding a count. One source Google found suggested that I wouldn't need the global if I used an object. So I created a Singleton class that now holds the former global as an instance attribute. Bye, bye, global. But later I thought about it. I cannot see a single advantage to the object approach. Am I missing something? Or was the original global a better, cleaner solution to the I need a value I can read/write from several places problem? The advantage of the global singleton is that it is a container; therefore, its contents are mutable and you don't need to keep using the ``global`` statement. but you do keep having to use a longer reference to the value so what have you won? -- Chris Green -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Phatch = PHoto bATCH processor and renamer based on PIL
On Feb 18, 9:58 am, SPE - Stani's Python Editor [EMAIL PROTECTED] wrote: I'm pleased to announce the release of Phatch which is a powerful batch processor and renamer. Phatch exposes a big part of This program is fantastic! Very accesible user interface and produces ggreat images. Thanks! Istvan PS. the name Phatch is a bit hard to prononunce (easily confusable with fetch), it is not easy to talk about it in a live conversation. You should just call it photo-batch, in the end all the acronym saves you is four letters and you lose the obvious meaning of what the tool does. Anyhow, just a suggestion based on the first impressions, great tool, great functionality. We can surely nominate it for the best Python based tool of 2008 ... so far ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Globals or objects?
In article [EMAIL PROTECTED], [EMAIL PROTECTED] wrote: I had a global variable holding a count. One source Google found suggested that I wouldn't need the global if I used an object. So I created a Singleton class that now holds the former global as an instance attribute. Bye, bye, global. But later I thought about it. I cannot see a single advantage to the object approach. Am I missing something? Or was the original global a better, cleaner solution to the I need a value I can read/write from several places problem? The advantage of the global singleton is that it is a container; therefore, its contents are mutable and you don't need to keep using the ``global`` statement. -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ All problems in computer science can be solved by another level of indirection. --Butler Lampson -- http://mail.python.org/mailman/listinfo/python-list
Re: understaning self
On Feb 21, 7:34 am, Poppy [EMAIL PROTECTED] wrote: I've been searching online to try get a better understanding of what self does when I define this parameter in my class functions. All I'm finding is debates on whether self has any value to the language but that doesn't help me in my newbie question. So the code excerpt below is from Beginning Python Norton, Samuel, Aitel, Foster-Johnson, Richardson, Diamon, Parker, and Roberts. What I think self is doing is limiting the function call to only function in this class. So in the function below has calls self.has_various(), if I had a function called has_various in my program or another included class using self insures that the has_various below is the one used. Am I correct in my understanding? thanks, Zach- def has(self, food_name, quantity=1): has(food_name, [quantity]) - checks if the string food_name is in the fridge. quantity defaults to 1 returns True if there is enough, false otherwise. return self.has_various({food_name:quantity}) def has_various(self, foods): has various(foods) determines if the dictionary food_name has enough of every element to satisfy a request. returns true if there's enough, Fasle if there's not or if an element does not exist. try: for food in foods.keys(): if self.items[food] foods[food]: return False return True except KeyError: return False I think you are correct. The term self is a convention more than anything. You can use another name, but it's not recommended as 99% of developers expect it to be called self. You can read up on it here: http://www.diveintopython.org/object_oriented_framework/defining_classes.html In there, they define it this way and I quote: The first argument of every class method, including __init__, is always a reference to the current instance of the class. By convention, this argument is always named self. In the __init__ method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called. Although you need to specify self explicitly when defining the method, you do not specify it when calling the method; Python will add it for you automatically. Hope that helps. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython Plot always comes to focus on redraw
On Feb 21, 2:57 am, Jacob Davis [EMAIL PROTECTED] wrote: Hi. I am using wxPython, and I have a frame that has a notebook in it. there are 3 pages in the notebook, 2 of which are Panels and 1 of which is a PlotCanvas. The data for the plot changes when I press a button that is in the frame, but not in the notebook (as designed). the button also makes the plot draw again, since the data has changed. The problem is that whenever I press my button, the focus of the notebook view area (as opposed to the tabs) changes focus to the plot. if I have multiple plots, the focus goes to that plot which was drawn last in the code. however, if I click anywhere on the panel, the page of the notebook that is supposed to be in focus is now shown in the view area of the notebook. will try to make a sample .py if anybody needs a visual, let me know pls. Thanks for any help! Jake Just a show in the dark, but is the plotcanvas object's parent a frame or a panel? If it's the frame, than that's probably what the problem is. You may want to post to the wxPython list where you'll get wx geeks to answer your question and you can learn a lot from them too. Here's a link where you can sign up: http://wxpython.org/maillist.php Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Globals or objects?
[EMAIL PROTECTED] wrote: I had a global variable holding a count. One source Google found suggested that I wouldn't need the global if I used an object. So I created a Singleton class that now holds the former global as an instance attribute. Bye, bye, global. But later I thought about it. I cannot see a single advantage to the object approach. Am I missing something? Or was the original global a better, cleaner solution to the I need a value I can read/write from several places problem? A singleton is simply another form of global. The benefit of a singleton is that it can be used to encapsulate several related values and methods in a single globally accessible space. The easiest way in Python to implement a singleton is just to use a module: all modules are singletons and there is a defined mechanism (import) for accessing them. It sounds as though you simply replaced a value stored in a singleton object (global in a module) with a value stored in a singleton object (attribute of your class) which is referenced from a singleton object (your module). The real benefit from using an object comes when you stop making it a singleton. Create it at some high level in your code and pass it around as a parameter, or hold a reference to it in some other object which is passed around. When you do this you no longer have a global, and the benefits you get include: * for your counter example, you can have multiple counters counting different things without having to duplicate counter code for each thing you want to count. * it becomes much easier to write tests for your code, because each test can create its own context and be completely independant from the other tests. e.g. you can test a generic counter without having to know you are testing the foo counter or the bar counter, and you can test something which counts foos without having to worry that other tests may already have counted some foos. There is another lesser (and Python specific) benefit to storing a value as an attribute of a class rather than a global in a module: if you later want to intercept assignments to the attribute you can turn it into a property, but doing the same thing on a module is much harder. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie in python
Dive into Python is a very good book but it's for people who have experience in other languages. I liked the book. Whatever book you read, please take a look at the Python Tutorial: http://docs.python.org/tut/tut.html, it will help. regards, Subeen. http://love-python.blogspot.com/ On Feb 21, 6:01 pm, 7stud [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: Hi anyone I'm very interesed to learn python and really willing to do so,but unfortunately dont know where to start, or what programs need to install to start. Can someone help me to get in the right track, and get a good move? Thanks for all help If you're a good student or you have prior programming experience, get the book 'Learning Python', which just came out with a 3rd edition, so it is the most up to date book. If you are not such a good student or have no prior programming experience, and you want a gentler introduction to python, check out the book 'Python Programming for the Absolute Beginner(2nd Ed.)' -- http://mail.python.org/mailman/listinfo/python-list
exec and closures
About a month ago, there was a thread on auto-assigning decorators for __init__. One by André Roberge is here: http://groups.google.com/group/comp.lang.python/browse_frm/ thread/32b421bbe6caaeed/0bcd17b1fa4fb07c?#0bcd17b1fa4fb07c This works well for simple cases, but doesn't take keyword arguments or set default values. I wrote a more extensive version implementing python call semantics, but it seemed awkard to be repeating something the compiler does already, so I tried execing a function definition on the fly with the right parameters that would function as the decorator. Like this (adjust the indentation variable if it throws a syntax error) def autoassign(_init_): import inspect import functools argnames, _, _, defaults = inspect.getargspec(_init_) argnames = argnames[1:] indentation = '' settings = ['self.%s = %s' % (arg[1:], arg) for arg in argnames if arg[0] == '_'] if len(settings) = 0: return _init_ if defaults is None: args = argnames[:] else: args = argnames[:-len(defaults)] for key, value in zip(argnames[-len(defaults):],defaults): args.append('%s=%s' % (key, repr(value))) template = def _autoassign(self, %(args)s): %(setting)s _init_(self, %(argnames)s) % {'args' : , .join(args), 'setting' : \n.join(['%s%s' % (indentation, setting) for setting in settings]), 'argnames' : ', '.join(argnames)} try: exec template except SyntaxError, e: raise SyntaxError('%s. line: %s. offset %s:\n%s' % (e.msg, e.lineno, e.offset, template)) return _autoassign Which creates what looked like the right template, but when instantiating a class that uses that (eg class A(object): @autoassign def __init__(self,_a): pass a = A(3) it throws a NameError: global name '_init_' is not defined Is there a way to bind the _init_ name at exec time? Thanks, ale -- http://mail.python.org/mailman/listinfo/python-list
RE: Article of interest: Python pros/cons for the enterprise
On Behalf Of Nicola Musatti Newbies learn, and the fundamental C++ lessons are usually learnt quite easily. Unless we're talking about idiots, that is, but in this case at least C++ is likely to make their deficiencies evident sooner than most other programming languages. So, yes, your big company is likely to be safer with newbie C++ programmers than with Python newbie programmers. The danger of memory leaks alone makes C++ a decidedly newbie-unfriendly language. Java I might go along with, but C++? Regards, Ryan Ginstrom (who learned C++ before Python and has grappled with his share of memory bugs) -- http://mail.python.org/mailman/listinfo/python-list
RE: using PIL for PCA analysis
Since nobody has responded to this: I know nothing about PIL, but you can do this using numpy and scipy fairly easily, and you can transform PIL arrays into Numpy arrays pretty quickly as well. -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Sent: Thursday, February 21, 2008 2:41 AM To: python-list@python.org Subject: using PIL for PCA analysis hi guys i am trying out PCA analysis using python.I have a set of jpeg(rgbcolor) images whose pixel data i need to extract and make a matrix .( rows =num of images and cols=num of pixels) For this i need to represent an image as an array. i was able to do this using java's BufferedImage as below javacode int[] rgbdata = new int[width * height]; image.getRGB(0,0,width,height,rgbdata,0,width); doubles = new double[rgbdata.length]; int i; for ( i = 0; i bytes.length; i++) { doubles[i] = (double)(rgbdata[i]); } /javacode this doubles[] now represent a single image's pixels then i can get a matrix of say 4 images ..(each of 4X3 size) sampledata images[][] rows=4,cols=12 [ [-4413029.0, -1.0463919E7,... -5201255.0] [-5399916.0, -9411231.0, ... -6583163.0] [-3886937.0, -1.0202292E7,... -6648444.0] [-5597295.0, -7901339.0,... -5989995.0] ] /sampledata i can normalise the above matrix to zeromean and then find covariance matrix by images * transpose(images) my problem is how i can use PIL to do the same thing..if i extract imagedata using im.getdata() i will get sampledata [ [(188, 169, 155), (96, 85, 81),.. (176, 162, 153)] [(173, 154, 148), (112, 101, 97),.. (155, 140, 133)] [(196, 176, 167), (100, 83, 76), ... (154, 141, 132)] [(170, 151, 145), (135, 111, 101), ... (164, 153, 149)] ] /sampledata i donot know how to find covariance matrix from such a matrix..it would'v been ideal if they were single values instead of tuples..i can't use greyscale images since the unput images are all rgb jpeg can someone suggest a solution? thanks dn - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. -- http://mail.python.org/mailman/listinfo/python-list
Re: using PIL for PCA analysis
On Feb 21, 7:35 pm, Bronner, Gregory [EMAIL PROTECTED] wrote: you can do this using numpy and scipy fairly easily, and you can transform PIL arrays into Numpy arrays pretty quickly as well. i can use numpy ndarray or matrix once i have a PIL array with elements in the correct format(ie a single number for each pixel instead of a tuple of integers) it is the image data extraction step that is giving me the problem ie i want PIL to return an image as something like [-4413029.0, -1.0463919E7,... -5201255.0] instead of [(188, 169, 155), (96, 85, 81),.. (176, 162, 153)] Any PIL experts please help dn -- http://mail.python.org/mailman/listinfo/python-list
Re: Article of interest: Python pros/cons for the enterprise
Newbies learn, and the fundamental C++ lessons are usually learnt quite easily. Ah yes...that would be why Scott Meyers has written three volumes[1] cataloging the gotchas that even experienced C++ programmers can make... And the 1030 page Stroustrup C++ reference is easily comprehended by the uninitiated[2]. The Python core language is a mere 97 pgs. The documentation for the *entire* standard library is about the size of just the C++ Language Reference.[3] Assembly language is pretty easy to learn too. But is it a productive use of a programmer's time? Only if it's 1975. -tkc [1] http://www.amazon.com/s?url=search-alias%3Dapsfield-keywords=scott%20meyers [2] http://www.amazon.com/dp/0201700735/103-4102786-4115058 [3] http://python.org/ftp/python/doc/2.5/pdf-letter-2.5.zip -- http://mail.python.org/mailman/listinfo/python-list
Re: using PIL for PCA analysis
On Feb 21, 1:41 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: hi guys i am trying out PCA analysis using python.I have a set of jpeg(rgbcolor) images whose pixel data i need to extract and make a matrix .( rows =num of images and cols=num of pixels) For this i need to represent an image as an array. i was able to do this using java's BufferedImage as below javacode int[] rgbdata = new int[width * height]; image.getRGB(0,0,width,height,rgbdata,0,width); doubles = new double[rgbdata.length]; int i; for ( i = 0; i bytes.length; i++) { doubles[i] = (double)(rgbdata[i]);} /javacode this doubles[] now represent a single image's pixels then i can get a matrix of say 4 images ..(each of 4X3 size) sampledata images[][] rows=4,cols=12 [ [-4413029.0, -1.0463919E7,... -5201255.0] [-5399916.0, -9411231.0, ... -6583163.0] [-3886937.0, -1.0202292E7,... -6648444.0] [-5597295.0, -7901339.0,... -5989995.0] ] /sampledata i can normalise the above matrix to zeromean and then find covariance matrix by images * transpose(images) my problem is how i can use PIL to do the same thing..if i extract imagedata using im.getdata() i will get sampledata [ [(188, 169, 155), (96, 85, 81),.. (176, 162, 153)] [(173, 154, 148), (112, 101, 97),.. (155, 140, 133)] [(196, 176, 167), (100, 83, 76), ... (154, 141, 132)] [(170, 151, 145), (135, 111, 101), ... (164, 153, 149)] ] /sampledata i donot know how to find covariance matrix from such a matrix..it would'v been ideal if they were single values instead of tuples..i can't use greyscale images since the unput images are all rgb jpeg can someone suggest a solution? thanks dn I'm surprised PIL doesn't have a grayscale conversion, but here is one that can manipulate your RGB values: sampledata = [ [(188, 169, 155), (96, 85, 81), (176, 162, 153)], [(173, 154, 148), (112, 101, 97), (155, 140, 133)], [(196, 176, 167), (100, 83, 76), (154, 141, 132)], [(170, 151, 145), (135, 111, 101), (164, 153, 149)], ] # following approx from http://www.dfanning.com/ip_tips/color2gray.html grayscale = lambda (R,G,B) : int(0.3*R + 0.59*G + 0.11*B) print [ [ grayscale(rgb) for rgb in row ] for row in sampledata ] prints (reformatted to match your sampledata): [ [173, 87, 165], [159, 103, 143], [181, 87, 143], [156, 117, 155] ] -- http://mail.python.org/mailman/listinfo/python-list
Re: Globals or objects?
James Newton wrote: Duncan Booth wrote: The easiest way in Python to implement a singleton is just to use a module: all modules are singletons and there is a defined mechanism (import) for accessing them. [ ... ] Could you give a bare-bones demonstration of it that the relative newbie that I am can understand? I had a club-membership application that ran for several years. Default pathnames, etc. for the particular year came from a module called thisyear.py: #= '''Values used to access this years trakkers files. $Id: thisyear.py,v 1.2 2006/08/26 16:30:23 mwilson Exp $ ''' memberpath = '2006-7/20062007.txt' # path to this years membership CSV dirname = '2006-7' # directory name for this year #= Programs that needed to use the comma-separated-value membership base would import thisyear, and pass thisyear.memberpath when creating the CSV reader object. Etc. Mel. -- http://mail.python.org/mailman/listinfo/python-list
RE: Globals or objects?
Duncan Booth wrote: The easiest way in Python to implement a singleton is just to use a module: all modules are singletons and there is a defined mechanism (import) for accessing them. Hi Duncan, I'm intrigued by this idea. Could you give a bare-bones demonstration of it that the relative newbie that I am can understand? Thanks in advance, James -- http://mail.python.org/mailman/listinfo/python-list
how can i profile every line of code
I want to profile a function which has some lines of statement. It seem that profile module only report function's stats instead of every line of code, how can i profile every line of code? thanks. scsoce -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie in python
A big help for 'easily learning python was and is Learning Python (a book written by Mark Lutz) after having studied this book you are able to think in python another book I like very much is Core Python Programming (written by Wesley Chun) regards michael On Thursday 21 February 2008 03:26:17 pm subeen wrote: Dive into Python is a very good book but it's for people who have experience in other languages. I liked the book. Whatever book you read, please take a look at the Python Tutorial: http://docs.python.org/tut/tut.html, it will help. regards, Subeen. http://love-python.blogspot.com/ On Feb 21, 6:01 pm, 7stud [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: Hi anyone I'm very interesed to learn python and really willing to do so,but unfortunately dont know where to start, or what programs need to install to start. Can someone help me to get in the right track, and get a good move? Thanks for all help If you're a good student or you have prior programming experience, get the book 'Learning Python', which just came out with a 3rd edition, so it is the most up to date book. If you are not such a good student or have no prior programming experience, and you want a gentler introduction to python, check out the book 'Python Programming for the Absolute Beginner(2nd Ed.)' -- http://mail.python.org/mailman/listinfo/python-list
Re: Article of interest: Python pros/cons for the enterprise
Please do not reply personally to newsgroup postings, thank you. On Thu, Feb 21, 2008 at 4:00 PM, Tim Chase [EMAIL PROTECTED] wrote: [...] -- Nicola.Musatti at gmail dot com Home: http://nicola.musatti.googlepages.com/home Blog: http://wthwdik.wordpress.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Article of interest: Python pros/cons for the enterprise
On Feb 21, 3:46 pm, Ryan Ginstrom [EMAIL PROTECTED] wrote: On Behalf Of Nicola Musatti Newbies learn, and the fundamental C++ lessons are usually learnt quite easily. Unless we're talking about idiots, that is, but in this case at least C++ is likely to make their deficiencies evident sooner than most other programming languages. So, yes, your big company is likely to be safer with newbie C++ programmers than with Python newbie programmers. The danger of memory leaks alone makes C++ a decidedly newbie-unfriendly language. Java I might go along with, but C++? Memory *leaks* are just as common in garbage collected languages if not more, thanks to C++'s deterministic destruction and its standard library, especially if complemented with smart pointers such as Boost's shared_ptr. At least C++ programmers tend to know that memory must be managed, while newbies in other languages are often lead to believe - wrongly - that the garbage collector takes care of everything. Dereferencing invalid pointers however is indeed a more serious problem. This is the one lesson I had in mind when I wrote my previous message; newbies that are not hopeless tend to learn it rather quickly and the number of mistakes of this kind they make tends to fall in a rather short time. I do admit however that even experienced programmers make similar errors every now and again. While attempting to dereference a null reference is a rather common mistake in languages such as Java and C# - I'm not sure about Python - the one invaluable guarantee provided by the garbage collector is the absence of *invalid* references. This is one of the reasons why there's an ongoing effort to add garbage collection to the C++ standard, albeit in an optional form. Cheers, Nicola Musatti -- http://mail.python.org/mailman/listinfo/python-list
Re: Globals or objects?
In article [EMAIL PROTECTED], [EMAIL PROTECTED] wrote: Aahz [EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], [EMAIL PROTECTED] wrote: I had a global variable holding a count. One source Google found suggested that I wouldn't need the global if I used an object. So I created a Singleton class that now holds the former global as an instance attribute. Bye, bye, global. But later I thought about it. I cannot see a single advantage to the object approach. Am I missing something? Or was the original global a better, cleaner solution to the I need a value I can read/write from several places problem? The advantage of the global singleton is that it is a container; therefore, its contents are mutable and you don't need to keep using the ``global`` statement. but you do keep having to use a longer reference to the value so what have you won? Clarity, simplicity, robustness -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ All problems in computer science can be solved by another level of indirection. --Butler Lampson -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there any python lib for NAT transversal?
On Thu, 21 Feb 2008 14:50:50 +0800, hawk gao [EMAIL PROTECTED] wrote: Is there any python lib for NAT transversal? Divmod Vertex is such a library (it does a few other things as well), but it is not nearly complete and has little documentation. http://divmod.org/trac/wiki/DivmodVertex Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter OSX and lift
Miki wrote: Hello Kevin, Tk.lift doesn't seem to work on OSX (Python 2.5.1). If you click on the PythonLauncher application that runs in your dock when this script is executed, the window comes into focus fine. You're right, but I want to window to be initially in focus (without the user clicking on the python launcher icon). Lift (which calls the Tk command raise) doesn't work this way, at least not under Aqua. If your application has focus, lift will raise the widget being called to the top of the stacking order. However, it will not make the application frontmost. To do this you'd have to use Carbon calls (look at Carbon.CarbonEvt) or use a Tk extension and call it from Python. Of course, this is pretty much a non-issue if your application is wrapped as a standard Mac application bundle via py2app--most Mac users don't run Python apps from the Terminal but instead double-click an application icon. In that event, lift should work fine, because the application will already have focus. -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for up to date documentation for Python/Tkinter
Kintaro wrote: Oh wise usenet users, Please speak unto me the URL which contain the latest documentation on Python/Tkinter programming. I have seen Fredrik Lundh's introduction to tkinter (and others) and it appears to be for an earlier version of Python. I am working with Python 2.5 and most doc I am finding are for Python 2.2 or earlier. Many thanks The documentation you've looked at should be perfectly valid. Tkinter doesn't change much from one version of Python to the next. Of course, Tk itself does change--the new release, 8.5, is a huge update, adding platform-specific theming to better blend in. There's tons of Tcl-specific documentation about that. There has been less Tkinter-style documentation--this link might be of use: http://tkinter.unpythonic.net/wiki/TileWrapper -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux/Python Issues
[EMAIL PROTECTED] a écrit : re being serious I am serious. I am seriously trying to develop a nice language for beginners. That's not what I was talking about. re DLing source As a solution to the problem of wanting a program on my computer, it sucks. On Windows I'll DL an install package, accept a license agreement, click Next a few times (no, I can't make a cup of coffee because the minute I step away the Wizard will ask a question), ... With CNR the commitment is that I CAN walk away. I do not know who should be responsible for putting things in the warehouse. Those who maintain the warehouse. I do wish that the *n*x community would create some sensible standards so the 'our distro doesn't put things where others do' There are such standards - but not anyone is following them. What you have to understand is that unix is not *one* OS, but a (quite large) family of OSs. would stop being an issue. Looking in /usr/bin and its brethren makes c:\Program Files seem organized. Your opinion. re changing distros because apt-get could do the job I'll take your words for the superiority of Ubuntu. But I'll not change from one problem (can't find the python-devel that python.org says I need) to another (installing a new OS). I bought my Linspire computer with the OS installed. I've no interest in mastering the art of installing Linux. Installing Ubuntu is quite straightforward. IMHO even simpler than installing any recent (ie = NT4) version of Windows. I'm a big fan of KDE, KATE and Konqueror and having a dozen desktops for a dozen projects. I do not miss crashes and viruses. I do not miss shelling out hundreds of bucks for an office suite. Fine. But anyway, you have to face the fact that your OS doesn't provide a proper package for recent Python versions, and that this is by no mean the responsability of the Python team. So you're left with the following options: - complain to the company selling Linspire until they provide this package - try to install Python from sources - install another OS -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for up to date documentation for Python/Tkinter
On Thu, 21 Feb 2008 07:47:35 -0800, Kintaro wrote: Oh wise usenet users, Please speak unto me the URL which contain the latest documentation on Python/Tkinter programming. I have seen Fredrik Lundh's introduction to tkinter (and others) and it appears to be for an earlier version of Python. I am working with Python 2.5 and most doc I am finding are for Python 2.2 or earlier. Many thanks One of my favorites is http://effbot.org/tkinterbook/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Article of interest: Python pros/cons for the enterprise
On Feb 21, 4:00 pm, Tim Chase [EMAIL PROTECTED] wrote: Newbies learn, and the fundamental C++ lessons are usually learnt quite easily. Ah yes...that would be why Scott Meyers has written three volumes[1] cataloging the gotchas that even experienced C++ programmers can make... Scott Meyers's books don't just catalogue gotcha's, but suggest effective ways to use the language. Moreover their combined word count is probably below the Python Cookbook's one. And the 1030 page Stroustrup C++ reference is easily comprehended by the uninitiated[2]. The Python core language is a mere 97 pgs. The documentation for the *entire* standard library is about the size of just the C++ Language Reference.[3] A more reasonable comparison would be against the core portion of the C ++ standard. This is still roughly three times the Python Reference Manual. The C++ syntax is way more complex than Python's and mostly due to its C heritage is also often inconsistent. However, despite its apparent semplicity, Python allows extremely advanced programming techniques. I wouldn't be surprised if the proportion of Python programmers that are capable of exploiting the language's full power was comparable to the corresponding proportion of C++ expert programmers. While I find the Python standard library documentation adequate for a free, voluntary effort, I consider it one of the weakest spots of Python as a professional tool. Still comparing its size against Stroustrup's book's is really comparing apples with oranges. Assembly language is pretty easy to learn too. But is it a productive use of a programmer's time? Only if it's 1975. It depends on the task at hand. Cheers, Nicola Musatti -- http://mail.python.org/mailman/listinfo/python-list
Re: Article of interest: Python pros/cons for the enterprise
Ryan Ginstrom wrote: On Behalf Of Nicola Musatti Newbies learn, and the fundamental C++ lessons are usually learnt quite easily. Unless we're talking about idiots, that is, but in this case at least C++ is likely to make their deficiencies evident sooner than most other programming languages. So, yes, your big company is likely to be safer with newbie C++ programmers than with Python newbie programmers. The danger of memory leaks alone makes C++ a decidedly newbie-unfriendly language. Java I might go along with, but C++? Regards, Ryan Ginstrom (who learned C++ before Python and has grappled with his share of memory bugs) I think you can safely assume that an irony/irony tag pair should have surrounded Nicola's assertion. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Looking for up to date documentation for Python/Tkinter
Oh wise usenet users, Please speak unto me the URL which contain the latest documentation on Python/Tkinter programming. I have seen Fredrik Lundh's introduction to tkinter (and others) and it appears to be for an earlier version of Python. I am working with Python 2.5 and most doc I am finding are for Python 2.2 or earlier. Many thanks -- http://mail.python.org/mailman/listinfo/python-list
RE: Globals or objects? (is: module as singleton)
Mel wrote: James Newton wrote: Could you give a bare-bones demonstration of [implementing a singleton by using a module]? I had a club-membership application that ran for several years. Default pathnames, etc. for the particular year came from a module called thisyear.py: #= '''Values used to access this years trakkers files. $Id: thisyear.py,v 1.2 2006/08/26 16:30:23 mwilson Exp $ ''' memberpath = '2006-7/20062007.txt' # path to this years membership CSV dirname = '2006-7' # directory name for this year #= Programs that needed to use the comma-separated-value membership base would import thisyear, and pass thisyear.memberpath when creating the CSV reader object. Etc. Hi Mel, So you were using thisyear.py as a preferences file: making it a module was a shortcut for reading in the file and parsing its contents. I like it. Would there be any circumstances where the singleton module would include functions and objects? In particular, would this system work if the application needed to change a value (such as a counter)? Suppose your application wanted to save the changed value, so that the next session started using the new value. Could you simply write out a new copy of the thisyear.py file? Or would this lead to version issues? Would a previously-imported version of the module be stored in a different place in RAM than a module that was imported after the change was made? Perhaps my real question is about how to visualize a module: what makes an imported module different from an instance? Thanks for your insights, James -- http://mail.python.org/mailman/listinfo/python-list
Python on Windows Help
I've written the following script based on information I have found on the web. The purpose of the script is to start an HTTP listener on the machine it's running on that will give status on a particular service running on that system. I've tried to create this as a service on the windows server it's running on, and it will install fine. The problem I'm having is that the service will not stop when I tell it to. Any help that anyone could provide would be greatly appreciated. I'm new to python so please let me know if there is a more efficient way to do what I'm trying to do. The code follows: import win32service import win32serviceutil import wmi from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler class BlobCheck(win32serviceutil.ServiceFramework): _svc_name_ = BlobCheck _svc_display_name_ = Epic Blob Checker _svc_description_ = Checks the Epic Blob Service and Creates an HTTP listener that can be polled for status def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.isAlive = True def SvcDoRun(self): import servicemanager c = wmi.WMI() while self.isAlive: class RequestHandler(BaseHTTPRequestHandler): def _writeheaders(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_HEAD(self): self._writeheaders() def do_GET(self): self._writeheaders() running = c.Win32_Process (name=notepad.exe) if running: self.wfile.write(HTMLHEADTITLEMonitor/TITLE/HEAD BODYKool-Aid!!!/BODY/HTML) else: self.wfile.write(HTMLHEADTITLEMonitor/TITLE/HEAD BODYOh No!!!/BODY/HTML) serveraddr = ('', 12345) srvr = HTTPServer(serveraddr, RequestHandler) srvr.handle_request() def SvcStop(self): import servicemanager servicemanager.LogInfoMsg(aservice - Recieved stop signal) self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.isAlive = False if __name__ == '__main__': win32serviceutil.HandleCommandLine(BlobCheck) -- http://mail.python.org/mailman/listinfo/python-list
distutils setup - changing the location in site-packages
I am hoping if someone can set me straight. I have created a setup script for a module, however, when running the install on my own machine, I would like to place the module in a specific site-packages directory/package. So if I start with a module in .\dev\mygreatmodule.py I want to end up with; .\lib\site-packages\mytools\mygreatmodule.py. I have the setup script working, however, when I run the install, it places the module in the root of site-packages. The following is the deatils from the script setup ( name = mymodule, version = 0.1, description = My modules special description, author = me, author_email = [EMAIL PROTECTED], py_modules = [exceptionhandler] ) This is for development purposes. I would like to have a development copy of some tools, but when ready and tested publish them to the site-packages where they can be included in production code. Any guidance/suggestions would be appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Globals or objects?
Aahz [EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], [EMAIL PROTECTED] wrote: Aahz [EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], [EMAIL PROTECTED] wrote: I had a global variable holding a count. One source Google found suggested that I wouldn't need the global if I used an object. So I created a Singleton class that now holds the former global as an instance attribute. Bye, bye, global. But later I thought about it. I cannot see a single advantage to the object approach. Am I missing something? Or was the original global a better, cleaner solution to the I need a value I can read/write from several places problem? The advantage of the global singleton is that it is a container; therefore, its contents are mutable and you don't need to keep using the ``global`` statement. but you do keep having to use a longer reference to the value so what have you won? Clarity, simplicity, robustness Clarity - why is it clearer? Simplicity - no, you've added an extra layer. Robustness - how? -- Chris Green -- http://mail.python.org/mailman/listinfo/python-list
RE: Article of interest: Python pros/cons for the enterprise
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of Tim Chase Sent: Wednesday, February 20, 2008 8:58 AM To: estherschindler Cc: python-list@python.org Subject: Re: Article of interest: Python pros/cons for the enterprise Oh noes! You might need competent programmers that actually understand what they're doing! (they might even have to write testing code to make sure their code works as intended...it's a good thing that Python includes unittest and doctest modules in the stock install) Sigh. Any programmer that can overcome the hurdles of learning Java or C# can quickly/easily pick up Python as long as they're willing to unlearn some bad habits. -Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of Carl Banks Sent: Wednesday, February 20, 2008 8:39 PM To: python-list@python.org Subject: Re: Article of interest: Python pros/cons for the enterprise C++ is a compile-time, type-checked language, which means it is totally safer for newbies than Python. Yep, your big company is totally safe with newbie C++ programmers. Eh, don't laugh too hard. Since Python code isn't type-checked until the actual code block is executed, you have to go through the extra step of testing/running _every_ line of code before you'll find an error. Then there's the problem of how mutable Python objects are. So even if you execute every line of code, you might not have executed the code with every possible type of object combination. Compared to a statically typed language, it can get very expensive to write comprehensive test cases for python scripts. So I wouldn't be quick to dismiss the notion that Java/C#/C++ are more newbie-safe than Python. =/ An amusing case in point was where I had a type-cast error in an exception's catch block's print statement. This simple error caused the program to stop with an unhandled exception. Something that basic would have been caught in a statically typed language very early in the dev cycle when it's cheaper to fix the problem. And the idea of running/testing exceptions or simple print statements isn't always foremost in people's minds. =P * The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA625 -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils setup - changing the location in site-packages
On Feb 21, 9:33 am, imageguy [EMAIL PROTECTED] wrote: I have the setup script working, however, when I run the install, it places the module in the root of site-packages. The following is the deatils from the script setup ( name = mymodule, version = 0.1, description = My modules special description, author = me, author_email = [EMAIL PROTECTED], py_modules = [exceptionhandler] ) Yeah, you need to specify the module path. ie, ``py_modules = [mytools.exceptionhandler]`` However, chances are that you want use ``packages``: setup ( ... packages = [mytools] ) This should include the ``exceptionhandler`` module in the package. Additionally, you'll need to structure the project to have a ``mytools`` directory that contains an ``__init__.py`` file(package initialization module), and the ``exceptionhandler.py`` file: projectdir/ | |- mytools/ || ||- __init__.py ||- exceptionhandler.py | |- setup.py ... This can be somewhat undesirable if you're using cvs, as chances are you'll want to change the package's name at some point in the future. However, I have found that the annoyance of empty directories littering the module's tree does not outweigh the annoyance of not being able to use setuptools' ``develop`` command. Not to mention the simplicity of just using ``packages``. This is for development purposes. I would like to have a development copy of some tools, but when ready and tested publish them to the site-packages where they can be included in production code. setuptools' 'develop' command can be handy for this. Hope this helps. -- http://mail.python.org/mailman/listinfo/python-list
RE: Globals or objects? (is: module as singleton)
James Newton [EMAIL PROTECTED] wrote: Perhaps my real question is about how to visualize a module: what makes an imported module different from an instance? On one level: nothing. An imported module is an instance of the module type. Modules don't have to be associated with python code: you can create additional module instances (by calling new.module) and populate them however you wish. What you get with a module is support for locating a specific module and ensuring that you don't get duplicate copies of a named module. What you lose is the ability to define methods: functions in a module don't have a 'self' parameter. Also you can't override special methods for a module, so it isn't quite equivalent to writing a class, but there are similarities. Regarding your question about saving the values: what you would usually do would be to store the values in a separate configuration file and the module would load them on startup and then rewrite the configuration file when you call a save function. That way the module code itself isn't changing. The 'singleton' config module would expose functions such as 'load', 'save', 'getXXX'. -- http://mail.python.org/mailman/listinfo/python-list
RE: Globals or objects? (is: module as singleton)
Duncan Booth wrote: you can create additional module instances (by calling new.module) Hi Duncan, Could you provide a scenario where this would be useful (and the best practice)? What you get with a module is support for locating a specific module and ensuring that you don't get duplicate copies of a named module. So if I were to execute the following pseudo-code, the second 'import' would simply point at the module (instance) imported the first time: import mymodule changeContentsOf(mymodule.py) #on the hard disk import mymodule The values, functions and classes available in mymodule would only change if I were to restart the application. Regarding your question about saving the values: what you would usually do would be to store the values in a separate configuration file and the module would load them on startup and then rewrite the configuration file when you call a save function... That's what I would normally do, too. Thanks for your help, James -- http://mail.python.org/mailman/listinfo/python-list
Re: Why must implementing Python be hard unlike Scheme?
[EMAIL PROTECTED] wrote: I'm learning Scheme and I am amazed how easy it is to start building a half baked Scheme implementation that somewhat works. After knowing Python for *years* I have no idea how to actually implement the darn thing. Why? It's not very difficult. Get a parser for LALR(1) grammars, like YACC or Bison, write a tokenizer that understands Python indentation, hook up a dictionary, and parse the thing into a tree. This is all covered in Compilers 101. Get the Dragon Book if you don't know this stuff. Once you have a tree, figure out some way to encode the tree into a linear form, and write an execution engine that reads byte codes and has the big switch to call the function for each byte code. The run-time data implementation is all dictionaries. In Python, everything is a variable-sized hash. You don't even have to allocate storage during compile time. The run-time environment is a tree of hashes. The resulting implementation will be slow, but then, so is CPython. Too much time goes into hash lookups. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Article of interest: Python pros/cons for the enterprise
On Feb 21, 5:14 pm, Steve Holden [EMAIL PROTECTED] wrote: Ryan Ginstrom wrote: On Behalf Of Nicola Musatti Newbies learn, and the fundamental C++ lessons are usually learnt quite easily. Unless we're talking about idiots, that is, but in this case at least C++ is likely to make their deficiencies evident sooner than most other programming languages. So, yes, your big company is likely to be safer with newbie C++ programmers than with Python newbie programmers. The danger of memory leaks alone makes C++ a decidedly newbie-unfriendly language. Java I might go along with, but C++? [...] I think you can safely assume that an irony/irony tag pair should have surrounded Nicola's assertion. To an extent, certainly. As not all companies can afford to hire only the best, you do have to cater for newbies. The way to do it, however, is not to provide them with sandbox languages [1], but rather to ensure that they acquire experience as quickly as possible and that they aren't in a position to do more damage than expert programmers through their inexperience. To this purpose mentoring, tests and code inspections appear to me as more effective tools than a garbage collector. Still, suppose you were to choose a team of swimmers that had to be ready for a tough task in a short time; the first time around, would you push them into the swimming pool with or without a life jacket? The trouble with C++ is that at times it takes you sooo long to drown ;-) Cheers, Nicola Musatti [1] I'm not thinking of any specific language, but rather to the notion that some languages are inherently safe. -- http://mail.python.org/mailman/listinfo/python-list
Re: exec and closures
Alejandro Dubrovsky wrote: About a month ago, there was a thread on auto-assigning decorators for __init__. One by André Roberge is here: http://groups.google.com/group/comp.lang.python/browse_frm/ thread/32b421bbe6caaeed/0bcd17b1fa4fb07c?#0bcd17b1fa4fb07c This works well for simple cases, but doesn't take keyword arguments or set default values. I wrote a more extensive version implementing python call semantics, but it seemed awkard to be repeating something the compiler does already, so I tried execing a function definition on the fly with the right parameters that would function as the decorator. Like this (adjust the indentation variable if it throws a syntax error) def autoassign(_init_): import inspect import functools argnames, _, _, defaults = inspect.getargspec(_init_) argnames = argnames[1:] indentation = '' settings = ['self.%s = %s' % (arg[1:], arg) for arg in argnames if arg[0] == '_'] if len(settings) = 0: return _init_ if defaults is None: args = argnames[:] else: args = argnames[:-len(defaults)] for key, value in zip(argnames[-len(defaults):],defaults): args.append('%s=%s' % (key, repr(value))) template = def _autoassign(self, %(args)s): %(setting)s _init_(self, %(argnames)s) % {'args' : , .join(args), 'setting' : \n.join(['%s%s' % (indentation, setting) for setting in settings]), 'argnames' : ', '.join(argnames)} try: exec template except SyntaxError, e: raise SyntaxError('%s. line: %s. offset %s:\n%s' % (e.msg, e.lineno, e.offset, template)) return _autoassign Which creates what looked like the right template, but when instantiating a class that uses that (eg class A(object): @autoassign def __init__(self,_a): pass a = A(3) it throws a NameError: global name '_init_' is not defined Is there a way to bind the _init_ name at exec time? Use a dedicated namespace: namespace = dict(_init_=_init_) exec template in namespace return namespace[_autoassign] Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Article of interest: Python pros/cons for the enterprise
On 21 Feb, 16:37, Nicola Musatti [EMAIL PROTECTED] wrote: While attempting to dereference a null reference is a rather common mistake in languages such as Java and C# - I'm not sure about Python - the one invaluable guarantee provided by the garbage collector is the absence of *invalid* references. This is one of the reasons why there's an ongoing effort to add garbage collection to the C++ standard, albeit in an optional form. The main reason why C++ has declined in usage is because almost everything of practical value is optional. Meanwhile, those C++ newbies we were talking about are having to deal with decisions that everyone else can quite happily ignore, knowing that the right choice has probably already been made for them, where automatic memory management is probably the right choice for the biggest decision of them all, as Java demonstrated quite successfully to the hordes of enterprise programmers (and their managers) at the end of the 1990s. Back to those C++ newbies, then. Of course, none of them pushed into a C++ project is going to have much say about which memory management best practice is going to be used - the decisions are already set in stone by the project - and so it's all about coping with the tedious tracking of who owns which pointer and hoping that different libraries don't have different policies. Taking the quotes out of order... At least C++ programmers tend to know that memory must be managed, while newbies in other languages are often lead to believe - wrongly - that the garbage collector takes care of everything. Sure, there are some issues with memory consumption patterns with various garbage collectors, but the it's good for you attitude has scant justification unless you're dealing with constrained environments. And even with people watching the dials in their C++ application, you still get obscene resource misuse, which is why Firefox eventually consumes over 1GB memory on this desktop. There are considerably fewer caveats involved with regard to languages with garbage-collected runtime environments. I seem to remember that Hans Boehm had some interesting observations about garbage collection myths, especially around performance, but since the mindset persists in large tracts of the C++ development landscape that it must somehow be cheating to use a garbage collector, I suppose we still have a few more years of applications accessing the wrong memory locations and showing the usual useless backtrace dialogues for submission to uninterested developers who insisted on using C++ because everything else is slow. Paul -- http://mail.python.org/mailman/listinfo/python-list
KeyboardInterrupt should not kill subprocess
Hi, I'm using subprocess.Popen() to run some background processes. However, the program is also supposed to catch CTRL+C keyboard interrupts for refreshs (i.e. a keyboard interrupt doesn't shut down the program). But as it seems, a keyboard interrupt will automatically pass down to the subprocesses, causing them to abort. Is there a way that I can prevent the subprocesses from being canceled by a keyboard interrupt? To clarify my question, here is a minimal example: import subprocess import os import time import sys # is 'sleep' available on Win machines? # use another dummy program if it isn't p = subprocess.Popen(['sleep', '10']) while True: try: time.sleep(1) pass # normal program procedure print subprocess poll: + str(p.poll()) except KeyboardInterrupt: try: print(Hit Ctrl+C again to quit) time.sleep(1) print Refreshing pass # do some refresh stuff here except KeyboardInterrupt: sys.exit(0) As you can see, after the refresh, p.poll() is '-2'. I'd want the subprocess to continue undisturbed, i.e. p.poll() would still return 'None'. Thanks, Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: Why must implementing Python be hard unlike Scheme?
On 21 Feb, 18:28, John Nagle [EMAIL PROTECTED] wrote: Why? It's not very difficult. Get a parser for LALR(1) grammars, like YACC or Bison, write a tokenizer that understands Python indentation, hook up a dictionary, and parse the thing into a tree. This is all covered in Compilers 101. Get the Dragon Book if you don't know this stuff. Or, if time is precious and you don't really care what parses your programs (or even compiles them), just skip over this and use the standard library compiler package: http://docs.python.org/lib/compiler.html Paul -- http://mail.python.org/mailman/listinfo/python-list
Last 4 Letters of String
Hello Guys, I'm looking for a function which will give me the last 4 characters of a given string. I'm sure it's a very simple task but I couldn't find anything of it. Any ideas? Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: understaning self
Thanks for your explanation and pointer. Mike Driscoll [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Feb 21, 7:34 am, Poppy [EMAIL PROTECTED] wrote: I've been searching online to try get a better understanding of what self does when I define this parameter in my class functions. All I'm finding is debates on whether self has any value to the language but that doesn't help me in my newbie question. So the code excerpt below is from Beginning Python Norton, Samuel, Aitel, Foster-Johnson, Richardson, Diamon, Parker, and Roberts. What I think self is doing is limiting the function call to only function in this class. So in the function below has calls self.has_various(), if I had a function called has_various in my program or another included class using self insures that the has_various below is the one used. Am I correct in my understanding? thanks, Zach- def has(self, food_name, quantity=1): has(food_name, [quantity]) - checks if the string food_name is in the fridge. quantity defaults to 1 returns True if there is enough, false otherwise. return self.has_various({food_name:quantity}) def has_various(self, foods): has various(foods) determines if the dictionary food_name has enough of every element to satisfy a request. returns true if there's enough, Fasle if there's not or if an element does not exist. try: for food in foods.keys(): if self.items[food] foods[food]: return False return True except KeyError: return False I think you are correct. The term self is a convention more than anything. You can use another name, but it's not recommended as 99% of developers expect it to be called self. You can read up on it here: http://www.diveintopython.org/object_oriented_framework/defining_classes.html In there, they define it this way and I quote: The first argument of every class method, including __init__, is always a reference to the current instance of the class. By convention, this argument is always named self. In the __init__ method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called. Although you need to specify self explicitly when defining the method, you do not specify it when calling the method; Python will add it for you automatically. Hope that helps. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for up to date documentation for Python/Tkinter
Daniel Mahoney [EMAIL PROTECTED] writes: On Thu, 21 Feb 2008 07:47:35 -0800, Kintaro wrote: Oh wise usenet users, Please speak unto me the URL which contain the latest documentation on Python/Tkinter programming. I have seen Fredrik Lundh's introduction to tkinter (and others) and it appears to be for an earlier version of Python. I am working with Python 2.5 and most doc I am finding are for Python 2.2 or earlier. Many thanks One of my favorites is http://effbot.org/tkinterbook/ 'Fredrik Lundh' == 'effbot' True ;-) Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Last 4 Letters of String
Robert Rawlins - Think Blue wrote: Hello Guys, I'm looking for a function which will give me the last 4 characters of a given string. I'm sure it's a very simple task but I couldn't find anything of it. Use the same technique as you'd use slicing a list. http://www.diveintopython.org/native_data_types/lists.html Any ideas? Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Last 4 Letters of String
Try this s = abcdefgh s[-4:] 'efgh 2008/2/21, Robert Rawlins - Think Blue [EMAIL PROTECTED]: Hello Guys, I'm looking for a function which will give me the last 4 characters of a given string. I'm sure it's a very simple task but I couldn't find anything of it. Any ideas? Rob -- http://mail.python.org/mailman/listinfo/python-list -- Rafael Sachetto Oliveira Sir - Simple Image Resizer http://rsachetto.googlepages.com -- http://mail.python.org/mailman/listinfo/python-list
Re: understaning self
On Feb 21, 2:34 pm, Poppy [EMAIL PROTECTED] wrote: I've been searching online to try get a better understanding of what self does when I define this parameter in my class functions. All I'm finding is debates on whether self has any value to the language but that doesn't help me in my newbie question. So the code excerpt below is from Beginning Python Norton, Samuel, Aitel, Foster-Johnson, Richardson, Diamon, Parker, and Roberts. What I think self is doing is limiting the function call to only function in this class. So in the function below has calls self.has_various(), if I had a function called has_various in my program or another included class using self insures that the has_various below is the one used. Am I correct in my understanding? I'll try to explain with as simple an example as I can think of. First of all, 'self' is just a conventional name, it isn't a keyword and has no special meaning per se. You could just as easily write: In [10]: class A(object): : def __init__(this, n): : this.n = n : : def f(me): : print me.n : : In [11]: a = A(42) In [12]: a.f() 42 The point is that when you write a statement such as a.f() the interpreter uses 'a' in two ways: first, to find which function f() to call; second, as a parameter to f() itself. The conventional 'self' helps you remind that the first argument is going to be the instance of the class on which the function f() is going to be called. You can actually separate the two uses above with the following equivalent call: In [13]: A.f(a) 42 Here you tell the interpreter which function f() to call by specifying its class, A, and you pass it 'a' explicitly as an argument. One could argue that the C++/Java/C# approach where you don't specify the current instance as an argument, but can optionally use the 'this' keyword to refer to it is more convenient; however the explicit 'self' makes it possible for free functions and class methods to work in exactly the same way. This in turn makes the language more consistent and makes some more advanced, very effective techniques possible. Hope this helps. Cheers, Nicola Musatti -- http://mail.python.org/mailman/listinfo/python-list
Re: Article of interest: Python pros/cons for the enterprise
Bruno Desthuilliers wrote: Carl Banks a écrit : On Feb 20, 8:58 am, Tim Chase [EMAIL PROTECTED] wrote: You Used Python to Write WHAT? http://www.cio.com/article/185350 Furthermore, the power and expressivity that Python offers means that it may require more skilled developers. [...down to the summary...] Python may not be an appropriate choice if you: [...] * Rely on teams of less-experienced programmers. These developers may benefit from the wider availability of training for languages like Java and are less likely to make mistakes with a compile-time, type-checked language. (snip) C++ is a compile-time, type-checked language, which means it is totally safer for newbies than Python. Yep, your big company is totally safe with newbie C++ programmers. Mouarf ! Brillant demonstration, thanks Carl !-) (and BTW, +1 QOTW) NB: This is not a troll. (Please, nobody try to be cute with a yes it is reply.) c.l.python seem to be about the most close-minded of any of the currently popular language-specific news groups. It's just taken for granted that Perl and C++, two of my personal favorite things in this world, inherently favor ugly, buggy code. That is the farthest thing from the truth as I see it. You can (and plenty of people will) write terrible code in any language, including Python. To use Python effectively, you have to know something about how it works, and the same is true of Perl and C++. But a newbie who's learning from a decent source (avoid the C++ for Morons style books) is likely (I contend) to be writing semi-useful programs about as fast as with Python, and to be writing heavy-duty work-horse programs far sooner. Perl is, and always has been, a language for getting your job done; when everything else failed, Perl and C++ got me through some of the toughest tasks of my life. Translating file formats, automating system-level tasks... And now that the C++ standard library is getting regular expressions, I can replace plenty of glued-together scripts with single-language, cohesive applications. I like Python, and I think it's got a brilliant future ahead of it. It is rapidly becoming the dynamic language of choice, especially for C++ projects. I am glad that Python can be extended straightforwardly in any C-linkable language. But this bashing of other powerful languages on the basis that they're hard to read and hard to use correctly is, frankly, nonsense. -- http://mail.python.org/mailman/listinfo/python-list
Choosing a Metaclass?
Hi list, Hopefully a quick metaclass question. In the following example, MyMeta is a metaclass that does not inherit directly from type: #!/usr/bin/python class MyMeta(object): def __new__(cls, name, bases, vars): print MyMeta.__new__ called for %s % name return type(name, bases, vars) class MetaWrapper(object): __metaclass__ = MyMeta class M(MetaWrapper): pass [EMAIL PROTECTED] ~]$ python t.py MyMeta.__new__ called for MetaWrapper [EMAIL PROTECTED] ~]$ When I run that script, it's apparent that although M inherits from MetaWrapper, it does not use MyMeta as it's metaclass. However, if I change MyMeta to be a subclass of builtin type, it works as I would expect: [EMAIL PROTECTED] ~]$ cat t.py #!/usr/bin/python class MyMeta(type): def __new__(cls, name, bases, vars): print MyMeta.__new__ called for %s % name return super(MyMeta, cls).__new__(cls, name, bases, vars) class MetaWrapper(object): __metaclass__ = MyMeta class M(MetaWrapper): pass [EMAIL PROTECTED] ~]$ python t.py MyMeta.__new__ called for MetaWrapper MyMeta.__new__ called for M [EMAIL PROTECTED] ~]$ How exactly does Python choose which MC it will use when building a class? It doesn't seem to me that the parent class of MyMeta should matter in this case? Thanks! Jeff -- http://mail.python.org/mailman/listinfo/python-list
RE: Last 4 Letters of String
How would you get the last 4 items of a list? From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Robert Rawlins - Think Blue Sent: Thursday, February 21, 2008 11:36 AM To: python-list@python.org Subject: Last 4 Letters of String Hello Guys, I'm looking for a function which will give me the last 4 characters of a given string. I'm sure it's a very simple task but I couldn't find anything of it. Any ideas? Rob -- http://mail.python.org/mailman/listinfo/python-list
RE: Last 4 Letters of String
string whose last four letters are abcd[-4:] 'abcd' From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Robert Rawlins - Think Blue Sent: 21 February 2008 11:36 To: python-list@python.org Subject: Last 4 Letters of String Hello Guys, I'm looking for a function which will give me the last 4 characters of a given string. I'm sure it's a very simple task but I couldn't find anything of it. Any ideas? Rob -- http://mail.python.org/mailman/listinfo/python-list
Help on help()
Is there any technique for preventing help from recursing into the module tree?? If I do: import my_module help(my_module) I'd like to see ONLY help on my_module, NOT help on all the functions inherited from the various parent classes . . . A quick search of the documentation didn't turn up anything . . . . TIA .. . Dan -- http://mail.python.org/mailman/listinfo/python-list
can't set attributes of built-in/extension type
I'm working on a simple extension. Following the classic 'noddy' example. In [15]: cmplx_int32 Out[15]: type 'numpy.cmplx_int32' Now I want to add an attribute to this type. More precisely, I want a class attribute. cmplx_int32.test = 0 --- TypeError Traceback (most recent call last) /home/nbecker/numpy/ipython console in module() TypeError: can't set attributes of built-in/extension type 'numpy.cmplx_int32' What am I missing? -- http://mail.python.org/mailman/listinfo/python-list
Script Running Time
Hello, I am trying to find a way to output how long a script took to run. Obviously the print would go at the end of the script, so it would be the time up till that point. I also run a PostgreSQL query inside the script and would like to separately show how long the query took to run. Is this even possible? Thanks, Ewan -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie in python
[EMAIL PROTECTED] wrote: I'm very interesed to learn python and really willing to do so,but unfortunately dont know where to start, or what programs need to install to start. There are several good replies already on this thread, but in case any experienced programmers searching the Google archives are looking for the fastest way to learn Python, I highly recommend Python in a Nutshell by Alex Martelli (O'Reilly). Good tutorial, high information density, avoids hand-waving, solid reference. Do *not* bother with Programming Python until you have some experience with the core language. I don't know why O'Reilly called it that, except to mislead people into thinking it was similar to the highly successful Programming Perl; if so, I fell for it, and so did plenty of other people (so there's probably a copy in your coworker's office already). Programming Python is (despite its size) the moral equivalent of the O'Reilly Cookbooks for other languages. It's not necessarily a bad book, but the only language/library tutorial it gives is meant to be a review, not an introduction. -- http://mail.python.org/mailman/listinfo/python-list
Re: can't set attributes of built-in/extension type
On Feb 21, 11:19 am, Neal Becker [EMAIL PROTECTED] wrote: I'm working on a simple extension. Following the classic 'noddy' example. In [15]: cmplx_int32 Out[15]: type 'numpy.cmplx_int32' Now I want to add an attribute to this type. More precisely, I want a class attribute. cmplx_int32.test = 0 --- TypeError Traceback (most recent call last) /home/nbecker/numpy/ipython console in module() TypeError: can't set attributes of built-in/extension type 'numpy.cmplx_int32' What am I missing? class Dog(object): def __setattr__(self, attr, val): print TypeError: can't set attributes of built-in/extension print type 'Dog.cmplx_int32' d = Dog() d.test = 0 --output:-- TypeError: can't set attributes of built-in/extension type 'Dog.cmplx_int32' -- http://mail.python.org/mailman/listinfo/python-list
Re: psycopg2: connect copy_from and copy_to
On Feb 20, 9:27 am, Thomas Guettler [EMAIL PROTECTED] wrote: Up to now I am happy with psycopg2. Yeah. psyco is good. Why do you develop pg_proboscis? [Good or bad as they may be] 1. Alternate interface (greentrunk) 2. Non-libpq implementation yields better control over the wire that allows: a. Custom communication channels (not limited to libpq's worldview) b. Leveraging of protocol features that libpq's API does not fully accommodate (think bulk INSERTs using prepared statements with less round-trip costs) c. Allows custom sub-protocols(I use this to implement a remote python command/console[pdb'ing stored Python procedures, zero network latency scripts]). 3. Makes use of binary types to reduce bandwidth usage. (I started developing this before libpq had the ability to describe statements to derive statement parameter types and cursor column types(?), so using the binary format was painful at best) 4. Has potential for being used in event driven applications without threads. 5. Better control/understanding of running queries allows for automatic operation interrupts in exception cases: [The last two may be possible using libpq's async interfaces, but I'm not entirely sure] 6. Arguably greater(well, *easier* is likely a better word) portability. While I have yet to get it to work with other Pythons(pypy, ironpython, jython), the potential to work with these alternate implementations is there. The real impediment here is missing/inconsistent features in the implementations(setuptools support, missing os module in ironpython(i know, i know, and I don't care. Last time I checked, it's missing from the default install that's broken :P), jython is still at 2.2, iirc) 7. Bit of a license zealot. psycopg2 is [L?]GPL, pg_proboscis is BSD[or MIT if you like] like PostgreSQL. (Yes, Darcy's interface is BSD licensed(iirc), but it too is libpq based) In sum, it yields greater control over the connection which I believe will lead to a more flexible and higher quality interface than a libpq solution. [The primary pain point I've had is implementing all the authentication mechanisms supported by PG] -- http://mail.python.org/mailman/listinfo/python-list
Re: Why must implementing Python be hard unlike Scheme?
On 21 Feb., 18:28, John Nagle [EMAIL PROTECTED] wrote: The run-time data implementation is all dictionaries. In Python, everything is a variable-sized hash. You don't even have to allocate storage during compile time. The run-time environment is a tree of hashes. Except that it is not. -- http://mail.python.org/mailman/listinfo/python-list
Re: Article of interest: Python pros/cons for the enterprise
On Feb 21, 6:31 pm, Paul Boddie [EMAIL PROTECTED] wrote: [...] The main reason why C++ has declined in usage is because almost everything of practical value is optional. The main reason why C++ has declined in usage is because it never got the kind of corporate marketing enjoyed by Java and C#. Meanwhile, those C++ newbies we were talking about are having to deal with decisions that everyone else can quite happily ignore, knowing that the right choice has probably already been made for them, where automatic memory management is probably the right choice for the biggest decision of them all, as Java demonstrated quite successfully to the hordes of enterprise programmers (and their managers) at the end of the 1990s. A choice that is available to C++ programmers too, altough I admit it's not a common one and does usually require an external library. As to it being the right choice it's debatable: it took Java something like ten years to come out with usable GUI applications and, judging from many articles and postings across the internet memory management *is* an issue with Java, especially for long running applications. There are other downsides to garbage collection, as the fact that it makes it harder to implement the Resource Acquisition Is Initialization idiom, due to the lack of deterministic destruction. Other languages, such as Python and C#, are recognizing this fact and provide the with/using statement, which serves this purpose but is definitely more clumsy. Back to those C++ newbies, then. Of course, none of them pushed into a C++ project is going to have much say about which memory management best practice is going to be used - the decisions are already set in stone by the project - and so it's all about coping with the tedious tracking of who owns which pointer and hoping that different libraries don't have different policies. Taking the quotes out of order... Sorry, but although this was probably true in the early 90's that's not the way it goes in practice nowadays, thanks to automatic variables, destructors, the standard library containers and smart pointers. At least C++ programmers tend to know that memory must be managed, while newbies in other languages are often lead to believe - wrongly - that the garbage collector takes care of everything. Sure, there are some issues with memory consumption patterns with various garbage collectors, but the it's good for you attitude has scant justification unless you're dealing with constrained environments. It's not just a matter of memory consumption patterns, it's also a question of explicitly resetting your memory references to ensure that the GC can reclaim them. This can be less than obvious when complex data structures and/or callback objects are involved. And even with people watching the dials in their C++ application, you still get obscene resource misuse, which is why Firefox eventually consumes over 1GB memory on this desktop. There are considerably fewer caveats involved with regard to languages with garbage-collected runtime environments. Unfortunately C++ by itself cannot ensure that only top programmers use it ;-) I seem to remember that Hans Boehm had some interesting observations about garbage collection myths, especially around performance, but since the mindset persists in large tracts of the C++ development landscape that it must somehow be cheating to use a garbage collector, I suppose we still have a few more years of applications accessing the wrong memory locations and showing the usual useless backtrace dialogues for submission to uninterested developers who insisted on using C++ because everything else is slow. Things change. Boehm himself is working for the inclusion of - optional - garbage collection in the C++ standard. Cheers, Nicola Musatti -- http://mail.python.org/mailman/listinfo/python-list
Re: can't set attributes of built-in/extension type
7stud wrote: On Feb 21, 11:19 am, Neal Becker [EMAIL PROTECTED] wrote: I'm working on a simple extension. Following the classic 'noddy' example. In [15]: cmplx_int32 Out[15]: type 'numpy.cmplx_int32' Now I want to add an attribute to this type. More precisely, I want a class attribute. cmplx_int32.test = 0 --- TypeError Traceback (most recent call last) /home/nbecker/numpy/ipython console in module() TypeError: can't set attributes of built-in/extension type 'numpy.cmplx_int32' What am I missing? class Dog(object): def __setattr__(self, attr, val): print TypeError: can't set attributes of built-in/extension print type 'Dog.cmplx_int32' d = Dog() d.test = 0 --output:-- TypeError: can't set attributes of built-in/extension type 'Dog.cmplx_int32' Not quite, I'm setting a class attribute, not an attribute on an instance. -- http://mail.python.org/mailman/listinfo/python-list
Odd behaviour of *.pth files and Apache
I tried searching the archives for information on this but nothing seemed to be germane. I am running Python sripts as CGI under Apache and I have a .pth file in site-packages that includes directory that has another .pth in it. Sometimes it picks up the paths in the second .pth and sometimes it does not. It always seems to work if I am working in a location not in the ServerRoot but if I use the main site it does not pick up the directories in the included .pth. I have tried changing just about everything with no difference. Can somone suggest any reason why Python would not recurse the .pth files sometimes and not others? -- D'Arcy J.M. Cain [EMAIL PROTECTED] | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: understaning self
On Feb 21, 6:34 am, Poppy [EMAIL PROTECTED] wrote: I've been searching online to try get a better understanding of what self does when I define this parameter in my class functions. All I'm finding is debates on whether self has any value to the language but that doesn't help me in my newbie question. So the code excerpt below is from Beginning Python Norton, Samuel, Aitel, Foster-Johnson, Richardson, Diamon, Parker, and Roberts. What I think self is doing is limiting the function call to only function in this class. So in the function below has calls self.has_various(), if I had a function called has_various in my program or another included class using self insures that the has_various below is the one used. Am I correct in my understanding? thanks, Zach- def has(self, food_name, quantity=1): has(food_name, [quantity]) - checks if the string food_name is in the fridge. quantity defaults to 1 returns True if there is enough, false otherwise. return self.has_various({food_name:quantity}) def has_various(self, foods): has various(foods) determines if the dictionary food_name has enough of every element to satisfy a request. returns true if there's enough, Fasle if there's not or if an element does not exist. try: for food in foods.keys(): if self.items[food] foods[food]: return False return True except KeyError: return False def bark(): print Yip, yip. class Dog(object): def __init__(the_obj_that_called_this_method): the_obj_that_called_this_method.name = Blackie print Initializing a dog object. def bark(the_obj_that_called_this_method): print 'My name is', the_obj_that_called_this_method.name print Woof, woof. d = Dog() d.bark() Because the variable name: 'the_obj_that_called_this_method' is too hard to type, by convention people use the variable name: 'self' instead. What I think self is doing is limiting the function call to only function in this class. No. Whenever you write obj.method_name, the '.' directs python to look inside obj's class definition for the specified method. When you call a function like this: def show(x): print x show('hello') python assigns the argument 'hello' to the parameter variable x. When you write: d.bark() even though there are no arguments specified in that method call, python secretly passes one argument to the method: the object on the left side of the '.'. -- http://mail.python.org/mailman/listinfo/python-list
Re: understaning self
On Feb 21, 11:49 am, 7stud [EMAIL PROTECTED] wrote: On Feb 21, 6:34 am, Poppy [EMAIL PROTECTED] wrote: I've been searching online to try get a better understanding of what self does when I define this parameter in my class functions. All I'm finding is debates on whether self has any value to the language but that doesn't help me in my newbie question. So the code excerpt below is from Beginning Python Norton, Samuel, Aitel, Foster-Johnson, Richardson, Diamon, Parker, and Roberts. What I think self is doing is limiting the function call to only function in this class. So in the function below has calls self.has_various(), if I had a function called has_various in my program or another included class using self insures that the has_various below is the one used. Am I correct in my understanding? thanks, Zach- def has(self, food_name, quantity=1): has(food_name, [quantity]) - checks if the string food_name is in the fridge. quantity defaults to 1 returns True if there is enough, false otherwise. return self.has_various({food_name:quantity}) def has_various(self, foods): has various(foods) determines if the dictionary food_name has enough of every element to satisfy a request. returns true if there's enough, Fasle if there's not or if an element does not exist. try: for food in foods.keys(): if self.items[food] foods[food]: return False return True except KeyError: return False def bark(): print Yip, yip. class Dog(object): def __init__(the_obj_that_called_this_method): the_obj_that_called_this_method.name = Blackie print Initializing a dog object. def bark(the_obj_that_called_this_method): print 'My name is', the_obj_that_called_this_method.name print Woof, woof. d = Dog() d.bark() Because the variable name: 'the_obj_that_called_this_method' is too hard to type, by convention people use the variable name: 'self' instead. What I think self is doing is limiting the function call to only function in this class. No. Whenever you write obj.method_name, the '.' directs python to look inside obj's class definition for the specified method. When you call a function like this: def show(x): print x show('hello') python assigns the argument 'hello' to the parameter variable x. When you write: d.bark() even though there are no arguments specified in that method call, python secretly passes one argument to the method: the object on the left side of the '.'. self is just a parameter variable in a function definition, and just like any other parameter variable in a function definition, self stands ready to have any argument passed to the function assigned to it. It just so happens, that *you* aren't the one specifying the *first* argument when you call a function in a class. Functions in a class are called 'methods', and all method calls of the form: d.bark() are transformed into this: d.bark(d) so bark() in d's class needs to be defined with one parameter variable--even though the method call looks like bark() should be defined with no parameter variables. On the other hand, if bark() were defined like this: class Dog(object): def __init__(the_obj_that_called_this_method): the_obj_that_called_this_method.name = Blackie print Initializing a dog object. def bark(the_obj_that_called_this_method, sound): print 'My name is', the_obj_that_called_this_method.name print sound Then you would call bark() like this: d = Dog() d.bark('Woof!') and the call: d.bark('Woof!') would be transformed into: d.bark(d, 'Woof!') As a result, bark() must be defined with two parameter variables: one for d and one for the string. -- http://mail.python.org/mailman/listinfo/python-list
Re: Script Running Time
I am trying to find a way to output how long a script took to run. Obviously the print would go at the end of the script, so it would be the time up till that point. I also run a PostgreSQL query inside the script and would like to separately show how long the query took to run. Is this even possible? Of course...depending on the resolution you need, you can do something like import datetime start_script = datetime.datetime.now() # do stuff start_postgresql = datetime.datetime.now() # make your PG call end_postgresql = datetime.datetime.now() # do remaining stuff end_script = datetime.datetime.now() pg_time_taken = end_postgresql - start_postgresql script_time_taken = end_script - start_script You than have pg_time_taken and script_time_taken (which are timedelta objects) that you can use for whatever display purposes you need. Alternatively, you can use time.clock() from time import clock clock() # do stuff start_pg = clock() # do pg stuff end_pg = clock() # rest of script end_script = clock() print Your script took %i seconds % end_script print Your PG took %i seconds % (end_pg - start_pg) -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: understaning self
On Thu, 21 Feb 2008 11:07:18 -0800 (PST) 7stud [EMAIL PROTECTED] wrote: d = Dog() d.bark('Woof!') and the call: d.bark('Woof!') would be transformed into: d.bark(d, 'Woof!') Actually, Dog.bark(d, 'Woof!') -- D'Arcy J.M. Cain [EMAIL PROTECTED] | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Double underscores -- ugly?
Has anyone thought about alternatives? Is there a previous discussion on this I can look up? Okay, I just emailed the BDFL and asked if he could tell me the origin of the double underscore syntax for __special__ methods, and what he said I'm pretty sure he won't mind me posting here: [Guido van Rossum said:] The specific naming convention was borrowed from the C standard, which reserves names like __FILE__ and __LINE__. The reason for needing a convention for system-assigned names was that I didn't want users to be surprised by the system giving a special meaning to methods or variables they had defined without intending that special meaning, while at the same time not wanting to introduce a physically separate namespace (e.g. a separate dict) for system names. I have no regrets. After that and this thread, I'm pretty good with it, I guess. :-) Cheers, Ben. -- http://mail.python.org/mailman/listinfo/python-list
Re: Article of interest: Python pros/cons for the enterprise
Jeff Schwab wrote: Bruno Desthuilliers wrote: Carl Banks a écrit : On Feb 20, 8:58 am, Tim Chase [EMAIL PROTECTED] wrote: You Used Python to Write WHAT? http://www.cio.com/article/185350 Furthermore, the power and expressivity that Python offers means that it may require more skilled developers. [...down to the summary...] Python may not be an appropriate choice if you: [...] * Rely on teams of less-experienced programmers. These developers may benefit from the wider availability of training for languages like Java and are less likely to make mistakes with a compile-time, type-checked language. (snip) C++ is a compile-time, type-checked language, which means it is totally safer for newbies than Python. Yep, your big company is totally safe with newbie C++ programmers. Mouarf ! Brillant demonstration, thanks Carl !-) (and BTW, +1 QOTW) NB: This is not a troll. (Please, nobody try to be cute with a yes it is reply.) c.l.python seem to be about the most close-minded of any of the currently popular language-specific news groups. It's just taken for granted that Perl and C++, two of my personal favorite things in this world, inherently favor ugly, buggy code. That is the farthest thing from the truth as I see it. You can (and plenty of people will) write terrible code in any language, including Python. I'm not sure I agree with that opinion. There is, however, a certain amount of what we might term defensive push back against static language bigots, some of whom come from the C++ camp. You are certainly right about bad programmers producing bad programs in any language. As far as C++ goes I usually defer to Alex Martelli, who used it a long time at IBM and is therefore well able to address its deficiencies. I believe you are also right in that the defensive posture tends to remain even after the bigots go away. For the record, there are many fine systems crafted in a mix of C++ and Python (EVE Online being a prime example). For any sufficiently large software system there will always be engineering problems, some of which are conditioned by choice of language and some by other factors. To use Python effectively, you have to know something about how it works, and the same is true of Perl and C++. But a newbie who's learning from a decent source (avoid the C++ for Morons style books) is likely (I contend) to be writing semi-useful programs about as fast as with Python, and to be writing heavy-duty work-horse programs far sooner. I agree that C++ is a nice language conceptually, and haven't used it enough to hit the hard problems. Perl is, and always has been, a language for getting your job done; when everything else failed, Perl and C++ got me through some of the toughest tasks of my life. Translating file formats, automating system-level tasks... And now that the C++ standard library is getting regular expressions, I can replace plenty of glued-together scripts with single-language, cohesive applications. Yes, Perl has always been a pragmatist's language (and indeed the author's favored acronym has the P stand for practical). I *did* have to use Perl for quite a while in the early days of the web and so got to experience its many delights at first hand. Again, you are probably right in saying we should accept Perl for its efficiencies (I believe even now it will generally beat Python on regular expression processing) and stop knocking it for its ill-though-out syntax and clumsy object implementation. I like Python, and I think it's got a brilliant future ahead of it. It is rapidly becoming the dynamic language of choice, especially for C++ projects. I am glad that Python can be extended straightforwardly in any C-linkable language. But this bashing of other powerful languages on the basis that they're hard to read and hard to use correctly is, frankly, nonsense. Agreed, mostly. I think Perl *is* hard to read (and frankly have been amazed at the intentions of the Perl 6 designers), but that shouldn't stop people using it, and isn't something that needs constant repetition. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Choosing a Metaclass?
Never mind, I've figured it out. The build_class function looks at the '__class__' attribute of the first base class if there's no explicit __metaclass__ attribute. By calling type directly, the __class__ attribute as returned by MyMeta is, in fact, type. Should have just looked at the source to begin with. On 2/21/08, Jeff McNeil [EMAIL PROTECTED] wrote: Hi list, Hopefully a quick metaclass question. In the following example, MyMeta is a metaclass that does not inherit directly from type: #!/usr/bin/python class MyMeta(object): def __new__(cls, name, bases, vars): print MyMeta.__new__ called for %s % name return type(name, bases, vars) class MetaWrapper(object): __metaclass__ = MyMeta class M(MetaWrapper): pass [EMAIL PROTECTED] ~]$ python t.py MyMeta.__new__ called for MetaWrapper [EMAIL PROTECTED] ~]$ When I run that script, it's apparent that although M inherits from MetaWrapper, it does not use MyMeta as it's metaclass. However, if I change MyMeta to be a subclass of builtin type, it works as I would expect: [EMAIL PROTECTED] ~]$ cat t.py #!/usr/bin/python class MyMeta(type): def __new__(cls, name, bases, vars): print MyMeta.__new__ called for %s % name return super(MyMeta, cls).__new__(cls, name, bases, vars) class MetaWrapper(object): __metaclass__ = MyMeta class M(MetaWrapper): pass [EMAIL PROTECTED] ~]$ python t.py MyMeta.__new__ called for MetaWrapper MyMeta.__new__ called for M [EMAIL PROTECTED] ~]$ How exactly does Python choose which MC it will use when building a class? It doesn't seem to me that the parent class of MyMeta should matter in this case? Thanks! Jeff -- http://mail.python.org/mailman/listinfo/python-list
Re[2]: python-ldap for plone 3 (python 2.4.4)
On 19/02/2008 at 07:12 p.m. Michael Ströder wrote: Erol Robaina Cepero wrote: I need download python-ldap for my plone 3.0.5 that use python 2.4.4. Do you know where I can find it? http://python-ldap.sourceforge.net/download.shtml There I found the version 2.3.1 for python 2.5. It works in python 2.4.4 too? thank a lot -- http://mail.python.org/mailman/listinfo/python-list
Re: packing things back to regular expression
On Feb 20, 7:36 pm, Amit Gupta [EMAIL PROTECTED] wrote: Before I read the message: I screwed up. Let me write again x = re.compile(CL(?Pname1[a-z]+)) # group name name1 is attached to the match of lowercase string of alphabet # Now I have a dictionary saying {name1, iamgood} # I would like a function, that takes x and my dictionary and return CLiamgood # If my dictionary instead have {name1, 123}, it gives error on processingit # # In general, I have reg-expression where every non-trivial match has a group-name. I want to do the reverse of reg-exp match. The function can take reg-exp and replace the group-matches from dictionary # I hope, this make it clear. If you want the string that matched the regex then you can use group(0) (or just group()): x = re.compile(CL(?Pname1[a-z]+)) m = x.search(something CLiamgood!something else) m.group() 'CLiamgood' -- http://mail.python.org/mailman/listinfo/python-list