Re: class initialization problem
EDIT: copy.copy did work in a simple python interactive session, but it caused infinite recursion in my real world code? Anyway what ever is going on (probably lack of sleep!) the cure all was using an arg in the initial function. So now i am good as gold ;-) WHY did i need do this you may ask? I am creating geometry with OpenGL. When you create a face you must specify a winding order (clockwise or counter clockwise) this winding order controls which side of the face will be visible (since only one side of a face is rendered). So to create a two sided face you must create two faces that share the exact same points, BUT have opposite windings, hence the need to create a face with a backface attribute that contains the mirrored face instance. So now i can move the frontface around and i have a handy reference to the backface so i can make it follow! class Face: def __init__(self, pts, nested=True): if nested: newpts = reverse(pts) self.backface = Face(pts, nested=False) def translate(self, v): #offset front and back face by vector two sided faces, yippie! And so ends another long day of coding. This is addicting. Does anybody know of a good Coders Anonymous group, i think i may have an addiction. 16 hours of strait coding with 4hrs sleep last night and only stopping for one meal (lunch) still have not ate dinner yet! Gheez! ;) -- http://mail.python.org/mailman/listinfo/python-list
Python history animation with code_swarm
Hi! Take a look at: http://vis.cs.ucdavis.edu/~ogawa/codeswarm/ code_swarm is a tool that generates a nice visual animation from a repository history. It also features one with the Python history for download, enhanced with a few comments. I hope this isn't old news and you enjoy it! Uli -- Sator Laser GmbH Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLite or files?
alex23 wrote: So what part of the standard library do you recommend using instead? Or was there no time for advice between snarkiness? As a matter of technique, I believe in fitting the storage to the particulars of the problem at hand. In my own projects, I will often employ simple text based formats (unix-rc, ini, or xml) whenever possible, and then roll the application specifics to suit it -- for any data that I expect that gaining good compression rates on later, will be favourable. Personally from what I've read in this thread, I would suggest using sqlite3 or an xml parser, depending on exactly what the OP wants. SQLite3 is fairly stable for routine use, and assuming that the OP has half a clue of figuring it out, would probably suit'em perfectly with much less bother then the standard xml brews. Over the years I have seen virtually everything tried for storing information, down to writing dictionaries out to a file for later slupin' eval() recovery, which is a method that I have occasionally thrown my hands up at I don't even want to mention some of the commercial products I've bumped into! -- TerryP. -- http://mail.python.org/mailman/listinfo/python-list
Re: class initialization problem
En Fri, 18 Sep 2009 03:12:46 -0300, rantingrick rantingr...@gmail.com escribió: I am creating geometry with OpenGL. When you create a face you must specify a winding order (clockwise or counter clockwise) this winding order controls which side of the face will be visible (since only one side of a face is rendered). So to create a two sided face you must create two faces that share the exact same points, BUT have opposite windings, hence the need to create a face with a backface attribute that contains the mirrored face instance. So now i can move the frontface around and i have a handy reference to the backface so i can make it follow! class Face: def __init__(self, pts, nested=True): if nested: newpts = reverse(pts) self.backface = Face(pts, nested=False) def translate(self, v): #offset front and back face by vector two sided faces, yippie! I'd use a factory: class Face: otherside = None def __init__(self, pts): self.pts = pts class BiFace(Face): otherside = None def BiFaceFactory(pts): front = BiFace(pts) back = BiFace(list(reversed(pts))) front.otherside = back back.otherside = front return front, back And so ends another long day of coding. This is addicting. Does anybody know of a good Coders Anonymous group, i think i may have an addiction. 16 hours of strait coding with 4hrs sleep last night and only stopping for one meal (lunch) still have not ate dinner yet! Gheez! ;) Remember, there is a whole world out there! -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of the Unicode standard
On Thursday 17 September 2009 15:29:38 Tim Rowe wrote: There are good reasons for it falling out of favour, though. At the time of the Sapir-Whorf hypothesis, anthropologists were arguing that members of a certain remote tribe did not experience grief on the death of a child because their language did not have a word for grief. They showed all the *signs* of grief -- weeping and wailing and so on -- and sometimes used metaphors (I feel as if my inside is being crushed). But because of the conviction at the time that if your language does not have a word for something, and you have never seen that object, then you __cannot__ think about it the anthropologists were convinced that this just looked and sounded like grief and wasn't actually grief. This is kind of convincing, when applied to an emotion like that. The whole thing is obviously a lot more complicated than the position I have taken here - if it weren't, then there would be no way for a language to change and grow, if it were literally true that you cannot think of something that you have no word for. By the way, at the moment I am thinking of a sort of purple blob-shaped monster with tentacles and fangs, that my language doesn't have a word for and that I have never seen. On your theory, how come I am thinking about it? I do not really believe you are thinking about a purple people eater. - you must be mistaken. :-) - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re:OT - people eaters - was: An assessment of the Unicode standard
On Friday 18 September 2009 06:39:57 Dennis Lee Bieber wrote: A one-eyed, one-horned, flying purple people eater? {Which brings up the confusing question... Is the eater purple, or does it eat purple people (which is why it is so rare... it only eats people caught in the last stages of suffocation G)} Snap (sort of). Does anybody know where the concept of the purple people eater comes from? I mean is there a children's book or something? - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: explicit call to __init__(self) in subclass needed?
Ethan Furman a écrit : Andrew MacKeith wrote: I create a class like this in Python-2.6 class Y(str): ... def __init__(self, s): ... pass ... y = Y('giraffe') y 'giraffe' How does the base class (str) get initialized with the value passed to Y.__init__() ? Is this behavior specific to the str type, or do base classes not need to be explicitly initialized? Andrew All the immutable base types (I *think*), use __new__ for object creation, not __init__. All types use __new__ for object *creation*. __init__ is for object initialization (which indeed happens in the __new__ method for immutable types, since the initializer works my mutating the newly created instance) !-) ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
specify max width to reportlab.canvas.drawString
I am using reportlab to create pdf documents, everything looks fine, how ever, is there a way to specify a max width to drawString function ? I mean cut the sentence and continue a step down... Cheers -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLite or files?
You can also make a SQLite database be in-memory, giving you the performance benefits of skipping the disk. Yes, I love the in-memory database -- especially for my automated testing in Django. However, the OP said that memory footprint was a concern (granted, I don't know how much data they were talking about -- a couple dozen rows in 1-2 tables might make this an attractive option). -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: explicit call to __init__(self) in subclass needed?
Andrew MacKeith a écrit : I create a class like this in Python-2.6 class Y(str): ... def __init__(self, s): ... pass ... y = Y('giraffe') y 'giraffe' How does the base class (str) get initialized with the value passed to Y.__init__() ? It happens in the __new__ method (which is the proper constructor) class Y(str): def __new__(cls, value, foo=foo): instance = str.__new__(cls, value) instance.foo = foo return instance def __repr__(self): return %s(%s, %s) % (type(self).__name__, self, self.foo) Is this behavior specific to the str type, or do base classes not need to be explicitly initialized? When you override a method in a derived class, it's your responsability to call on the parent(s) class(es) implementation. __init__ is not an exception to that rule. The point is that since __init__ works by mutating the newly created instance, it makes no sense to have a distinct __init__ for immutable types - which have their value set once for all at creation time. -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a pure Python chart drawing module
John Nagle wrote: That's a wrapper for Antigrain (http://www.antigrain.com/;), which is a C++ library. I'm trying hard to avoid dependencies on binary libraries with limited support. Builds exist only for Python 2.4 and 2.5. Huh? Matplotlib is a pretty phenomenal charting library, I use it routinely on both windows and linux, I've never had any compilation problems on Linux and never even needed to compile it on Windows. Writing if off as just a wrapper for antigrain is pretty insulting... Chris -- Simplistix - Content Management, Batch Processing Python Consulting - http://www.simplistix.co.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a pure Python chart drawing module
Grant Edwards wrote: On 2009-09-16, Alan G Isaac alan.is...@gmail.com wrote: Tkinter is part of the Python standard library: That doesn't mean you can depend on it being available. It doesn't get installed by default on some Linux distros. That's 'cos some linux distros feel the need to destroy python's packaging for their own silly reasons... Take them out and shoot them. Chris -- Simplistix - Content Management, Batch Processing Python Consulting - http://www.simplistix.co.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: recommendation for webapp testing?
Simon Brunning wrote: Mechanize is a superb library for its intended purpose - I use it all the time. It's lack of support for pages with JavaScript functionality, though, means it's not very useful at a testing tool for modern web sites. There's also zope.testbrowser, which is a handy wrapper around Mechanize. I wonder if they've done anything with JS there? Chris -- Simplistix - Content Management, Batch Processing Python Consulting - http://www.simplistix.co.uk -- http://mail.python.org/mailman/listinfo/python-list
Cross platform TTF font render from Python [was: Load TTF from pycairo under Windows]
Hi All, I need to render antialiased PNG images using TTF font files and UTF-8 text. It needs to be available at least on Linux and Windows. This is what I have tried: #1. PIL - it has some problems and I cannot use it. Specifically, the ImageFont.getsize() returns bad value for some fonts, and there are some TTF fonts that are rendered incorrectly (UTF-8) #2. pycairo - very sophisticated, nice features, knows and does everything correctly. However, has no native support for libfreetype. I could write an extension in C and use it from Linux. Not available on windows. #3. gdmodule - I tried to install in under windows without success. No binary installer available. #4. pygame - documentation looks great, it is cross platform. But the first example program I had tried has been terminated, printing out memory dump and complaining about double freeing some memory location. What other options do we have? Thanks, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I begin debugging a python memory leak?
Matthew Wilson wrote: I have a web app based on TurboGears 1.0. In the last few days, as traffic and usage has picked up, I noticed that the app went from using 4% of my total memory all the way up to 50%. I suspect I'm loading data from the database and somehow preventing garbage collection. Are there any tools that might help me out with this? http://pypi.python.org/pypi/guppy ...which will give you: http://guppy-pe.sourceforge.net/heapy_tutorial.html Good for finding out what's making up the memory usage. cheers, Chris -- Simplistix - Content Management, Batch Processing Python Consulting - http://www.simplistix.co.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a local variable scope.
On Sep 11, 7:36 pm, Johan Grönqvist johan.gronqv...@gmail.com wrote: Hi All, I find several places in my code where I would like to have a variable scope that is smaller than the enclosing function/class/module definition. This is one of the single major frustrations I have with Python and a important source of bugs for me. Here is a typical situation for i, j in visited: a[i, j] = 1 for i in range(rows): a[i, 0] = 1 for j in range(columns): a[0, i] = 1 As you see the third loop has a bug (I am actually mixing two logics: 1) using i for rows and j for columns 2) using i for the first iterator and j for the second). The result is a buggy code that is tolerated by Python. In C++ or Perl I don't have this problem. I wonder whether other people share this opinion and if we have ever had PEPs trying to address that... Marko -- http://mail.python.org/mailman/listinfo/python-list
Place the timer in Python script
How to place the timer in python code. I want calculate the python script execution time. ex : Start Timer : End Timer Execution Time : End Timer - Start Timer. How can we write the python code for this. Help would be appreciable. Thanks in Advance. Vamsi -- http://mail.python.org/mailman/listinfo/python-list
Tkinter - Text - bullets
My intention is to write a small custom widget displaying text where the text can have a simple wiki syntax. The main interest is to support heading, bold, italic, underline, itemization and enumeration. How can I implement itemization using the Tkinter.Text widget? (bullets) -- http://mail.python.org/mailman/listinfo/python-list
Re: Cross platform TTF font render from Python [was: Load TTF from pycairo under Windows]
Laszlo Nagy wrote: Hi All, I need to render antialiased PNG images using TTF font files and UTF-8 text. It needs to be available at least on Linux and Windows. This is what I have tried: #1. PIL - it has some problems and I cannot use it. Specifically, the ImageFont.getsize() returns bad value for some fonts, and there are some TTF fonts that are rendered incorrectly (UTF-8) #2. pycairo - very sophisticated, nice features, knows and does everything correctly. However, has no native support for libfreetype. I could write an extension in C and use it from Linux. Not available on windows. #3. gdmodule - I tried to install in under windows without success. No binary installer available. #4. pygame - documentation looks great, it is cross platform. But the first example program I had tried has been terminated, printing out memory dump and complaining about double freeing some memory location. ... the reportlab graphics renderPM(_renderPM) module does most things with T1 and TTF and works linux/win32. We use freetype2 internally to extract the curves from ttf and then draw them with libart_lgpl which does anti-aliasing. However, we don't render the fonts using freetype so hinting etc etc don't get done. I think something similar could be done directly with PIL and the antigrain extension. I'm surprised when you say that libfreetype isn't available on windows. It's a fairly hard road, but it can be travelled; certainly we built the parts of freetype that we needed into our extension. That required only a static library from freetype. I haven't needed to do this on windows since 2.1.5 so perhaps it's harder now. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: Place the timer in Python script
Vamsikrishna wrote: How to place the timer in python code. timeit ... it's in the standard library: http://docs.python.org/library/timeit.html Cheers, Ju -- Whomever controls the press, owns history -- Johann Gutenberg -- http://mail.python.org/mailman/listinfo/python-list
Re: specify max width to reportlab.canvas.drawString
juanefren wrote: I am using reportlab to create pdf documents, everything looks fine, how ever, is there a way to specify a max width to drawString function ? I mean cut the sentence and continue a step down... Cheers You'll get better results asking at the reportlab user group reportlab-us...@reportlab.com but there are some ways to do what you want just with simple string manipulation. Assuming you know the initial x, y and have setup a canvas with the font and sizeand the maximum width you want. from reportlab.lib.utils import simpleSplit L = simpleSplit(text,canv._fontname,canv._fontsize,maxWidth) for t in L: canv.drawString(x,y,t) y -= canv._leading I haven't tested this code, but that's the principle anyway for direct drawing to the canvas. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I begin debugging a python memory leak?
On 17 Sep., 02:10, Matthew Wilson m...@tplus1.com wrote: I have a web app based on TurboGears 1.0. In the last few days, as traffic and usage has picked up, I noticed that the app went from using 4% of my total memory all the way up to 50%. I suspect I'm loading data from the database and somehow preventing garbage collection. Are there any tools that might help me out with this? If have one of the following plattforms X86/Linux, AMD64/Linux, PPC32/Linux, PPC64/Linux and X86/Darwin (Mac OS X), have a look at valgrind. http://valgrind.org/ I used of often for searching the memory leaks in c++. It's a great tool to analyse your memory behaviour. Greetings -- http://mail.python.org/mailman/listinfo/python-list
python-win32 : cross database automation
Hello Everybody... I working on a client-server database solution. The system is normalized and is using MySQL. To automate some of processes I using Python. Part of the old database will be still running on Lotus Notes. After working on it, it seems that the best choice to directly manipulate Lotus is to use Python with win32COM - http://www.boddie.org.uk/python/COM.html . I installed ActivePython 2.6 compiler, which comes with integrated win32com. However, when I try to run.. it gives me the error: --x--x-- ActivePython 2.6.2.2 (ActiveState Software Inc.) based on Python 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. import win32com.client sess=win32com.client.Dispatch(Lotus.NotesSession) Traceback (most recent call last): File stdin, line 1, in module File C:\dev\python\Py26\lib\site-packages\win32com\client\__init__.py, line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File C:\dev\python\Py26\lib\site-packages\win32com\client\dynamic.py, line 98, in _GetGoodDispatchAndUserN ame return (_GetGoodDispatch(IDispatch, clsctx), userName) File C:\dev\python\Py26\lib\site-packages\win32com\client\dynamic.py, line 78, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) pywintypes.com_error: (-2147221005, 'Invalid class string', None, None) --x--x-- Any suggestions? Some help is mostly appreciated. I will keep working to get it fixed, after I post the working solution here. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a local variable scope.
markol...@gmail.com wrote: On Sep 11, 7:36 pm, Johan Grönqvist johan.gronqv...@gmail.com wrote: Hi All, I find several places in my code where I would like to have a variable scope that is smaller than the enclosing function/class/module definition. This is one of the single major frustrations I have with Python and a important source of bugs for me. Here is a typical situation for i, j in visited: a[i, j] = 1 for i in range(rows): a[i, 0] = 1 for j in range(columns): a[0, i] = 1 As you see the third loop has a bug (I am actually mixing two logics: 1) using i for rows and j for columns 2) using i for the first iterator and j for the second). The result is a buggy code that is tolerated by Python. In C++ or Perl I don't have this problem. I wonder whether other people share this opinion and if we have ever had PEPs trying to address that... Marko I agree. I wish there were a convenient way to switch this 'feature' on/off. I believe the vast majority of the time I do not want variable names leaking out into other scopes. OTOH, sometimes it's convenient. -- http://mail.python.org/mailman/listinfo/python-list
ANN: Resolver One 1.6.5 released
We are proud to announce the release of Resolver One, version 1.6.5. Resolver One is a Windows-based spreadsheet that integrates Python deeply into its recalculation loop, making the models you build more reliable and more maintainable. For versions 1.6 and 1.6.5, we've made it easier for people to share their spreadsheets. A new free player version means you can pass your work on to other people, and they can use it without having to buy anything, while a new Resolverlib makes calling your spreadsheets from IronPython programs as easy as calling a function. You can read more about Resolver One here: http://www.resolversystems.com/products/resolver-one/ We have a 31-day free trial version, so if you would like to take a look, you can download it from our website: http://www.resolversystems.com/download/ If you want to use Resolver One in an Open Source project, we offer free licenses for that: http://www.resolversystems.com/opensource/ Best regards, Giles -- Giles Thomas giles.tho...@resolversystems.com +44 (0) 20 7253 6372 17a Clerkenwell Road, London EC1M 5RD, UK VAT No.: GB 893 5643 79 Registered in England and Wales as company number 5467329. Registered address: 843 Finchley Road, London NW11 8NA, UK -- http://mail.python.org/mailman/listinfo/python-list
Re: class initialization problem
rantingrick wrote: On Sep 18, 12:24 am, OKB (not okblacke) brennospamb...@nobrenspambarn.net wrote: Perhaps you want to cut off the recursion at the first step, so that the nested instance itself does not have a nested instance. If so, add another parameter to __init__ that flags whether you are creating a top-level instance. yes, i also figured that out just a few minutes ago. class A(): def __init__(self, nested=ue) if nested: self.var =(nestedúlse) I think i have been staring at code too long and my noodle just shutdown for the evening :) Thanks! Don't forget the else: clause. If the nested flag is not set, set self.var = None. Otherwise, some user of this class has to face the possibility that he gets an attribute exception accessing the child. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a pure Python chart drawing module
Chris Withers ch...@simplistix.co.uk (CW) wrote: CW John Nagle wrote: That's a wrapper for Antigrain (http://www.antigrain.com/;), which is a C++ library. I'm trying hard to avoid dependencies on binary libraries with limited support. Builds exist only for Python 2.4 and 2.5. CW Huh? CW Matplotlib is a pretty phenomenal charting library, I use it routinely on CW both windows and linux, I've never had any compilation problems on Linux CW and never even needed to compile it on Windows. CW Writing if off as just a wrapper for antigrain is pretty insulting... *You* made up the just in that quote. The point was that the OP wants something that only needs Python. -- Piet van Oostrum p...@cs.uu.nl URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a pure Python chart drawing module
On Sep 15, 1:25 pm, John Nagle na...@animats.com wrote: I'm looking for something that can draw simple bar and pie charts in Python. I'm trying to find a Python package, not a wrapper for some C library, as this has to run on both Windows and Linux and version clashes are a problem. http://skimpygimpy.sourceforge.net includes charts and canvases that generate PNG using pure Python. Honestly, they aren't very pretty though :(. Also, if you are looking for web display also take a look at WHIFF Flash charts (using either open flash charts or amcharts) -- these are very pretty. http://aaron.oirt.rutgers.edu/myapp/docs/W1100_1600.openFlashCharts -- Aaron Watters === Tee front: 80 minutes / 16 positions / no protection back: Rutgers Rugby -- http://mail.python.org/mailman/listinfo/python-list
Re: Place the timer in Python script
Vamsikrishna wrote: How to place the timer in python code. I want calculate the python script execution time. ex : Start Timer : End Timer Execution Time : End Timer - Start Timer. How can we write the python code for this. Help would be appreciable. Thanks in Advance. Vamsi import time start = time.time() .. DO SOME STUFF print Elapsed time, time.time() - start Note that the time resolution on some OS's is better than others. So if you're on a system that only gives one-second resolution, you may want to use a different function. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Cross platform TTF font render from Python [was: Load TTF from pycairo under Windows]
... the reportlab graphics renderPM(_renderPM) module does most things with T1 and TTF and works linux/win32. We use freetype2 internally to extract the curves from ttf and then draw them with libart_lgpl which does anti-aliasing. I just tried reportlab and RenderPM. I got the same error others got: it looks impossible to use it for creating raster images. Details here: http://osdir.com/ml/python.reportlab.user/2005-06/msg00015.html I think something similar could be done directly with PIL and the antigrain extension. PIL would be ideal because it is lightweight and works on Windows and Linux too. But it is buggy. It doesn't render some east european (iso8859-2) characters, which we deperately need. Some TTF fonts are rendered incorrecly in PIL. Simply it doesn't work. I'm surprised when you say that libfreetype isn't available on windows. It's a fairly hard road, but it can be travelled; certainly we built the parts of freetype that we needed into our extension. That required only a static library from freetype. I haven't needed to do this on windows since 2.1.5 so perhaps it's harder now. I'll try anything that might work. In fact I have already seen articles about windows + libfreetype on the internet, but I could not find statically linked libraries built against Python 2.6. If you could send me a few hints where to start, I would greatly appreciate it. The only one requirement that I do not want to start writting C code and glue together libraries by hand. Not because I'm lazy but because I would like to have something that can be installed easily on new windows systems, and have no dependency problems out of the box. Thank you for your efforts. Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a local variable scope.
Neal Becker wrote: markol...@gmail.com wrote: On Sep 11, 7:36 pm, Johan Grönqvist johan.gronqv...@gmail.com wrote: Hi All, I find several places in my code where I would like to have a variable scope that is smaller than the enclosing function/class/module definition. This is one of the single major frustrations I have with Python and a important source of bugs for me. Here is a typical situation for i, j in visited: a[i, j] = 1 for i in range(rows): a[i, 0] = 1 for j in range(columns): a[0, i] = 1 As you see the third loop has a bug (I am actually mixing two logics: 1) using i for rows and j for columns 2) using i for the first iterator and j for the second). The result is a buggy code that is tolerated by Python. In C++ or Perl I don't have this problem. I wonder whether other people share this opinion and if we have ever had PEPs trying to address that... Marko I agree. I wish there were a convenient way to switch this 'feature' on/off. I believe the vast majority of the time I do not want variable names leaking out into other scopes. OTOH, sometimes it's convenient. loop != scope ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: explicit call to __init__(self) in subclass needed?
Bruno Desthuilliers wrote: Ethan Furman a écrit : Andrew MacKeith wrote: I create a class like this in Python-2.6 class Y(str): ... def __init__(self, s): ... pass ... y = Y('giraffe') y 'giraffe' How does the base class (str) get initialized with the value passed to Y.__init__() ? Is this behavior specific to the str type, or do base classes not need to be explicitly initialized? Andrew All the immutable base types (I *think*), use __new__ for object creation, not __init__. All types use __new__ for object *creation*. __init__ is for object initialization (which indeed happens in the __new__ method for immutable types, since the initializer works my mutating the newly created instance) !-) ~Ethan~ Thanks for the clarification, Bruno! ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a local variable scope.
On Friday 18 September 2009, Ethan Furman wrote: loop != scope true for python but in some languages the loop counter has a scope limited to the loop -- Wolfgang -- http://mail.python.org/mailman/listinfo/python-list
Re: Cross platform TTF font render from Python [was: Load TTF from pycairo under Windows]
Laszlo Nagy wrote: ... looks impossible to use it for creating raster images. Details here: http://osdir.com/ml/python.reportlab.user/2005-06/msg00015.html OK your error occurs because we need to set up the renderPM canvas with an initial font (for compatibility with the PDF canvas). You can down load a zip file containing suitable files from http://www.reportlab.org/ftp/pfbfer.zip. Just unzip the pfb/afm files into reportlab/fonts and stuff should work there after. . I'm surprised when you say that libfreetype isn't available on windows. It's a fairly hard road, but it can be travelled; certainly we built the parts of freetype that we needed into our extension. That required only a static library from freetype. I haven't needed to do this on windows since 2.1.5 so perhaps it's harder now. I'll try anything that might work. In fact I have already seen articles about windows + libfreetype on the internet, but I could not find statically linked libraries built against Python 2.6. If you could send me a few hints where to start, I would greatly appreciate it. The only one requirement that I do not want to start writting C code and glue together libraries by hand. Not because I'm lazy but because I would like to have something that can be installed easily on new windows systems, and have no dependency problems out of the box. Thank you for your efforts. Laszlo I could send you the statically linked library that I use, but it's a relocatable static library ie you need to combine it with some other extension. I'm using it to combine with the _renderPM.c file to create a standalone pyd. I suspect that's not what you want. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a pure Python chart drawing module
Piet van Oostrum p...@cs.uu.nl writes: Chris Withers ch...@simplistix.co.uk (CW) wrote: CW John Nagle wrote: That's a wrapper for Antigrain (http://www.antigrain.com/;), which is a C++ library. I'm trying hard to avoid dependencies on binary libraries with limited support. Builds exist only for Python 2.4 and 2.5. CW Huh? CW Matplotlib is a pretty phenomenal charting library, I use it CW routinely on both windows and linux, I've never had any CW compilation problems on Linux and never even needed to compile CW it on Windows. CW Writing if off as just a wrapper for antigrain is pretty CW insulting... *You* made up the just in that quote. The point was that the OP wants something that only needs Python. matplotlib can be used to generate .ps, .pdf and .svg files (all vectorial formats) without resorting to Antigrain Antigrain is used only in rasterizing, due to its better capabilities in the field of antialiasing, when you use matplotlib with an interactive backend; of course, if you're truly dispising Antigrain and are happy with a coarser display you can select interactive backends that DO NOT use Antigrain that's for the Antigrain wrapper otoh, if the OP intended a plotting library that does not use binary modules at all (then his reference to Antigrain was mostly fogging), then matplotlib is not for him % find matplotlib-0.99.0/| grep -v agg24 | grep '\.cpp$' | wc -l 23 % find matplotlib-0.99.0/| grep -v agg24 | grep '\.c$' | wc -l 5 % -- I wish we'd come to our senses and see there is no truth In those who promote the confusion for this ever changing mood. (people get ready people get ready people get ready people get ready) -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a local variable scope.
Thanks for all replies. First, two general comments, and then my conclusions: I did not intend to ask for new features, but my interest was in writing readable code that works in python 2.5, although I may upgrade to 2.6 soon. Also, what I gave was intended as a minimal example, and not a complete use case. Summarizing the answers, it seems that I will try to follow three suggestions: 1) In general, try to restructure the code into smaller modules and smaller functions. 2) When using many local variables bindings to create one larger object, define an inner function that hides those bindings. 3) If I define a few values intended to be used very locally, delete those after use. Thanks again, Johan -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a pure Python chart drawing module
On 2009-09-18, Chris Withers ch...@simplistix.co.uk wrote: Grant Edwards wrote: On 2009-09-16, Alan G Isaac alan.is...@gmail.com wrote: Tkinter is part of the Python standard library: That doesn't mean you can depend on it being available. It doesn't get installed by default on some Linux distros. That's 'cos some linux distros feel the need to destroy python's packaging What do you mean by Python's packaging? I used to build python from sources, and tcl/tk support was optional then as well. for their own silly reasons... Take them out and shoot them. I think you're overstating that a bit. AFAIK, when building Python from sources, tcl/tk support has always been optional as well. -- Grant Edwards grante Yow! Being a BALD HERO at is almost as FESTIVE as a visi.comTATTOOED KNOCKWURST. -- http://mail.python.org/mailman/listinfo/python-list
Re: OT - people eaters - was: An assessment of the Unicode standard
On Fri, Sep 18, 2009 at 3:26 AM, Hendrik van Rooyen hend...@microcorp.co.za wrote: Does anybody know where the concept of the purple people eater comes from? I mean is there a children's book or something? - Hendrik http://en.wikipedia.org/wiki/Purple_People_Eater -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I begin debugging a python memory leak?
Rainer Grimm r.gr...@science-computing.de writes: have a look at valgrind. Have you actually used that on Python? -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter - Text - bullets
On Sep 18, 11:57 am, Thomas Lehmann iris-und-thomas-lehm...@t- Online.de wrote: My intention is to write a small custom widget displaying text where the text can have a simple wiki syntax. The main interest is to support heading, bold, italic, underline, itemization and enumeration. How can I implement itemization using the Tkinter.Text widget? (bullets) Something like this maybe? from Tkinter import * root = Tk() txt = Text(root, wrap='word') txt.pack() txt.tag_configure('text_body', font=('Times', 18), lmargin1=0, lmargin2=0) txt.tag_configure('bulleted_list', font=('Times', 18), lmargin1='10m', lmargin2='15m', tabs=['15m']) txt.insert(END, uThis is a normal paragraph. Let's make it a bit long to see that it wraps as expected.\n, 'text_body') txt.insert(END, u\u00B7\tThis is the first item in the list.\n, 'bulleted_list') txt.insert(END, u\u00B7\tThis is the second item in the list. Let's make this one quite long too to see how it wraps.\n, 'bulleted_list') root.mainloop() HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: multiprocessing managers and socket connection.
On Aug 31, 10:41 pm, Terry terry.yin...@gmail.com wrote: On Aug 26, 7:25 pm, Chris chris...@gmail.com wrote: On Aug 25, 9:11 pm, Terry terry.yin...@gmail.com wrote: On Aug 25, 10:14 pm, Chris chris...@gmail.com wrote: I've been using multiprocessing managers and I really like the functionality. I have a question about reconnecting to a manager. I have a situation where I start on one machine (A) a manager that is listening and then on another machine (B) connects to that manager and uses its proxy object to call functions on the manager's computer; this all works as expected. But, if the manager from A shuts down, B's application won't notice because in the MP code it ignores socket error errno.ECONNREFUSED. If A becomes available again or is restarted, B doesn't automatically reconnect either and continue its operation. It's function is basically stopped. Here is the code from connection.py: while 1: try: s.connect(address) except socket.error, e: if e.args[0] != errno.ECONNREFUSED: # connection refused debug('failed to connect to address %s', address) raise time.sleep(0.01) else: break How can I have B automatically reconnect to A and continue its work once A is available again? I think you need to retry repeatedly until successfully connected. br, Terry I'm having issue after once connected. If the server goes down during a long-running connection. I would want to be notified so I could try to reconnect. I'm doing more experimenting now and will try to post an example. Hi Chris, Are you sure that the proxy object keeps a permanent connection to the server? br, Terry Sorry for the delay in response. I was able to find a solution by NOT using sockets, but using PIPES instead. The socket connections to the managers don't disconnect properly. Here's how to reproduce the situation (yes it's a stupid example, but that's the point): mp_manager_test.py -- http://python.pastebin.com/m3d10e343 mp_manager_test_client.py -- http://python.pastebin.com/m7a8fda4c run the following sequence which requires 3 shells. shell1 python mp_manager_test.py start_server shell2 python mp_manager_test_client.py shell3 python mp_manager_test.py stop_server Run the 3rd line while the client is accessing the server. When you use the socket for a connection, it hangs. When you use a PIPE, it throws the exception and actually exits; so I can catch the exception and handle it properly instead of having a hanging program. I am not sure how well a remote pipe will work though as I have yet to try it over a network between machines. To switch from socket to pipe, just switch the comments at the top in the source files: ADDY = (127.0.0.1,9000) ADDY2 = (127.0.0.1,9001) #ADDY = r'\\.\pipe\PipeName' #ADDY2 = r'\\.\pipe\PipeName2' Chris -- http://mail.python.org/mailman/listinfo/python-list
Not this one the other one, from a dictionary
Learning my way around list comprehension a bit. I wonder if someone has a better way to solve this issue. I have a two element dictionary, and I know one of the keys but not the other, and I want to look up the other one. So I have this dictionary: aDict = {'a': 'bob', 'b': 'stu'} I know that the dictionary contains two keys/value pairs, but I don't know the values nor that the keys will be 'a' and 'b'. I finally get one of the keys passed to me as variable BigOne. e.g.: BigOne = a The other key, call it littleOne remains unknown. It might be b but could be c, x, etc... I later need to access both values... I have something that works, with list comprehension - but wonder if there's a more brief/elegant way to get there: BigValu = aDict[BigOne] temp = [ thing for thing in aDict if thing != BigOne ] LittleValu = aDict[ temp[0] ] Any thoughts? - Ross. -- http://mail.python.org/mailman/listinfo/python-list
Re: multiprocessing managers and socket connection.
Is this server something you wrote from scratch or something that is just being used. Some details are left out -- --Original Message-- From: Chris chris...@gmail.com To: python-list@python.org Date: Fri, 18 Sep 2009 09:10:15 AM -0700 Subject: Re: multiprocessing managers and socket connection. On Aug 31, 10:41 pm, Terry terry.yin...@gmail.com wrote: On Aug 26, 7:25 pm, Chris chris...@gmail.com wrote: On Aug 25, 9:11 pm, Terry terry.yin...@gmail.com wrote: On Aug 25, 10:14 pm, Chris chris...@gmail.com wrote: I've been using multiprocessing managers and I really like the functionality. I have a question about reconnecting to a manager. I have a situation where I start on one machine (A) a manager that is listening and then on another machine (B) connects to that manager and uses its proxy object to call functions on the manager's computer; this all works as expected. But, if the manager from A shuts down, B's application won't notice because in the MP code it ignores socket error errno.ECONNREFUSED. If A becomes available again or is restarted, B doesn't automatically reconnect either and continue its operation. It's function is basically stopped. Here is the code from connection.py: while 1: try: s.connect(address) except socket.error, e: if e.args[0] != errno.ECONNREFUSED: # connection refused debug('failed to connect to address %s', address) raise time.sleep(0.01) else: break How can I have B automatically reconnect to A and continue its work once A is available again? I think you need to retry repeatedly until successfully connected. br, Terry I'm having issue after once connected. If the server goes down during a long-running connection. I would want to be notified so I could try to reconnect. I'm doing more experimenting now and will try to post an example. Hi Chris, Are you sure that the proxy object keeps a permanent connection to the server? br, Terry Sorry for the delay in response. I was able to find a solution by NOT using sockets, but using PIPES instead. The socket connections to the managers don't disconnect properly. Here's how to reproduce the situation (yes it's a stupid example, but that's the point): mp_manager_test.py -- http://python.pastebin.com/m3d10e343 mp_manager_test_client.py -- http://python.pastebin.com/m7a8fda4c run the following sequence which requires 3 shells. shell1 python mp_manager_test.py start_server shell2 python mp_manager_test_client.py shell3 python mp_manager_test.py stop_server Run the 3rd line while the client is accessing the server. When you use the socket for a connection, it hangs. When you use a PIPE, it throws the exception and actually exits; so I can catch the exception and handle it properly instead of having a hanging program. I am not sure how well a remote pipe will work though as I have yet to try it over a network between machines. To switch from socket to pipe, just switch the comments at the top in the source files: ADDY = (127.0.0.1,9000) ADDY2 = (127.0.0.1,9001) #ADDY = r'\\.\pipe\PipeName' #ADDY2 = r'\\.\pipe\PipeName2' Chris -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
How to print without spaces?
Hi, I don't want to print the space between 'a' and 'b'. Could somebody let me know how to do it? Regards, Peng $ python Python 2.5.2 (r252:60911, May 21 2008, 10:08:24) [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2 Type help, copyright, credits or license for more information. print a,b a b -- http://mail.python.org/mailman/listinfo/python-list
RE: How to print without spaces?
Hi, I don't want to print the space between 'a' and 'b'. Could somebody let me know how to do it? Regards, Peng $ python Python 2.5.2 (r252:60911, May 21 2008, 10:08:24) [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2 Type help, copyright, credits or license for more information. print a,b a b print a + b Cheers, Drea -- http://mail.python.org/mailman/listinfo/python-list
Re: How to print without spaces?
print a+b \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Why use locals()
On Mon, Sep 14, 2009 at 1:12 AM, Sean DiZazzo half.ital...@gmail.com wrote: Thanks for your explanation Steven. I see how it can be valuable, but it seems to always break the second rule of Zen. I don't really want to get into the code of debuggers, but I guess I can see how they might have no other way to know what local variables have been set. ~Sean The zeroth rule of zen is don't take the rules so seriously. They're really more like guidelines anyway. Regards, ~simon -- http://mail.python.org/mailman/listinfo/python-list
Re: multiprocessing managers and socket connection.
On Sep 18, 12:42 pm, bouncy...@gmail.com bouncy...@gmail.com wrote: Is this server something you wrote from scratch or something that is just being used. Some details are left out -- --Original Message-- From: Chris chris...@gmail.com To: python-l...@python.org Date: Fri, 18 Sep 2009 09:10:15 AM -0700 Subject: Re: multiprocessing managers and socket connection. On Aug 31, 10:41 pm, Terry terry.yin...@gmail.com wrote: On Aug 26, 7:25 pm, Chris chris...@gmail.com wrote: On Aug 25, 9:11 pm, Terry terry.yin...@gmail.com wrote: On Aug 25, 10:14 pm, Chris chris...@gmail.com wrote: I've been using multiprocessing managers and I really like the functionality. I have a question about reconnecting to a manager. I have a situation where I start on one machine (A) a manager that is listening and then on another machine (B) connects to that manager and uses its proxy object to call functions on the manager's computer; this all works as expected. But, if the manager from A shuts down, B's application won't notice because in the MP code it ignores socket error errno.ECONNREFUSED. If A becomes available again or is restarted, B doesn't automatically reconnect either and continue its operation. It's function is basically stopped. Here is the code from connection.py: while 1: try: s.connect(address) except socket.error, e: if e.args[0] != errno.ECONNREFUSED: # connection refused debug('failed to connect to address %s', address) raise time.sleep(0.01) else: break How can I have B automatically reconnect to A and continue its work once A is available again? I think you need to retry repeatedly until successfully connected. br, Terry I'm having issue after once connected. If the server goes down during a long-running connection. I would want to be notified so I could try to reconnect. I'm doing more experimenting now and will try to post an example. Hi Chris, Are you sure that the proxy object keeps a permanent connection to the server? br, Terry Sorry for the delay in response. I was able to find a solution by NOT using sockets, but using PIPES instead. The socket connections to the managers don't disconnect properly. Here's how to reproduce the situation (yes it's a stupid example, but that's the point): mp_manager_test.py --http://python.pastebin.com/m3d10e343 mp_manager_test_client.py --http://python.pastebin.com/m7a8fda4c run the following sequence which requires 3 shells. shell1 python mp_manager_test.py start_server shell2 python mp_manager_test_client.py shell3 python mp_manager_test.py stop_server Run the 3rd line while the client is accessing the server. When you use the socket for a connection, it hangs. When you use a PIPE, it throws the exception and actually exits; so I can catch the exception and handle it properly instead of having a hanging program. I am not sure how well a remote pipe will work though as I have yet to try it over a network between machines. To switch from socket to pipe, just switch the comments at the top in the source files: ADDY = (127.0.0.1,9000) ADDY2 = (127.0.0.1,9001) #ADDY = r'\\.\pipe\PipeName' #ADDY2 = r'\\.\pipe\PipeName2' Chris --http://mail.python.org/mailman/listinfo/python-list No, that's a full example posted in those 2 files right there; there is nothing else needed to run it. -- http://mail.python.org/mailman/listinfo/python-list
detmining name during an assignment
I have an app that uses Python scripting. When a user creates a new object: objName = newObject() I'd like the newObject be able to use objName as its internal name. So, if a user says: cube1 = Cube() A cube1 object should apear in the scene list. I believe this means I need to determine that a namespace assignment is going on from inside the object's init code or by using properties. I've searched the web but can't find a simple answer. Is there some way to use the inspect module get source code functoins? How would I get the code for the current interpreter line causing the init code to execute? Thanks very much in advance, Jamie Riotto -- http://mail.python.org/mailman/listinfo/python-list
Re: detmining name during an assignment
On Fri, Sep 18, 2009 at 10:00 AM, Jamie Riotto jamie.rio...@gmail.comwrote: I have an app that uses Python scripting. When a user creates a new object: objName = newObject() I'd like the newObject be able to use objName as its internal name. Almost this exact same question came up not so long ago, which is a bit strange. The short of it is, you can't. So, if a user says: cube1 = Cube() A cube1 object should apear in the scene list. I believe this means I need to determine that a namespace assignment is going on from inside the object's init code or by using properties. That's the thing: during the object's __init__, a namespace assignment isn't going on. newObject() initializes and creates an object, returning it. There's no way for it to tell what happens to that object after. It might just get discarded and garbage collected immediately. Or it might get inserted into a dictionary. Or it might end up bound to a name in a namespace. It has no idea: all of that happens completely -after- the __init__ is completely finished and returned. There isn't a simple answer because Python just doesn't work like that :) An assignment statement doesn't create a variable or a cell or anything of that nature, it simply labels an object with a particular name that's only meaningful in a certain namespace. A given object can have any number of such labels and the object can't actually tell what those are. --S -- http://mail.python.org/mailman/listinfo/python-list
Re: detmining name during an assignment
On Sep 18, 1:00 pm, Jamie Riotto jamie.rio...@gmail.com wrote: I have an app that uses Python scripting. When a user creates a new object: objName = newObject() I'd like the newObject be able to use objName as its internal name. So, if a user says: cube1 = Cube() A cube1 object should apear in the scene list. I believe this means I need to determine that a namespace assignment is going on from inside the object's init code or by using properties. I've searched the web but can't find a simple answer. Is there some way to use the inspect module get source code functoins? How would I get the code for the current interpreter line causing the init code to execute? Thanks very much in advance, Jamie Riotto Save yourself a lot of trouble and just assign a name manually: class foo: def __init__(self, name): self.name = name some_foo = foo(some_foo) -- http://mail.python.org/mailman/listinfo/python-list
Re: Not this one the other one, from a dictionary
Learning my way around list comprehension a bit. I wonder if someone has a better way to solve this issue. I have a two element dictionary, and I know one of the keys but not the other, and I want to look up the other one. Several ways occur to me. Of the various solutions I played with, this was my favorite (requires Python2.4+ for generator expressions): d = {'a': 'alice', 'b':'bob'} known = 'a' other_key, other_value = ( (k,v) for k,v in d.iteritems() if k != known ).next() If you just want one or the other, you can simplify that a bit: other_key = (k for k in d.iterkeys() if k != known).next() other_key = (k for k in d if k != known).next() or other_value = (v for k,v in d.iteritems() if k != known).next() If you're using pre-2.4, you might tweak the above to something like other_key, other_value = [ (k,v) for k,v in d.iteritems() if k != known ][0] other_key = [k for k in d if k != known)[0] other_value = [k for k in d.iteritems if k != known][0] Hope this helps, -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: detmining name during an assignment
Jamie Riotto schrieb: I have an app that uses Python scripting. When a user creates a new object: objName = newObject() I'd like the newObject be able to use objName as its internal name. So, if a user says: cube1 = Cube() A cube1 object should apear in the scene list. I believe this means I need to determine that a namespace assignment is going on from inside the object's init code or by using properties. As the others already explained to you there is no way to archive your goal with an assignment to a local or global variable. But you can follow a different approach: class Scene(object): def __setattr__(self, name, value): super(Scene, self).__setattr__(name value) if isinstance(value, SceneObject): value.name = name value.scene = self class SceneObject(object): pass class Cube(SceneObject): pass scene = Scene() scene.cube1 = Cube() Have fun! Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: detmining name during an assignment
Jamie, Hi. I have an app that uses Python scripting. When a user creates a new object: objName = newObject() newObject should technically speaking be newClass() but nevermind :-) I'd like the newObject be able to use objName as its internal name. So, if a user says: cube1 = Cube() A cube1 object should apear in the scene list. I believe this means I need to determine that a namespace assignment is going on from inside the object's init code or by using properties. A class's init code is like a constructor (guessing you know about ctors here). Basically, initialising all the variables that particular class uses. In this instance calling Cube( ) would cause it to call up the __init__(self) function in Cube class and do whatever it does there such as defining a variable, calling other initialisation functions etc... I've searched the web but can't find a simple answer. Is there some way to use the inspect module get source code functoins? How would I get the code for the To get the source code for a function, you can manually inspect it. To get the functions that a class exports, use can use dir(object_of_a_class) in Python shell (this may not be what you want but I write it anyway because I feel like writing today). You can also run help(module_name_here) to see the docs+functions. current interpreter line causing the init code to execute? I am starting to suspect that you are very much asking for a debugger ;-) Look up pdb;a Python debugger. -- Regards, Ishwor Gurung -- http://mail.python.org/mailman/listinfo/python-list
Re: Not this one the other one, from a dictionary
Ross Hi. So I have this dictionary: aDict = {'a': 'bob', 'b': 'stu'} Yes. I know that the dictionary contains two keys/value pairs, but I don't know the values nor that the keys will be 'a' and 'b'. I finally get one of the keys passed to me as variable BigOne. e.g.: BigOne = a Right. aDict[BigOne] will give you - 'bob' which may/maynot be what you want by the looks of it, you want aDict[BigOne]. aDict.keys() ['a', 'b'] aDict.values() ['bob', 'stu'] keys() / values() return list so you do not have to worry about explicitly getting list. The other key, call it littleOne remains unknown. It might be b but could be c, x, etc... I later need to access both values... I have something that works, with list comprehension - but wonder if there's a more brief/elegant way to get there: If you know the dictionary name in this case aDict (which you don't mention you know or not), you can just traverse it using easily as such: for k in aDict: print k, aDict[k]; [[i,a[i]] for i in aDict] [['a', 'bob'], ['b', 'stu']] [[i,a[i]] for i in aDict][0] ['a', 'stu'] [[i,a[i]] for i in aDict][0][0] 'a' [[i,a[i]] for i in aDict][0][1] 'bob' -- Regards, Ishwor Gurung -- http://mail.python.org/mailman/listinfo/python-list
Re: How to improve this code?
elements_present = lambda seq, match: any(((x in match) for x in seq)) On Mon, 14 Sep 2009 19:08:59 -0600, Oltmans rolf.oltm...@gmail.com wrote: Hello, Is there someway I can improve the following code(pythonically)? (Copying from IDLE) match=[1,2,3,4,5] def elementsPresent(aList): result=False if not aList: return False for e in aList: if e in match: result=True else: result = False return result elementsPresent([6,7,8,9,5]) # should return True because 5 is present in list named match. Is there somehow I can improve code in elementsPresent()? I'm not a very good programmer but I sense that idea of using a variable named 'result' inside elementsPresent() doesn't sound very good. Any ideas will be highly appreciated. Thanks, Oltmans -- Kind regards, Sergey Simonenko. -- http://mail.python.org/mailman/listinfo/python-list
Python based paramiko package acting up on Linux, code works fine on windows
I've tried to post to the mailing list for paramiko and contact the author, but it seems he's having some mailing list problems. Anyways, I have this small example that works just fine on Windows against Python 2.6.2, but fails on Ubuntu against 2.6.2. Here is the code: import subprocess import os import re import paramiko import sqlite3 import datetime import base64 import sys import logging from paramiko.rsakey import RSAKey class OpenSessions: sshconns = [] sqlconn = sqlite3.connect('test.sqlite') def __init__(self): self.sqlconn.row_factory = sqlite3.Row sqlcur = self.sqlconn.cursor() sqlcur.execute(select host, pub_key, username, password, private_key from ssh_hosts) rows = sqlcur.fetchall() for row in rows: sshconn = paramiko.SSHClient() sshconn._system_host_keys.add(row[host], ssh-rsa, RSAKey (data=base64.decodestring(row[pub_key]))) if row[private_key] != : sshconn.connect(hostname=row[host], username=row[username], pkey=RSAKey(data=base64.decodestring(row[private_key]))) elif row[password] != : sshconn.connect(hostname=row[host], username=row[username], password=row[password], look_for_keys=False, timeout=60) self.sshconns.append(sshconn) output = for conn in self.sshconns: print conn.exec_command(uname -a)[1].readline() exit() if __name__== '__main__': sessions = OpenSessions() The code fails with this trace: Traceback (most recent call last): File test.py, line 41, in module sessions = OpenSessions() File test.py, line 36, in __init__ print chan.exec_command(uname -a)[1].readline() File /usr/local/lib/python2.6/dist-packages/paramiko/channel.py, line 212, in exec_command self._wait_for_event() File /usr/local/lib/python2.6/dist-packages/paramiko/channel.py, line 1077, in _wait_for_event raise e paramiko.SSHException: Channel closed. Exception in thread Thread-1 (most likely raised during interpreter shutdown): Traceback (most recent call last): File /usr/lib/python2.6/threading.py, line 525, in __bootstrap_inner File /usr/local/lib/python2.6/dist-packages/paramiko/transport.py, line 1567, in run type 'exceptions.AttributeError': 'NoneType' object has no attribute 'error' This well beyond my abilities to debug. All I know is that it always works on Windows, and always fails in Ubuntu (which of course is where I need use the code). Any suggestions? I know the paramiko mailing list would probably be the better spot for this, but like I said, its got some issues right now. OLIVER -- http://mail.python.org/mailman/listinfo/python-list
Re: Not this one the other one, from a dictionary
Thanks Tim (and Ishwor) for the suggestions, those are structures that somewhat new to me - looks good! I'll play with those.At this rate I may soon almost know what I'm doing. Rgds Ross. On 18-Sep-09, at 1:19 PM, Tim Chase wrote: Learning my way around list comprehension a bit. I wonder if someone has a better way to solve this issue. I have a two element dictionary, and I know one of the keys but not the other, and I want to look up the other one. Several ways occur to me. Of the various solutions I played with, this was my favorite (requires Python2.4+ for generator expressions): d = {'a': 'alice', 'b':'bob'} known = 'a' other_key, other_value = ( (k,v) for k,v in d.iteritems() if k != known ).next() If you just want one or the other, you can simplify that a bit: other_key = (k for k in d.iterkeys() if k != known).next() other_key = (k for k in d if k != known).next() or other_value = (v for k,v in d.iteritems() if k != known).next() If you're using pre-2.4, you might tweak the above to something like other_key, other_value = [ (k,v) for k,v in d.iteritems() if k != known ][0] other_key = [k for k in d if k != known)[0] other_value = [k for k in d.iteritems if k != known][0] Hope this helps, -tkc -- http://mail.python.org/mailman/listinfo/python-list
Granularity of OSError
I've often come across the idea that good Python style deals with potential errors using an EAFP (easier to ask forgiveness than permission) strategy rather than a LBYL (look before you leap) strategy. For example, LBYL would look like this: if os.path.isfile(some_file): os.unlink(some_file) In contrast, EAFP would look like this: try: os.unlink(some_file) except OSError: pass But, as written, the EAFP code above is not satisfactory, because there can be OSError's triggered for reasons other than the non-existence of the regular file some_file. What one needs is a finer granularity of exception, mapping to exactly the error that one is guarding against. Is there a standard approach to refining the granularity of exceptions such as OSError? The only approach I can think of is to somehow parse the error string (assuming is available) to determine whether the exception is indeed of the specific kind we're trying to catch. But this strikes me as grossly inelegant. Is there a better way? (BTW, the problem is generic, because client code has no control over the specificity of the exceptions raised by a library module. If these exceptions turn out to be too broad, client code has to somehow deal with this reality, at least in the short term.) TIA! kynn -- http://mail.python.org/mailman/listinfo/python-list
Re: explicit call to __init__(self) in subclass needed?
Bruno Desthuilliers wrote: Andrew MacKeith a écrit : I create a class like this in Python-2.6 class Y(str): ... def __init__(self, s): ... pass ... y = Y('giraffe') y 'giraffe' How does the base class (str) get initialized with the value passed to Y.__init__() ? It happens in the __new__ method (which is the proper constructor) class Y(str): def __new__(cls, value, foo=foo): instance = str.__new__(cls, value) instance.foo = foo return instance def __repr__(self): return %s(%s, %s) % (type(self).__name__, self, self.foo) Is this behavior specific to the str type, or do base classes not need to be explicitly initialized? When you override a method in a derived class, it's your responsability to call on the parent(s) class(es) implementation. __init__ is not an exception to that rule. The point is that since __init__ works by mutating the newly created instance, it makes no sense to have a distinct __init__ for immutable types - which have their value set once for all at creation time. Thanks for the explanation, Bruno. I have been successfully using a class derived from str, and in that class I add a lot of extra data to the derived class instance in the __init__ method of the derived class, so it is possible to mutate the derived class __dict__, even if the base class data remains immutable. See example below. The __init__ must have the same arguments as the base class. class Y(str): ... def __init__(self): ... self.color = 'blue' ... y = Y('Parrot') Traceback (most recent call last): File stdin, line 1, in module TypeError: __init__() takes exactly 1 argument (2 given) class Y(str): ... def __init__(self, text): ... self.color = 'blue' ... y = Y('Parrot') y 'Parrot' y.color 'blue' y[:3] 'Par' y.size = 'small' y.__class__ class '__main__.Y' But you can get bitten if you do something that returns a new object y += 'Tail' y 'ParrotTail' y.color Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'str' object has no attribute 'color' y.__class__ type 'str' Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: Granularity of OSError
On Sep 18, 11:54 am, kj no.em...@please.post wrote: I've often come across the idea that good Python style deals with potential errors using an EAFP (easier to ask forgiveness than permission) strategy rather than a LBYL (look before you leap) strategy. For example, LBYL would look like this: if os.path.isfile(some_file): os.unlink(some_file) In contrast, EAFP would look like this: try: os.unlink(some_file) except OSError: pass But, as written, the EAFP code above is not satisfactory, because there can be OSError's triggered for reasons other than the non-existence of the regular file some_file. What one needs is a finer granularity of exception, mapping to exactly the error that one is guarding against. Is there a standard approach to refining the granularity of exceptions such as OSError? The only approach I can think of is to somehow parse the error string (assuming is available) to determine whether the exception is indeed of the specific kind we're trying to catch. But this strikes me as grossly inelegant. Is there a better way? (BTW, the problem is generic, because client code has no control over the specificity of the exceptions raised by a library module. If these exceptions turn out to be too broad, client code has to somehow deal with this reality, at least in the short term.) TIA! kynn You can access the exception object which gives you greater detail. try: os.unlink(some_file) except OSError, e: print e.errno print e.strerror if e.errno == 2: pass else: raise If it's the error you are looking for, handle it, or else raise. ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: How to print without spaces?
I don't want to print the space between 'a' and 'b'. Could somebody let me know how to do it? print a,b a b Since you are new, you should also be aware of: print %s%s % (a, b) -- http://mail.python.org/mailman/listinfo/python-list
Re: Granularity of OSError
On Sep 18, 3:05 pm, Sean DiZazzo half.ital...@gmail.com wrote: On Sep 18, 11:54 am, kj no.em...@please.post wrote: I've often come across the idea that good Python style deals with potential errors using an EAFP (easier to ask forgiveness than permission) strategy rather than a LBYL (look before you leap) strategy. For example, LBYL would look like this: if os.path.isfile(some_file): os.unlink(some_file) In contrast, EAFP would look like this: try: os.unlink(some_file) except OSError: pass But, as written, the EAFP code above is not satisfactory, because there can be OSError's triggered for reasons other than the non-existence of the regular file some_file. What one needs is a finer granularity of exception, mapping to exactly the error that one is guarding against. Is there a standard approach to refining the granularity of exceptions such as OSError? The only approach I can think of is to somehow parse the error string (assuming is available) to determine whether the exception is indeed of the specific kind we're trying to catch. But this strikes me as grossly inelegant. Is there a better way? (BTW, the problem is generic, because client code has no control over the specificity of the exceptions raised by a library module. If these exceptions turn out to be too broad, client code has to somehow deal with this reality, at least in the short term.) TIA! kynn You can access the exception object which gives you greater detail. try: os.unlink(some_file) except OSError, e: print e.errno print e.strerror if e.errno == 2: pass else: raise If it's the error you are looking for, handle it, or else raise. ~Sean I do this myself in a lot of places, almost exactly like this. It's slightly clearer to use 'if e.errno == errno.ENOENT' in my opinion, but, whatever. The only place I've run into issues with this is when dealing with socket programming across operating systems. Python on Windows exports all of the WSA errors when dealing with sockets, but 'WSAEHOSTUNREACH' is not the same as 'ENETUNREACH.' In cases like that, you've got to be careful to check for all possible variations of the same error if you care about supporting Windows. Thanks, Jeff mcjeff.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Granularity of OSError
In 254eac4d-ce19-4af9-8c6a-5be8e7b0f...@u16g2000pru.googlegroups.com Sean DiZazzo half.ital...@gmail.com writes: On Sep 18, 11:54=A0am, kj no.em...@please.post wrote: I've often come across the idea that good Python style deals with potential errors using an EAFP (easier to ask forgiveness than permission) strategy rather than a LBYL (look before you leap) strategy. For example, LBYL would look like this: if os.path.isfile(some_file): =A0 =A0 os.unlink(some_file) In contrast, EAFP would look like this: try: =A0 =A0 os.unlink(some_file) except OSError: =A0 =A0 pass But, as written, the EAFP code above is not satisfactory, because there can be OSError's triggered for reasons other than the non-existence of the regular file some_file. What one needs is a finer granularity of exception, mapping to exactly the error that one is guarding against. Is there a standard approach to refining the granularity of exceptions such as OSError? =A0The only approach I can think of is to somehow parse the error string (assuming is available) to determine whether the exception is indeed of the specific kind we're trying to catch. But this strikes me as grossly inelegant. =A0Is there a better way? (BTW, the problem is generic, because client code has no control over the specificity of the exceptions raised by a library module. If these exceptions turn out to be too broad, client code has to somehow deal with this reality, at least in the short term.) TIA! kynn You can access the exception object which gives you greater detail. try: os.unlink(some_file) except OSError, e: print e.errno print e.strerror if e.errno =3D=3D 2: pass else: raise If it's the error you are looking for, handle it, or else raise. Thanks, that's very handy. kynn -- http://mail.python.org/mailman/listinfo/python-list
Re: Not this one the other one, from a dictionary
2009/9/18 Ross ros...@gmail.com: Learning my way around list comprehension a bit. I wonder if someone has a better way to solve this issue. I have a two element dictionary, and I know one of the keys but not the other, and I want to look up the other one. So I have this dictionary: aDict = {'a': 'bob', 'b': 'stu'} I know that the dictionary contains two keys/value pairs, but I don't know the values nor that the keys will be 'a' and 'b'. I finally get one of the keys passed to me as variable BigOne. e.g.: BigOne = a The other key, call it littleOne remains unknown. It might be b but could be c, x, etc... I later need to access both values... I have something that works, with list comprehension - but wonder if there's a more brief/elegant way to get there: BigValu = aDict[BigOne] temp = [ thing for thing in aDict if thing != BigOne ] LittleValu = aDict[ temp[0] ] Any thoughts? - Ross. -- http://mail.python.org/mailman/listinfo/python-list Hi, not a list comprehension, but another useful approach to get the complement of (a) given item(s) might be the set operations. (As you are working with dict keys, the requirements for set elements are automatically fulfilled. data_dict = {'a': 'bob', 'b': 'stu'} not_wanted_key = a other_key = (set(data_dict.iterkeys()) - set([not_wanted_key,])).pop() other_key 'b' data_dict[other_key] 'stu' vbr -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I begin debugging a python memory leak?
On Sep 18, 5:42 pm, Paul Rubin http://phr...@nospam.invalid wrote: Rainer Grimm r.gr...@science-computing.de writes: have a look at valgrind. Have you actually used that on Python? Not with python as far I can remember. But often with C++ executables, as i mentioned it. I you look at http://valgrind.org/info/ there stands: Valgrind has been used on programs written partly or entirely in C, C+ +, Java, Perl, Python, assembly code, Fortran, Ada, and many others. It exists also a extension for python http://blogs.gnome.org/jamesh/2008/03/24/python-valgrind/ , to get rid of the false positiv errors. So it should be worth a try. -- http://mail.python.org/mailman/listinfo/python-list
Re: detmining name during an assignment
En Fri, 18 Sep 2009 14:38:08 -0300, Christian Heimes li...@cheimes.de escribió: Jamie Riotto schrieb: I have an app that uses Python scripting. When a user creates a new object: objName = newObject() I'd like the newObject be able to use objName as its internal name. As the others already explained to you there is no way to archive your goal with an assignment to a local or global variable. But you can follow a different approach: class Scene(object): def __setattr__(self, name, value): super(Scene, self).__setattr__(name value) if isinstance(value, SceneObject): value.name = name value.scene = self class SceneObject(object): pass class Cube(SceneObject): pass scene = Scene() scene.cube1 = Cube() As the OP said it's being used for scripting some application, presumably the application can control the environment on which the script is run. One may use the Scene class above as the globlal scope when executing the script: scene = Scene() code = cube1 = Cube(); print cube1.name exec code in Scene (well, not exactly, Scene should inherit from dict and override __setitem__ instead, but you get the idea) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: How to print without spaces?
On Sep 18, 9:49 pm, Andreas Tawn andreas.t...@ubisoft.com wrote: Hi, I don't want to print the space between 'a' and 'b'. Could somebody let me know how to do it? Regards, Peng $ python Python 2.5.2 (r252:60911, May 21 2008, 10:08:24) [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2 Type help, copyright, credits or license for more information. print a,b a b print a + b Cheers, Drea What if I want to print 1 to 100 in a loop without spaces in between? I think that is the OPs question. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to print without spaces?
On Fri, Sep 18, 2009 at 4:16 PM, koranthala koranth...@gmail.com wrote: What if I want to print 1 to 100 in a loop without spaces in between? I think that is the OPs question. In that case I would skip using print entirely, and use something like this: import sys for i in xrange(100): sys.stdout.write(str(i)) sys.stdout.write('\n') That allows you to bypass any of the behavior of the print builtin that you don't want. -- Jerry -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a local variable scope.
En Fri, 18 Sep 2009 10:55:47 -0300, Johan Grönqvist johan.gronqv...@gmail.com escribió: Summarizing the answers, it seems that I will try to follow three suggestions: 1) In general, try to restructure the code into smaller modules and smaller functions. That's a good thing - manageable modules and functions. 2) When using many local variables bindings to create one larger object, define an inner function that hides those bindings. I'd say, not to *hide* those bindings, but because the code fragment deserves logically to become a function. 3) If I define a few values intended to be used very locally, delete those after use. Why bother? Unless they're big objects and you want to ensure they get deleted as soon as possible. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: How to print without spaces?
On Friday 18 September 2009, koranthala wrote: What if I want to print 1 to 100 in a loop without spaces in between? I think that is the OPs question. arr = ['a', 'b', 'c', 'andsoon'] print ''.join(arr) -- Wolfgang -- http://mail.python.org/mailman/listinfo/python-list
Re: Application-global switches?
In 579a15bf-83c0-4228-9079-bbaac1222...@o13g2000vbl.googlegroups.com Marius Gedminas mged...@gmail.com writes: On Sep 4, 9:29=A0pm, kj no.em...@please.post wrote: The only solution I can come up with is to define a dummy module, say _config.py, which contains only upper-case variables representing these global switches, and is imported by all the other modules in the application with the line from _config import *. =A0During the early stages of the run, the script inspects the command-line flags, and if it finds a --continuing flag, it sets the variable _config.CONTINUATION_MODE to True. =A0(The last point implies that these variables are not strictly speaking read-only, since they most be set at the beginning of the run. =A0But after this initial setting, they should remain read-only.) Be very very careful about from _config import *. If you import a module that, in turn, imports _config this way, before you set the initial values, that module will already have made its own copies of all the variables and thus will not see the correct values. Good point. That's another reason for going for something like Nick's solution earlier in this thread. Thanks, kynn -- http://mail.python.org/mailman/listinfo/python-list
Re: Why use locals()
On Sep 18, 9:55 am, Simon Forman sajmik...@gmail.com wrote: On Mon, Sep 14, 2009 at 1:12 AM, Sean DiZazzo half.ital...@gmail.com wrote: Thanks for your explanation Steven. I see how it can be valuable, but it seems to always break the second rule of Zen. I don't really want to get into the code of debuggers, but I guess I can see how they might have no other way to know what local variables have been set. ~Sean The zeroth rule of zen is don't take the rules so seriously. They're really more like guidelines anyway. Regards, ~simon Yeah. I think I was just a bit randy at that moment. I realized that the (*args,**kwargs) idiom is very similar and I use it all the time. ~Sean -- http://mail.python.org/mailman/listinfo/python-list
[ANN] pyjamas pyv8run converts python to javascript, executes under command-line
just for fits and giggles and also because i'm getting fed up of using web browsers as part of the pyjs development cycle instead of the command-line, the pyjamas pyv8run.py has been brought back up-to- scratch, and can now execute the pyjamas LibTest regression tests with a 99.95% pass rate. pyv8run is a back-to-back combination of google's v8 engine + a library by flier liu which makes extensive use of python-boost (http:// code.google.com/p/pyv8) + the pyjamas python-to-javascript compiler. the initial experiment some months ago, with pyjamas 0.5, produced a python ACcellerator with a 10x performance increase; the latest 0.6~svn pyjamas compiler results in a python DEcellerator with a [finger-in-the-air] 10x performance DEcrease, thanks to the addition of several python strictness features. hurrah! :) perhaps it is the fact that the 0.5 test used google's stable x86 libv8, and the 0.6~svn test used google's alpha-release of amd64 libv8 - who knows, who cares, it's just hilarious to convert arbitrary python code into javascript and have it do 99.95% the same job. on the roadmap of this sub-sub-project of pyjamas is: * to throw pyv8run at the standard http://python.org regression tests and see what sticks * to improve the pyjamas compiler and/or alter the adapted lib2to3 parser/AST library in order to create a stand-alone, self-bootstrapped _javascript_ version of the pyjamas python-to-javascript compiler. this is _mandatory_ in order to support eval and exec - execution of python _source_ code - inside web browsers (and under a js prompt such as spidermonkey or d8) this latter goal has already been hilariously achieved by the (completely independent) skulpt project: http://skulpt.org/ whose parser/AST code the pyjamas project has borrowed - and back-ported from javascript to python. you can see their demo python prompt on the main page, and use it to mash your own web browser of choice into submission. the pyjamas project is taking a slightly different approach to achieve this same goal: beat the stuffing out of the pyjamas compiler, rather than hand-write such large sections of code in pure javascript, and double-run regression tests (once as python, second time converted to javascript under pyv8run, d8 or spidermonkey). anyway, just thought there might be people who would be intrigued (or horrified enough to care what's being done in the name of computer science) by either of these projects. l. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python based paramiko package acting up on Linux, code works fine on windows
On Sep 18, 11:22 am, flxkid theflx...@gmail.com wrote: I've tried to post to the mailing list for paramiko and contact the author, but it seems he's having some mailing list problems. Anyways, I have this small example that works just fine on Windows against Python 2.6.2, but fails on Ubuntu against 2.6.2. Here is the code: import subprocess import os import re import paramiko import sqlite3 import datetime import base64 import sys import logging from paramiko.rsakey import RSAKey class OpenSessions: sshconns = [] sqlconn = sqlite3.connect('test.sqlite') def __init__(self): self.sqlconn.row_factory = sqlite3.Row sqlcur = self.sqlconn.cursor() sqlcur.execute(select host, pub_key, username, password, private_key from ssh_hosts) rows = sqlcur.fetchall() for row in rows: sshconn = paramiko.SSHClient() sshconn._system_host_keys.add(row[host], ssh-rsa, RSAKey (data=base64.decodestring(row[pub_key]))) if row[private_key] != : sshconn.connect(hostname=row[host], username=row[username], pkey=RSAKey(data=base64.decodestring(row[private_key]))) elif row[password] != : sshconn.connect(hostname=row[host], username=row[username], password=row[password], look_for_keys=False, timeout=60) self.sshconns.append(sshconn) output = for conn in self.sshconns: print conn.exec_command(uname -a)[1].readline() exit() if __name__== '__main__': sessions = OpenSessions() The code fails with this trace: Traceback (most recent call last): File test.py, line 41, in module sessions = OpenSessions() File test.py, line 36, in __init__ print chan.exec_command(uname -a)[1].readline() File /usr/local/lib/python2.6/dist-packages/paramiko/channel.py, line 212, in exec_command self._wait_for_event() File /usr/local/lib/python2.6/dist-packages/paramiko/channel.py, line 1077, in _wait_for_event raise e paramiko.SSHException: Channel closed. Exception in thread Thread-1 (most likely raised during interpreter shutdown): Traceback (most recent call last): File /usr/lib/python2.6/threading.py, line 525, in __bootstrap_inner File /usr/local/lib/python2.6/dist-packages/paramiko/transport.py, line 1567, in run type 'exceptions.AttributeError': 'NoneType' object has no attribute 'error' This well beyond my abilities to debug. All I know is that it always works on Windows, and always fails in Ubuntu (which of course is where I need use the code). Any suggestions? I know the paramiko mailing list would probably be the better spot for this, but like I said, its got some issues right now. OLIVER Was a bug in paramiko channel.py in the _wait_for_event function. All fixed up now. OLIVER -- http://mail.python.org/mailman/listinfo/python-list
Re: can python make web applications?
On Sep 16, 7:02 pm, Paul Boddie p...@boddie.org.uk wrote: On 16 Sep, 18:31, lkcl luke.leigh...@googlemail.com wrote: http://pyjs.org/examples/timesheet/output/TimeSheet.html I get this error dialogue message when visiting the above page: TimeSheet undefined list assignment index out of range ah well spotted, thanks paul. -- http://mail.python.org/mailman/listinfo/python-list
Re: can python make web applications?
On Sep 16, 7:02 pm, Paul Boddie p...@boddie.org.uk wrote: On 16 Sep, 18:31, lkcl luke.leigh...@googlemail.com wrote: http://pyjs.org/examples/timesheet/output/TimeSheet.html I get this error dialogue message when visiting the above page: TimeSheet undefined list assignment index out of range Along with the following in-page error, once the data has been imported: JavaScript Error: uncaught exception: list assignment index out of range at line number 0. Please inform webmaster. It looks quite nice, though. Paul DOH! someone assuming javascript-isms in lists, and the compiler's been improved to ban them :) ... self.date = None ... ... print 'setEntries:', entries try: #tt = time.localtime(time.time()) -tt = [] -tt[0] = int(self.date[:4]) -tt[1] = int(self.date[4:6]) -tt[2] = int(self.date[6:8]) +tt = [0] * 9 +if self.date: +tt[0] = int(self.date[:4]) +tt[1] = int(self.date[4:6]) +tt[2] = int(self.date[6:8]) tt[3] = 0 tt[4] = 0 tt[5] = 0 -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a local variable scope.
On Sep 11, 10:36 am, Johan Grönqvist johan.gronqv...@gmail.com wrote: Hi All, I find several places in my code where I would like to have a variable scope that is smaller than the enclosing function/class/module definition. One representative example would look like: -- spam = { ... } eggs = { ... } ham = (a[eggs], b[spam]) -- The essence is that for readability, I want spam and eggs in separate definitions, but for clarity, I would like to express the fact that they are local to the definition of ham, i.e., they are not used outside of the definition of ham. The language reference at http://docs.python.org/reference/executionmodel.html says that The following are blocks: a module, a function body, and a class definition. (all other cases seem to refer to dynamic execution using eval() or similar). Python 3 and 2.6 seem to have identical scope rules. In the other languages I have used I can either use braces (C and descendants) or use let-bindings (SML, Haskell etc.) to form local scopes. Are there suggestions or conventions to maximize readability for these cases in python? (Execution time is not important in the cases I currently consider.) Regards Johan I would do something like this: class Namespace(object): ... pass ... n = Namespace() n.f = 2 n.g = 4 print f Traceback (most recent call last): File stdin, line 1, in ? NameError: name 'f' is not defined print n.f 2 ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: detmining name during an assignment
On Fri, Sep 18, 2009 at 1:10 PM, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: En Fri, 18 Sep 2009 14:38:08 -0300, Christian Heimes li...@cheimes.de escribió: Jamie Riotto schrieb: I have an app that uses Python scripting. When a user creates a new object: objName = newObject() I'd like the newObject be able to use objName as its internal name. As the others already explained to you there is no way to archive your goal with an assignment to a local or global variable. But you can follow a different approach: class Scene(object): def __setattr__(self, name, value): super(Scene, self).__setattr__(name value) if isinstance(value, SceneObject): value.name = name value.scene = self class SceneObject(object): pass class Cube(SceneObject): pass scene = Scene() scene.cube1 = Cube() As the OP said it's being used for scripting some application, presumably the application can control the environment on which the script is run. One may use the Scene class above as the globlal scope when executing the script: scene = Scene() code = cube1 = Cube(); print cube1.name exec code in Scene (well, not exactly, Scene should inherit from dict and override __setitem__ instead, but you get the idea) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list Thanks for the detailed clarifications and suggestions. I understand the problem a lot better now. However, I'll have to keep looking for a more elegant solution. Telling a user that typing: cube1 = Cube(name = cube1) is a good thing because its pythonic is somehow unsatisfying. Also, in the last suggestion about execution the script in the Scene Handler global scope, well thats exactly what I do, and yes, cube1=Cube, print cube1.name works great. The issue is say perhaps that cube then collides with something called sphere1. How does cube1 know that it hit sphere1 and not just a sphere object. Since I can execute the scripts one line at a time, I suppose I could search dictionaries for new names pointing to the same object after every execution, but Yuck. Perhaps the best approach is a preprossesor that looks for lines of the form name = class() and adds in the class(name = name) behind the scenes. Thanks again - jamie -- http://mail.python.org/mailman/listinfo/python-list
Re: pygame and py2app : big package
On Sep 18, 9:28 pm, pdora...@pas-de-pub-merci.mac.com (Pierre-Alain Dorange) wrote: I used py2app on Mac to build a package of my game (using pygame). It works fine (better than py2exe, i can'tmake work at tht time). But the package is very big. The biggest thing is numpy lib : 19 MB ! numpy is very big and i doubt all is reallly needed -- Pierre-Alain Dorange MicroWar 2.0 : kill some PC http://microwar.sourceforge.net/ Excuse me, but what was the point? (id est, are you just saying this or do you wish to ask a question?;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Granularity of OSError
You can access the exception object which gives you greater detail. try: os.unlink(some_file) except OSError, e: print e.errno print e.strerror if e.errno == 2: pass else: raise I do this myself in a lot of places, almost exactly like this. It's slightly clearer to use 'if e.errno == errno.ENOENT' in my opinion, but, whatever. In some cases it's also more correct. While ENOENT is always 2, some error codes differ between windows and posix. In general it's better to use the constants from the errno module. Ryan -- Ryan Kelly http://www.rfk.id.au | This message is digitally signed. Please visit r...@rfk.id.au| http://www.rfk.id.au/ramblings/gpg/ for details signature.asc Description: This is a digitally signed message part -- http://mail.python.org/mailman/listinfo/python-list
Re: pyjamas pyv8run converts python to javascript, executes under command-line
On 18 Sep, 23:17, lkcl luke.leigh...@googlemail.com wrote: the pyjamas project is taking a slightly different approach to achieve this same goal: beat the stuffing out of the pyjamas compiler, rather than hand-write such large sections of code in pure javascript, and double-run regression tests (once as python, second time converted to javascript under pyv8run, d8 or spidermonkey). anyway, just thought there might be people who would be intrigued (or horrified enough to care what's being done in the name of computer science) by either of these projects. I've added pyjamas to the implementations page on the Python Wiki in the compilers section: http://wiki.python.org/moin/implementation The Skulpt implementation, already listed by Cameron Laird on his page of Python implementations, is now also present, although using it is a bit like using various 8-bit microcomputer emulators which assume a UK keyboard and ignore the replacement keys on my own non-UK keyboard. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Granularity of OSError
kj wrote: For example, LBYL would look like this: if os.path.isfile(some_file): os.unlink(some_file) In contrast, EAFP would look like this: try: os.unlink(some_file) except OSError: pass The two version aren't equal. The first one suffers from a race condition which may lead to a severe security issue. The file may be gone or replaced by a different file in the time span between the check and the call to unlink(). Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Granularity of OSError
On Sep 18, 5:23 pm, Christian Heimes li...@cheimes.de wrote: kj wrote: For example, LBYL would look like this: if os.path.isfile(some_file): os.unlink(some_file) In contrast, EAFP would look like this: try: os.unlink(some_file) except OSError: pass The two version aren't equal. The first one suffers from a race condition which may lead to a severe security issue. The file may be gone or replaced by a different file in the time span between the check and the call to unlink(). Christian Thanks for pointing that out. I never thought of it before. ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: Substitute for KConfig in Qt4
On Thursday 17 September 2009 13:04, nusch wrote: I want to remove pyKDE dependencies from my app to make it pure PyQt. What will be the best substitute for KConfig? What exactly do you use KConfig for in your application? David -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of the Unicode standard
On Friday 18 September 2009 06:39:57 Dennis Lee Bieber wrote: (snip) Snap (sort of). Does anybody know where the concept of the purple people eater comes from? I mean is there a children's book or something? - Hendrik Where is the one eyed, one horned, lavender (antiquated) language eater i ask! He would be a friend of mine for sure ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Granularity of OSError
On 2009-09-19, Christian Heimes li...@cheimes.de wrote: kj wrote: For example, LBYL would look like this: if os.path.isfile(some_file): os.unlink(some_file) In contrast, EAFP would look like this: try: os.unlink(some_file) except OSError: pass The two version aren't equal. The first one suffers from a race condition which may lead to a severe security issue. The file may be gone or replaced by a different file in the time span between the check and the call to unlink(). IOW, just be cause you look before you leap, it doesn't mean you're not going to land on anybody and have to ask for forgiveness afterwards. Since you always have to handle the error case, there's not much point in checking first unless the error case has bad side-effects that you're trying to avoid. In this case, attempting to unlink a non-existent file has no bad side-effects, so there's no point in checking before the unlink. -- Grant -- http://mail.python.org/mailman/listinfo/python-list
Re: Podcast catcher in Python
On Sep 12, 3:37 pm, Chuck galois...@gmail.com wrote: On Sep 11, 9:54 pm, Chris Rebert c...@rebertia.com wrote: On Fri, Sep 11, 2009 at 7:43 PM, Chuck galois...@gmail.com wrote: Does anyone know how I should read/download the mp3 file, and how I should write/save it so that I can play it on a media player such as Windoze media player? Excuse my ignorance, but I am a complete noob at this. I downloaded the mp3, and I got a ton of hex, I think, but it could've been unicode. urllib.urlretrieve():http://docs.python.org/library/urllib.html#urllib.urlretrieve Cheers, Chris Thanks Chris! I will play around with this. I am using Python 3.1, but I can't figure out why I can't use xml.dom.minidom. Here is my code: from xml.dom.minidom import parse, parseString url = 'http://minnesota.publicradio.org/tools/podcasts/ grammar_grater.xml' #just for test purposes doc = parse(url) #I have also tried parseString(url), not to mention a million other methods from xml.Etree, xml.sax etc... all to no avail What the heck am I doing wrong? How can I get this xml file and use the toprettyxml() method. Or something, so I can parse it. I don't have any books and the documentation for Python kind of sucks. I am a complete noob to Python and internet programming. (I'm sure that is obvious :) ) Thanks! Charlie -- http://mail.python.org/mailman/listinfo/python-list
Re: Cross platform TTF font render from Python [was: Load TTF from pycairo under Windows]
On Friday 18 September 2009 08:54, Laszlo Nagy wrote: I need to render antialiased PNG images using TTF font files and UTF-8 text. It needs to be available at least on Linux and Windows. This is what I have tried: [...] #4. pygame - documentation looks great, it is cross platform. But the first example program I had tried has been terminated, printing out memory dump and complaining about double freeing some memory location. I'm surprised this doesn't work. I've seen games that are distributed with TrueType fonts, so I would expect them to work, or people would probably say something. :-) What other options do we have? PyQt4 can render Unicode text to all sorts of paint devices, and it supports TrueType fonts, too. You basically do all the painting via a single API: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qpainter.html Here's a quick example of how it could be done: http://www.diotavelli.net/PyQtWiki/Paint%20on%20an%20image All the relevant stuff happens in the updateImage() method. David -- http://mail.python.org/mailman/listinfo/python-list
Re: Podcast catcher in Python
On Fri, Sep 18, 2009 at 7:34 PM, Chuck galois...@gmail.com wrote: snip I am using Python 3.1, but I can't figure out why I can't use xml.dom.minidom. Here is my code: from xml.dom.minidom import parse, parseString url = 'http://minnesota.publicradio.org/tools/podcasts/ grammar_grater.xml' #just for test purposes doc = parse(url) #I have also tried parseString(url), not to mention a million other methods from xml.Etree, xml.sax etc... all to no avail What the heck am I doing wrong? How can I get this xml file and use the toprettyxml() method. Or something, so I can parse it. I don't have any books and the documentation for Python kind of sucks. I am a complete noob to Python and internet programming. (I'm sure that is obvious :) ) Impossible to say, considering *you didn't actually state what problem/error you're encountering*. Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
[issue6925] Doc for locals and vars
Senthil orsent...@gmail.com added the comment: On Fri, Sep 18, 2009 at 04:35:37AM +, Terry J. Reedy wrote: Was 2.x different? Even in 2.x it returns {} And I thought that was expected. Even I am confused by the free variable explaination as you pointed out. Perhaps, Georg could explain better? -- nosy: +orsenthil ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6925 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6919] Link CRT Statically
Henri Hein he...@granitetower.net added the comment: Right, I was thinking about rebuilding Python26.dll. If we do go down that path, I will report the results. Thanks for the feedback. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6919 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6937] multiprocessing lock on OS X Snow Leopard dumps core
Ronald Oussoren ronaldousso...@mac.com added the comment: Jesse: is this something you can look into? This is a crash of multiprocessing on MacOSX 10.6 with a 64-bit build of python. -- assignee: ronaldoussoren - jnoller nosy: +jnoller ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6937 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6934] [PATCH] postflight.framework script (from the Mac OS X .dmg installer) fails.
Ronald Oussoren ronaldousso...@mac.com added the comment: Thanks. I'll fix this over the weekend. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6934 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6767] Python as zip package
Senthil orsent...@gmail.com added the comment: I think it is okay to close this, with Martin's Howto. -- nosy: +orsenthil resolution: - invalid status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6767 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6925] Doc for locals and vars
Georg Brandl ge...@python.org added the comment: I'm sorry, I messed up the test. When x is not used in g(), it's of course *not* a free variable in g. This is the correct test: def f(): x = 1 def g(): print x print locals() g() f() -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6925 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6936] Import needed to quit Python?
Georg Brandl ge...@python.org added the comment: They are meant for interactive use only. -- resolution: - works for me status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6936 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6936] Import needed to quit Python?
Georg Brandl ge...@python.org added the comment: And fixed now (I used ``quit()``) in r74896. -- resolution: works for me - fixed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6936 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6935] Version updates needed in tutorial
Georg Brandl ge...@python.org added the comment: Fixed in r74897, r74898 (3.1). -- resolution: - fixed status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6935 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6508] expose setresuid
Martin v. Löwis mar...@v.loewis.de added the comment: Your patch looks good (except that in getresuid, you seem to be missing return). I have no clue why it doesn't work; I'll see whether I can try it out on Linux within the next few weeks. The one puzzling detail is that you don't include a patch to pyconfig.h.in: did you run autoheader? -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6508 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com