Building Web Site Using Python
I am new to python. I am looking to read in a 12mb csv file, parse it, generate web pages, summarize on a column and make drop down bottons. Where would I be able to find sample code that does something similar to this? Also, I know that microsoft has put out .net beta version of it. If I am using windows server, I am confined to use iron python? or are there alternatives? Perhaps, there are python web packages that have their own web server engine? Thanks in advance, -- http://mail.python.org/mailman/listinfo/python-list
List Manipulation
I would appreciate it if somebody could tell me where I went wrong in the following snipet: When I run I get no result cnt = 0 p=[] reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel", quotechar="'", delimiter='\t') for line in reader: if cnt > 6: break for col in line: p[:0].append(str(col)) cnt = cnt + 1 print p when I change it to the following, I get rows back cnt = 0 p=[] reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel", quotechar="'", delimiter='\t') for line in reader: if cnt > 6: break for col in line: print col cnt = cnt + 1 print p Thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: List Manipulation
Thanks for your help My intention is to create matrix based on parsed csv file. So, I would like to have a list of columns (which are also lists). I have made the following changes and it still doesn't work. cnt = 0 p=[[], [], [], [], [], [], [], [], [], [], []] reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel", quotechar="'", delimiter='\t') for line in reader: if cnt > 6: break j = 0 for col in line: p[j].append(col) j=j+1 cnt = cnt + 1 print p Iain King wrote: > Roman wrote: > > I would appreciate it if somebody could tell me where I went wrong in > > the following snipet: > > > > When I run I get no result > > > > cnt = 0 > > p=[] > > reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel", > > quotechar="'", delimiter='\t') > > for line in reader: > > if cnt > 6: > >break > > for col in line: > >p[:0].append(str(col)) > > What are you trying to do here? p[:0] returns a new list, of all the > elements in p up to element 0 (which is of course the empty list), > which is then appended to, but is not stored anywhere. If you want to > insert str(col) then use p.insert > > > Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: List Manipulation
Nothing got printed. Could you tell me what would be pythonic version of what I am trying to do? Diez B. Roggisch wrote: > > p[j] does not give you a reference to an element inside p. It gives > > you a new sublist containing one element from p. You then append a > > column to that sublist. Then, since you do nothing more with that > > sublist, YOU THROW IT AWAY. > > Not correct. > > p = [[]] > p[0].append(1) > print p > > yields > > [[1]] > > p[0] _gives_ you a reference to an object. If it is mutable (list are) and > append mutates it (it does), the code is perfectly alright. > > I don't know what is "not working" for the OP, but actually his code works > if one replaces the csv-reading with a generated list: > > cnt = 0 > p=[[], [], [], [], [], [], [], [], [], [], []] > reader = [["column_%i" % c for c in xrange(5)] for l in xrange(7)] > for line in reader: > if cnt > 6: >break > j = 0 > for col in line: >p[j].append(col) >j=j+1 > cnt = cnt + 1 > print p > > > You are right of course that it is the most unpythonic way imaginabe to do > it. But it works. > > Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: List Manipulation
I am getting TypeError: unsubscriptable object when specifying for line in reader[:7]: Steven D'Aprano wrote: > On Tue, 04 Jul 2006 07:01:55 -0700, Roman wrote: > > > I would appreciate it if somebody could tell me where I went wrong in > > the following snipet: > > > > When I run I get no result > > What do you mean? Does it print None? > > > cnt = 0 > > p=[] > > reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel", > > quotechar="'", delimiter='\t') > > for line in reader: > > if cnt > 6: > >break > > That's a very unPythonic way of doing the job. The usual way of doing > this would be something like this: > > for line in reader[:7]: > # no need for the "if cnt > 6: break" clause now > > > > for col in line: > >p[:0].append(str(col)) > > p[:0] creates a new list, which has a string appended to it, and is then > thrown away. What are you trying to do? > > If you are trying to insert the new entry at the beginning of the list, > you probably want this: > > p.insert(0, str(col)) -- http://mail.python.org/mailman/listinfo/python-list
Re: List Manipulation
Thanks for spending so much time with me. I had since made the following change. matrix = [[[] for l in range(len(list(reader)[:10]))] for c in range(len(list(reader)[7]))] for numline, line in enumerate(reader): for numcol, col in enumerate(line): matrix[numcol][numline] = col print matrix I don't get mistakes anymore. However, still nothing gets printed Bruno Desthuilliers wrote: > Roman wrote: > (please dont top-post - corrected) > > > > Iain King wrote: > > > >>Roman wrote: > >> > >>>I would appreciate it if somebody could tell me where I went wrong in > >>>the following snipet: > >>> > (snip) > > >>What are you trying to do here? p[:0] returns a new list, of all the > >>elements in p up to element 0 (which is of course the empty list), > >>which is then appended to, but is not stored anywhere. If you want to > >>insert str(col) then use p.insert > >> > >> > >>Iain > > > > > > Thanks for your help > > > > My intention is to create matrix based on parsed csv file. So, I > > would like to have a list of columns (which are also lists). > > csv = [ >['L0C0', 'L0C1', 'L0C2'], >['L1C0', 'L1C1', 'L1C2'], >['L2C0', 'L2C1', 'L2C2'], > ] > > matrix = [[[] for l in range(len(csv))] for c in range(len(csv[0]))] > > for numline, line in enumerate(csv): > for numcol, col in enumerate(line): > matrix[numcol][numline] = col > > assert matrix == [ >['L0C0', 'L1C0', 'L2C0'], >['L0C1', 'L1C1', 'L2C1'], >['L0C2', 'L1C2', 'L2C2'] > ] > > NB : There are probably more elegant solutions. > > > I have made the following changes and it still doesn't work. > > "doesn't work" is the worst possible description of a problem... > > (snip) > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: List Manipulation
below is the data I am trying to read "04""AS0042123BO" "AS 0042.123 ROYAL ELONG SEAT BO" "001610""A/S Fixtures" 0 $99.00 3.70"" "0042123" 11/20/2003 "24""AS0042001BK" "AS 0042.001 ROYAL EL*DISC BY MFG*BK" "001610""A/S Fixtures" 0 $99.00 8.00"723085611663" "0042001" 11/20/2003 "000104""CH130TTWH" "CH 130TT EL PLAS SEAT C/F W/C WH" "207067""Church Seats" 12 $25.00 6.75"073088079961" "130TT 000"12/28/1995 "000112""CH130TTBO" "CH 130TT EL PLAS SEAT C/F W/C BO" "207067""Church Seats" 23 $29.00 7.50"073088079954" "130TT 006"02/23/1998 "000124""CH130TTSS" "CH 130TT EL PLAS SEAT C/F W/C SS" "207067""Church Seats" 14 $29.00 6.75"073088079985" "130TT 162" "000176""XPT562""PP T562" "201681""Price Pfister"0 $233.50 0.00"" "" 01/22/1998 "000180""XPT564""PP T564" "201681""Price Pfister"0 $0.00 0.00"" "" 07/19/1996 "000224""MO5270""MO 5270*DBM*MON BIDET FCT L/HDL CP" "204938""Moen" 0 $0.00 8.00"026508050286" "005270" "000236""MO5270P" "MO 5270P*DBM*BIDET FCT LVR/HDL PB" "204938""Moen" 0 $0.00 8.00"026508050309" "05270P" "000240""MO5275""MO 5275 *DBM* BIDET FCT L/HDLS CP" "204938""Moen" 1 $0.00 8.00"" "" 11/20/2003 "000244""MO5275P" "MO 5275P*DBM* MON BIDET FCT PB" "204938""Moen" 0 $0.00 8.00"026508050347" "05275P"01/04/1996 "000248""MO5201""MO 5201 *DBM* TRAD BIDET LVR FCT CP" "204938""Moen" 0 $0.00 6.70"026508050354" "5201" 01/04/1996 "000260""MO5201P" "MO 5201P TRAD BIDET FCT LVR/H*DBM*B""204938""Moen" 0 $0.00 7.00"026508050378" "5201P" 01/04/1996 "000264""MO5201W" "MO 5201W**DBM**IDET FCT LVR/HDL WH" "204938""Moen" 0 $0.00 6.70"026508050385" "05201W"01/04/1996 "066916""FB1418AB" "FB D2418AB 18 TOWEL BAR AB" "220502""Liberty Hardware" 0 $18.70 1.15"079171141898" "D2418AB" 04/14/1998 "066920""FBD2424AB" "FB D2424AB 24 TOWEL BAR AB" "220502""Liberty Hardware" 39 $20.50 1.32"079171242427" "D2424AB" "066956""P7341FLC" "PP 734-1FLC*DBM* SNK FCT 1H L/SP CP" "201681""Price Pfister"0 $147.65 7.00"038877420218" "7341FLC" 04/14/1998 "066960""P7341FLW" "PP 734-1FLW FILT SNK FCT 1H L/SP WH" "201681""Price Pfister"0 $157.99 7.00"038877420225" "7341FLW" 04/14/1998 Dennis Lee Bieber wrote: > On 4 Jul 2006 07:01:55 -0700, "Roman" <[EMAIL PROTECTED]> declaimed > the following in comp.lang.python: > > > I would appreciate it if somebody could tell me where I went wrong in > > the following snipet: > > > It would help if you gave a sample of the input data (three lines > worth, say) AND an example of what the final output should be from those > three lines. > > > for col in line: > >p[:0].append(str(col)) > > As has been pointed out, as soon as you used the [:0], you created a > local/temporary EMPTY slice of the original P, and you are appending one > column's value to this temporary, which is then thrown away. > import csv > > -=-=-=-=-=-=-=-
RE Module
I am trying to filter a column in a list of all html tags. To do that, I have setup the following statement. row[0] = re.sub(r'<.*?>', '', row[0]) The results I get are sporatic. Sometimes two tags are removed. Sometimes 1 tag is removed. Sometimes no tags are removed. Could somebody tell me where have I gone wrong here? Thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: RE Module
Thanks for your help. A thing I didn't mention is that before the statement row[0] = re.sub(r'<.*?>', '', row[0]), I have row[0]=re.sub(r'[^ 0-9A-Za-z\"\'\.\,[EMAIL PROTECTED](\)\*\&\%\%\\\/\:\;\?\`\~\<\>]', '', row[0]) statement. Hence, the line separators are going to be gone. You mentioned the size of the string could be a factor. If so what is the max size before I see problems? Thanks again Anthra Norell wrote: > Roman, > > Your re works for me. I suspect you have tags spanning lines, a thing you get > more often than not. If so, processing linewise > doesn't work. You need to catch the tags like this: > > >>> text = re.sub ('<(.|\n)*?>', '', text) > > If your text is reasonably small I would recommend this solution. Else you > might want to take a look at SE which is a stream edtor > that does the buffering for you: > > http://cheeseshop.python.org/pypi/SE/2.2%20beta > > >>> import SE > >>> Tag_Stripper = SE.SE (' "~<(.|\n)*?>~=" "~~=" ') > >>> print Tag_Stripper (text) > (... your text without tags ...) > > The Tag_Stripper is made up of two regexes. The second one catches comments > which may nest tags. The first expression alone would > also catch comments, but would mistake the '>' of the first nested tag for > the end of the comment and quit prematurely. The example > "re.sub ('<(.|\n)*?>', '', text)" above would misperform in this respect. > > Your Tag_Stripper takes input from files directly: > > >>> Tag_Stripper ('name_of_file.htm', 'name_of_output_file') > 'name_of_output_file' > > Or if you want to to view the output: > > >>> Tag_Stripper ('name_of_file.htm', '') > (... your text without tags ...) > > If you want to keep the definitions for later use, do this: > > >>> Tag_Stripper.save ('[your_path/]tag_stripper.se') > > Your definitions are now saved in the file 'tag_stripper.se'. You can edit > that file. The next time you need a Tag_Stripper you can > make it simply by naming the file: > > >>> Tag_Stripper = SE.SE ('[your_path/]tag_stripper.se') > > You can easily expand the capabilities of your Tag_Stripper. If, for > instance, you want to translate the ampersand escapes ( > etc.) you'd simply add the name of the file that defines the ampersand > replacements: > > >>> Tag_Stripper = SE.SE ('tag_stripper.se htm2iso.se') > > 'htm2iso.se' comes with the SE package ready to use and as an example for > writing ones own replacement sets. > > > Frederic > > > - Original Message - > From: "Simon Forman" <[EMAIL PROTECTED]> > Newsgroups: comp.lang.python > To: > Sent: Friday, August 25, 2006 7:09 AM > Subject: Re: RE Module > > > > Roman wrote: > > > I am trying to filter a column in a list of all html tags. > > > > What? > > > > > To do that, I have setup the following statement. > > > > > > row[0] = re.sub(r'<.*?>', '', row[0]) > > > > > > The results I get are sporatic. Sometimes two tags are removed. > > > Sometimes 1 tag is removed. Sometimes no tags are removed. Could > > > somebody tell me where have I gone wrong here? > > > > > > Thanks in advance > > > > I'm no re expert, so I won't try to advise you on your re, but it might > > help those who are if you gave examples of your input and output data. > > What results are you getting for what input strings. > > > > Also, if you're just trying to strip html markup to get plain text from > > a file, "w3m -dump some.html" works great. ;-) > > > > HTH, > > ~Simon > > > > -- > > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: RE Module
This is excellent. Thanks a lot. Also, what made the expression greedy? tobiah wrote: > Roman wrote: > > I am trying to filter a column in a list of all html tags. > > > > To do that, I have setup the following statement. > > > > row[0] = re.sub(r'<.*?>', '', row[0]) > > The regex will be 'greedy' and match through one tag > all the way to the end of another on the same line. > There are more complete suggestions offered, but > it seems to me that the simple fix here is to not > match through the end of the tag, like this: > > "<[^>]*>" > > -- > Posted via a free Usenet account from http://www.teranews.com -- http://mail.python.org/mailman/listinfo/python-list
Re: RE Module
I looked at a book called beginning python and it claims that <.*?> is a non-greedy match. tobiah wrote: > > In python's RE module, they're like Perl: > > > > Greedy: "<.*>" > > Nongreedy: "<.*?>" > > > > Oh, I have never seen that. In that case, why > did Roman's first example not work well for > HTML tags? > > '<.*?>' > > Also, how does the engine decide whether I am adjusting > the greed of the previous operator, or just asking > for another possible character? > > Suppose I want: > > "x*?" to match "xxxO" > > If the '?' means non greedy, then I should get 'x' back. > If the '?' means optional character then I should get > the full string back. > > Checking in python: > > ## > import re > > s = 'xxx0' > > m = re.search("x*", s) > print "First way", m.group(0) > > m = re.search("x*?", s) > print "Second way", m.group(0) > # > First way xxx > Second way > > So now I'm really confused. It didn't do a non-greedy > 'x' match, nor did it allow the '?' to match the '0'. > > > -- > Posted via a free Usenet account from http://www.teranews.com -- http://mail.python.org/mailman/listinfo/python-list
Re: RE Module
It turns out false alarm. It work. I had other logic in the expression involving punctuation marks and got all confused with the escape characters. It becomes a mess trying to keep track of all the reserved character as you are going from module to module. tobiah wrote: > Roman wrote: > > I looked at a book called beginning python and it claims that <.*?> is > > a non-greedy match. > > Yeah, I get that now, but why didn't it work for you in > the first place? > > -- > Posted via a free Usenet account from http://www.teranews.com -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expression
Asper Faner wrote: > I seem to always have hard time understaing how this regular expression > works, especially how on earth do people bring it up as part of > computer programming language. Natural language processing seems not > enough to explain by the way. Why no eliminate it ? > It has very much to do with computer programming. There is program flow, conditions, loops, variables. Roman -- http://mail.python.org/mailman/listinfo/python-list
XML Processing
Is there a package that converts a string that contains special characters in xml to to literal value. For instance, converts string http://myhome/¶m to http://myhome/¶m. Thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
How to guess the language of a given textstring?
Does anybody know an easy way (or tool) to guess the language of a given text string? e.g. Feeding in "This is an example." --> should return "english" or ISO code Feeding in "Das ist ein Beispiel." --> should return "german" or ISO code Feeding in "Esto es un ejemplo." --> should return "spanish" or ISO code I would prefer something more lightweight than using nltk/corpus/... And it's ok if the success ratio is just about 90% or so. Roman -- http://mail.python.org/mailman/listinfo/python-list
Re: How to guess the language of a given textstring?
Hi This is what I'm looking for. Thank you. Roman gene tani schrieb: > Roman wrote: > > Does anybody know an easy way (or tool) to guess the language of a > > given text string? > > > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/355807 > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/326576 -- http://mail.python.org/mailman/listinfo/python-list
Re: pygccxml xml output file
On Jan 24, 3:25 pm, whatazor wrote: > Hi all, > I start to use this module in order to produce xml( and the make other > things), but differently from gccxml I don't find the variable that > set the name of the xml output file after the parsing (in gccxml is - > fxml), so it creates temporary files. > how can I do an Is there a tutorial that explain with dectails how it > works? I suggest you to ask your questions on the following mailing list: https://lists.sourceforge.net/lists/listinfo/pygccxml-development As for your question: see http://www.language-binding.net/pygccxml/apidocs/pygccxml.parser.project_reader-module.html#create_cached_source_fc documentation. and http://www.language-binding.net/pygccxml/apidocs/pygccxml.parser.project_reader.project_reader_t-class.html#read_files HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to get ABC to work
Following code works, although I'm not sure that it's exactly what you want: import abc class MetaExample(abc.ABCMeta): def __new__(mcs, name, bases, ns): ns['cls_meth'] = mcs.cls_meth if not 'cls_abc' in ns: ns['cls_abc'] = mcs.cls_abc return super().__new__(mcs, name, bases, ns) def cls_meth(cls): print('Class method defined stub') @abc.abstractmethod def cls_abc(cls): try: print('Class-Abstract method defined stub') except NotImplementedError as err: print('Must implement cls_abc') except: print('General exception at cls_abc method') That's how I've tested it: class Test1(object, metaclass=MetaExample): def cls_abc(self): print("method of", self) class Test2(object, metaclass=MetaExample): pass test1 = Test1() test1.cls_meth() test1.cls_abc() test2 = Test2() Output: Class method defined stub method of <__main__.Test1 object at 0xb7b5f52c> Traceback (most recent call last): File "/tmp/test.py", line 32, in test2 = Test2() TypeError: Can't instantiate abstract class Test2 with abstract methods cls_abc According to the documentation, @abstractmethod "requires that the metaclass is ABCMeta or derived from it", so I've changed base class from type to ABCMeta. Also I don't think that using try/except inside the abstract method will work, maybe it would be better to check presence of all required methods directly inside the metaclass, without @abstractmethod decorator. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it possible to have the python color in the terminal ?
On 04/08/09 12:20, aurelien wrote: > Hello, > > I am under gNewSense, i am a newbbie on Python, i look for how change > the color terminal when python run. > at the step >>> all is in black and white. > Is it possible to have the python color in the terminal ? > > Thanks for your help > > aurelien > -- > http://mail.python.org/mailman/listinfo/python-list > If you want to get colourful output, you can use IPython (http://ipython.scipy.org/moin/FrontPage), it is an enhanced Python shell. You may also change colour of text by printing appropriate escape sequences (e.g. executing print("\033[0;32m") in Python interpreter should change foreground colour to green. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with regex
On 06/08/09 08:35, Robert Dailey wrote: > Hey guys, > > I'm creating a python script that is going to try to search a text > file for any text that matches my regular expression. The thing it is > looking for is: > > FILEVERSION #,#,#,# > > The # symbol represents any number that can be any length 1 or > greater. Example: > > FILEVERSION 1,45,10082,3 > > The regex should only match the exact above. So far here's what I have > come up with: > > re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' ) > > This works, but I was hoping for something a bit cleaner. I'm having > to create a special case portion of the regex for the last of the 4 > numbers simply because it doesn't end with a comma like the first 3. > Is there a better, more compact, way to write this regex? > -- > http://mail.python.org/mailman/listinfo/python-list > Since there cannot be more than one "end of string" you can try this expression: re.compile( r'FILEVERSION (?:[0-9]+(,|$)){4}' ) -- http://mail.python.org/mailman/listinfo/python-list
Re: use Python to post image to Facebook
Try to use http://pycurl.sourceforge.net/ I don't test it, but there is no problem interact with google services. 22.06.12 17:27, davecotef...@gmail.com пишет: On Monday, 9 April 2012 20:24:54 UTC-7, CM wrote: Shot in the dark here: has any who reads this group been successful with getting Python to programmatically post an image to Facebook? I've tried using fbconsole[1] and facepy[2], both of which apparently work fine for their authors and others and although I have an authorization code, publish permissions, a Facebook app, I get back these unhelpful errors when I try this (like "an unknown error occurred"). If anyone has been able to do this, maybe you can help me figure out what I am doing wrong. Hi, I am not sure, but have a similar question. How can I post (upload) an image to google images and return the resulting page..? In python? If you can help I would appreciate it ever so much, Dave:) -- http://mail.python.org/mailman/listinfo/python-list
Re: Grok vs. Django for RESTful API?
You could implement REST protocol for Grok using http://pypi.python.org/pypi/restkit/ 2012/6/25 TG > Just hoping to get some opinions: Grok vs Django for REST? I've started > evaluating TastyPie with Django. Is there something similar for Grok? > > I'm working on a project that will mostly be mobile-app based. Though > there will be a web interface, the mobile part is more important to us. Our > data model is pretty straight-forward so far (it's a social networking type > app), but may become a bit more involved if we begin to add > information/event streams. > So finding a framework that works well with a dynamically changing data > model is somewhat important (hopefully we won't change it too often). > Having a good security/authentication/authorization framework is important > too. > > I consider myself pretty strong with Python and other languages, but web > programming is new to me. I'm comfortable though with HTTP/SQL/etc. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Help: PYMALLOC_DBUG and PIL
2012/7/5 tom z > Hi~ all, > I encounter a odd problem, when i compile Python with PYMALLOC_DEBUG, the > PIL module can't work fine, it always make core-dump like this > > [Switching to Thread 182897301792 (LWP 16102)] > 0x004df264 in PyObject_Malloc (nbytes=64) at Objects/obmalloc.c:804 > 804 if ((pool->freeblock = *(block **)bp) != NULL) { > Current language: auto; currently c > (gdb) bt > #0 0x004df264 in PyObject_Malloc (nbytes=64) at > Objects/obmalloc.c:804 > #1 0x004dfb97 in _PyObject_DebugMallocApi (id=109 'm', nbytes=32) > at Objects/obmalloc.c:1461 > #2 0x004dfd22 in _PyObject_DebugReallocApi (api=109 'm', p=0x0, > nbytes=32) at Objects/obmalloc.c:1523 > #3 0x004dfac0 in _PyMem_DebugRealloc (p=0x0, nbytes=32) at > Objects/obmalloc.c:1416 > #4 0x004c68d9 in list_resize (self=0x2a988409b8, newsize=1) at > Objects/listobject.c:62 > #5 0x004c6f63 in app1 (self=0x2a988409b8, v=0x2a958cea90) at > Objects/listobject.c:277 > #6 0x004c6fdd in PyList_Append (op=0x2a988409b8, > newitem=0x2a958cea90) at Objects/listobject.c:289 > #7 0x00558c7f in symtable_add_def (st=0x2a99a4ca68, > name=0x2a958cea90, flag=4) at Python/symtable.c:910 > #8 0x0055a953 in symtable_visit_params (st=0x2a99a4ca68, > args=0x924380, toplevel=1) at Python/symtable.c:1318 > #9 0x0055aaa7 in symtable_visit_arguments (st=0x2a99a4ca68, > a=0x9243c8) at Python/symtable.c:1365 > #10 0x00558f3d in symtable_visit_stmt (st=0x2a99a4ca68, > s=0x9244d0) at Python/symtable.c:1012 > #11 0x0055919e in symtable_visit_stmt (st=0x2a99a4ca68, > s=0x924500) at Python/symtable.c:1029 > #12 0x005574d7 in PySymtable_Build (mod=0x931798, > filename=0x7fbfffa2c0 > "../lib/python2.7/site-packages/PIL/BmpImagePlugin.py", > future=0x2a9883aae0) at Python/symtable.c:240 > #13 0x00531f14 in PyAST_Compile (mod=0x931798, > filename=0x7fbfffa2c0 > "../lib/python2.7/site-packages/PIL/BmpImagePlugin.py", flags=0x7fbfff9020, > arena=0x8eedd0) at Python/compile.c:282 > #14 0x00545967 in parse_source_module ( > pathname=0x7fbfffa2c0 > "../lib/python2.7/site-packages/PIL/BmpImagePlugin.py", fp=0x91a060) at > Python/import.c:843 > #15 0x00545e75 in load_source_module (name=0x7fbfffb3e0 > "PIL.BmpImagePlugin", > pathname=0x7fbfffa2c0 > "../lib/python2.7/site-packages/PIL/BmpImagePlugin.py", fp=0x91a060) at > Python/import.c:1027 > > i've no idea about this, someone could get me help~ > > --- > thanks a lot > > -- > http://mail.python.org/mailman/listinfo/python-list > > PYMALLOC_DEBUG requires WITH_PYMALLOC. It's enabled? -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I disable module of tkinter when compiling Python 2.5 on redhat9 ?
09.07.12 13:21, cheetah ?: I don't need it. thanks In python's setup.py replace: self.detect_tkinter(inc_dirs, lib_dirs) of def detect_modules(self): This will ignore the compilation of _tkinter.c and tkappinit.c of the python distribution. -- http://mail.python.org/mailman/listinfo/python-list
Re: save dictionary to a file without brackets.
for key in dict: print key[0], key[1], dict[key] 10.08.2012, в 0:11, giuseppe.amatu...@gmail.com написал(а): > Hi, > I have a dict() unique > like this > {(4, 5): 1, (5, 4): 1, (4, 4): 2, (2, 3): 1, (4, 3): 2} > and i want to print to a file without the brackets comas and semicolon in > order to obtain something like this? > 4 5 1 > 5 4 1 > 4 4 2 > 2 3 1 > 4 3 2 > Any ideas? > Thanks in advance > Giuseppe > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: save dictionary to a file without brackets.
dict.items() is a list - linear access time whereas with 'for key in dict:' access time is constant: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#use-in-where-possible-1 10.08.2012, в 0:35, Tim Chase написал(а): > On 08/09/12 15:22, Roman Vashkevich wrote: >>> {(4, 5): 1, (5, 4): 1, (4, 4): 2, (2, 3): 1, (4, 3): 2} >>> and i want to print to a file without the brackets comas and semicolon in >>> order to obtain something like this? >>> 4 5 1 >>> 5 4 1 >>> 4 4 2 >>> 2 3 1 >>> 4 3 2 >> >> for key in dict: >> print key[0], key[1], dict[key] > > This might read more cleanly with tuple unpacking: > > for (edge1, edge2), cost in d.iteritems(): # or .items() >print edge1, edge2, cost > > (I'm making the assumption that this is a edge/cost graph...use > appropriate names according to what they actually mean) > > -tkc > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: save dictionary to a file without brackets.
Actually, they are different. Put a dict.{iter}items() in an O(k^N) algorithm and make it a hundred thousand entries, and you will feel the difference. Dict uses hashing to get a value from the dict and this is why it's O(1). 10.08.2012, в 1:21, Tim Chase написал(а): > On 08/09/12 15:41, Roman Vashkevich wrote: >> 10.08.2012, в 0:35, Tim Chase написал(а): >>> On 08/09/12 15:22, Roman Vashkevich wrote: >>>>> {(4, 5): 1, (5, 4): 1, (4, 4): 2, (2, 3): 1, (4, 3): 2} >>>>> and i want to print to a file without the brackets comas and semicolon in >>>>> order to obtain something like this? >>>>> 4 5 1 >>>>> 5 4 1 >>>>> 4 4 2 >>>>> 2 3 1 >>>>> 4 3 2 >>>> >>>> for key in dict: >>>>print key[0], key[1], dict[key] >>> >>> This might read more cleanly with tuple unpacking: >>> >>> for (edge1, edge2), cost in d.iteritems(): # or .items() >>> print edge1, edge2, cost >>> >>> (I'm making the assumption that this is a edge/cost graph...use >>> appropriate names according to what they actually mean) >> >> dict.items() is a list - linear access time whereas with 'for >> key in dict:' access time is constant: >> http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#use-in-where-possible-1 > > That link doesn't actually discuss dict.{iter}items() > > Both are O(N) because you have to touch each item in the dict--you > can't iterate over N entries in less than O(N) time. For small > data-sets, building the list and then iterating over it may be > faster faster; for larger data-sets, the cost of building the list > overshadows the (minor) overhead of a generator. Either way, the > iterate-and-fetch-the-associated-value of .items() & .iteritems() > can (should?) be optimized in Python's internals to the point I > wouldn't think twice about using the more readable version. > > -tkc > > -- http://mail.python.org/mailman/listinfo/python-list
Re: save dictionary to a file without brackets.
10.08.2012, в 1:47, Dave Angel написал(а): > On 08/09/2012 05:34 PM, Roman Vashkevich wrote: >> Actually, they are different. >> Put a dict.{iter}items() in an O(k^N) algorithm and make it a hundred >> thousand entries, and you will feel the difference. >> Dict uses hashing to get a value from the dict and this is why it's O(1). > > Sure, that's why > > for key in dict: > print key[0], key[1], dict[key] > > is probably slower than > > for (edge1, edge2), cost in d.iteritems(): # or .items() > print edge1, edge2, cost > > > So, the latter is both faster and easier to read. Why are you arguing > against it? > > Also, please stop top-posting. It's impolite here, and makes it much harder > to figure out who is saying what, in what order. > > > > -- > > DaveA > I'm not arguing at all. Sorry if it sounded like I was arguing. Thanks for notifying me of the way messages should be sent. Roman -- http://mail.python.org/mailman/listinfo/python-list
Re: [newbie] A question about lists and strings
10.08.2012, в 13:19, Mok-Kong Shen написал(а): > > In an earlier question about lists, I was told about the issue of > creation of local names in a function. However, I still can't > understand why the program below outputs: > > [999] sss > [999] > > and not two identical lines of output. For both operators "+=" should > anyway work in similar manner in the function xx in my view. > > Thanks for your help in advance. > > M. K. Shen > > -- > > def xx(list,str): > list+=[999] > str+="sss" > > lista=[] > stra="" > lista+=[999] > stra+="sss" > print(lista,stra) > > listb=[] > strb="" > xx(listb,strb) > print(listb,strb) > -- > http://mail.python.org/mailman/listinfo/python-list It seems like your xx() function doesn't return local str parameter and prints the global empty str, whereas it mutates the global list. Roman -- http://mail.python.org/mailman/listinfo/python-list
Re: [newbie] A question about lists and strings
10.08.2012, в 13:28, Roman Vashkevich написал(а): > 10.08.2012, в 13:19, Mok-Kong Shen написал(а): > >> >> In an earlier question about lists, I was told about the issue of >> creation of local names in a function. However, I still can't >> understand why the program below outputs: >> >> [999] sss >> [999] >> >> and not two identical lines of output. For both operators "+=" should >> anyway work in similar manner in the function xx in my view. >> >> Thanks for your help in advance. >> >> M. K. Shen >> >> -- >> >> def xx(list,str): >> list+=[999] >> str+="sss" >> >> lista=[] >> stra="" >> lista+=[999] >> stra+="sss" >> print(lista,stra) >> >> listb=[] >> strb="" >> xx(listb,strb) >> print(listb,strb) >> -- >> http://mail.python.org/mailman/listinfo/python-list > > It seems like your xx() function doesn't return local str parameter and > prints the global empty str, whereas it mutates the global list. > > Roman Excuse me for the mess I just did in my message:) The function doesn't print anything of cause. It takes list by reference and creates a new local str. When it's called with listb and strb arguments, listb is passed by reference and mutated. A string "sss" is concatenated with an empty local str. Nothing more happens. Since local str is not returned by xx(), it can not be expected to be printed out in the statement that follows. What is printed out in the print statement is the mutated listb and the global strb. RV -- http://mail.python.org/mailman/listinfo/python-list
Re: [newbie] A question about lists and strings
10.08.2012, в 14:12, Mok-Kong Shen написал(а): > Am 10.08.2012 11:48, schrieb Roman Vashkevich: >> [snip] > >The function It takes list by reference and creates a new local > > str. When it's called with listb and strb arguments, listb is passed > > by reference and mutated. A string "sss" is concatenated with an > > empty local str. Nothing more happens. Since local str is not > > returned by xx(), it can not be expected to be printed out in the > > statement that follows. What is printed out in the print statement is > > the mutated listb and the global strb. > > Thanks for the explanation of the output obtained. But this means > nonetheless that parameters of types lists and strings are dealt with > in "inherently" (semantically) different ways by Python, right? > > M. K. Shen > > -- > http://mail.python.org/mailman/listinfo/python-list I am not sure I understand your question. Can you rephrase it or make it more explicit? RV -- http://mail.python.org/mailman/listinfo/python-list
Re: [newbie] A question about lists and strings
10.08.2012, в 14:12, Mok-Kong Shen написал(а): > Am 10.08.2012 11:48, schrieb Roman Vashkevich: >> [snip] > >The function It takes list by reference and creates a new local > > str. When it's called with listb and strb arguments, listb is passed > > by reference and mutated. A string "sss" is concatenated with an > > empty local str. Nothing more happens. Since local str is not > > returned by xx(), it can not be expected to be printed out in the > > statement that follows. What is printed out in the print statement is > > the mutated listb and the global strb. > > Thanks for the explanation of the output obtained. But this means > nonetheless that parameters of types lists and strings are dealt with > in "inherently" (semantically) different ways by Python, right? > > M. K. Shen > > -- > http://mail.python.org/mailman/listinfo/python-list DaveA provided a very explicit explanation of how py handles list and string objects. Parameters are handled "inherently" by functions... RV -- http://mail.python.org/mailman/listinfo/python-list
Fwd: Question about PyXML and python's stdlib xml
I'm forwarding this message to python-list, since I didn't get answer on xml-sig ML. Hopefully this is right list to question. Please keep me in CC. Original message is below. RR Original Message Subject:Question about PyXML and python's stdlib xml Date: Mon, 27 Feb 2012 16:51:00 +0100 From: Roman Rakus To: xml-...@python.org Hi, I have concerns about PyXML and stdlib xml included directly in python. Currently (in Fedora) python is trying to import PyXML, which means other results when you have and haven't PyXML installed. Furthermore, python's xml provides "dom", "parsers", "sax" and "etree". PyXML provides 'dom', 'marshal', 'parsers', 'sax', 'schema', 'utils', 'xpath' and 'xslt'. Some modules are duplicated. Does PyXML provides more functionality in those modules? Is python's xml better, same or worse then PyXML? Anyway, python's xml is newer - is PyXML deprecated? Please keep me in CC, I'm not subscribed to the list. RR -- http://mail.python.org/mailman/listinfo/python-list
Jython callable. How?
Hi. How exactly jython decides is object callable or not? I defined __call__ method but interpreter says it's still not callable. BTW, my code works in cpython -- http://mail.python.org/mailman/listinfo/python-list
Re: Jython callable. How?
> Perhaps if you show us what you actually do, and what happens, we might > be able to tell you what is happening. Please COPY AND PASTE the full > traceback. Here is my code: # Trying to make callable staticmethod class sm(staticmethod): def __call__(self, *args, **kwargs): """ I know here is one more potential problem, because object passed instead of real class """ return self.__get__(None, object)(*args, **kwargs) issubclass(sm, Callable) class Foo(object): @sm def bar(): print("ololo") print("inside", bar, callable(bar), bar()) if __name__=="__main__": print("class outise", Foo.bar, callable(Foo.bar), Foo.bar()) f = Foo() print("instance outside", f.bar, callable(f.bar), f.bar()) cpython output: ololo ('inside', <__main__.sm object at 0xb72b404c>, True, None) ololo ('class outise', , True, None) ololo ('instance outside', , True, None) jython output: Traceback (most recent call last): File "sm.py", line 17, in class Foo(object): File "sm.py", line 23, in Foo print("inside", bar, callable(bar), bar()) TypeError: 'staticmethod' object is not callable -- http://mail.python.org/mailman/listinfo/python-list
Re: Flat file, Python accessible database?
On Tue, 1 Nov 2005, Karlo Lozovina wrote: > [EMAIL PROTECTED] (=?utf-8?Q?Bj=C3=B6rn_Lindstr=C3=B6m?=) wrote in > news:[EMAIL PROTECTED]: > >> If you need it to be SQL-like, SQLite seems to be the right thing. > > Tried that one, but had some problems setting things up. That is strange. SQLite + PySQLite are IMHO no harder to install than BerkeleyDB + Pybsddb... > On the other > hand, BerkeleyDB + Pybsddb worked like a charm, with no setting up (under > Cygwin). Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: reading internet data to generate random numbers.
On Wed, 2 Nov 2005, Grant Edwards wrote: > On 2005-11-02, Levi Campbell <[EMAIL PROTECTED]> wrote: > >> Hi, I'm working on a random number generator using the internet as a >> way to gather entropy, I have two questions. So far interesting. >> 1. is there a way to capture the internet stream? Most news sites provide RSS and/or ATOM feeds these days. Or maybe you mean video/audio stream from Internet stations? (not sure how much entropy such a stream could contain: probably depends on the genre ;-) Or perhaps you mean low-level Ethernet/TCP/IP "stream"? Then it is not original and I already saw answers with recomendations. Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: XML DOM: XML/XHTML inside a text node
On Thu, 2 Nov 2005 [EMAIL PROTECTED] wrote: > In my program, I get input from the user and insert it into an XHTML > document. Sometimes, this input will contain XHTML, but since I'm > inserting it as a text node, xml.dom.minidom escapes the angle brackets > ('<' becomes '<', '>' becomes '>'). I want to be able to > override this behavior cleanly. I know I could pipe the input through > a SAX parser and create nodes to insert into the tree, but that seems > kind of messy. Is there a better way? What about parsing the input into XML first? Is there any point in including unescaped code into XML document unless it is XML itself? > Thanks. > > Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Pychecker Re: Nested List Question
On Thu, 3 Nov 2005, Chris McCoy wrote: > Thank you! I've been banging my head against the wall! > > Chris M. >> gridSystemId = [[None]*columns]*rows > > You've made gridSystemID a list of `rows` references to the SAME "inner" > list, so the behavior you observe is the only possible one. > > If you want copies instead, ASK for copies...: > > gridSystemId = [ [None]*columns for x in xrange(rows) ] Interesting, could not pychecker recognize such situations in Python code and give warnings? Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Pythonising the vim (e.g. syntax popups) -> vimpst
> Evening, > > Is there a decent way to get that help into vim? Or like showing docstrings > or help that I get through pydoc on request? I've been working myself > through a pile of vim macros/plugins but couldn't find even one which > simplifies programming in Python. Further issues would be handling the Hi Christoph, Hi Vim users, The last 5 days I´ve been working on a code-completion/calltips plugin for vim. It´s working pretty good but not finished yet. I will anounce the first beta version on this mailling list. I hope during the next week. I recorded a swf-video so that you can take a look at the current status. Link: http://www.tuxed.de/vimpst/video.tar.gz Note that it is not necessary to generate symboltable files, etc. Everything is done "on demand". It is even possible to change the python implementation e.g. CPython, Jython, IronPython. It is also possible to add some "special feature" interceptor. Currently this is working for SQLObject: Lets say you have the class User and the attribute username is a alternate ID. Then, the method User.byUsername("...") will always return a User object. vimpst checks this and provides a suitable help. Regards, Roman -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric array in unittest problem
* Alex Martelli <[EMAIL PROTECTED]>: > [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > > > Sorry Peter, > > > > Try this > > > > import unittest > > import Numeric > > > > class myTest(unittest.TestCase): > > def runTest(self): > > var1 = Numeric.array([1,22]) > > var2 = Numeric.array([1,33]) > > self.assertEqual(var1,var2) > > > > if __name__ == '__main__': > > unittest.main() > > > i.e., thanks to element-by-element evaluation, == will generally return > a true value for ANY comparison of Numeric arrays, causing a very > frequent beginner's bug to be sure. Try Numeric.alltrue(c), or > Numeric.allclose(a,b) ... I extend unittest.TestCase as follows (uses numarray, not Numeric): class NumTestCase(unittest.TestCase): """Extends TestCase with equality tests for numarrays. """ def numAssertEqual(self, a1, a2): """Test for equality of numarray fields a1 and a2. """ self.assertEqual(a1.shape, a2.shape) self.assertEqual(a1.type(), a2.type()) self.assertTrue(N.alltrue(N.equal(a1.flat, a2.flat))) def numAssertAlmostEqual(self, a1, a2): """Test for approximately equality of numarray fields a1 and a2. """ self.assertEqual(a1.shape, a2.shape) self.assertEqual(a1.type(), a2.type()) if a1.type() == 'Float64' or a1.type() == 'Complex64': prec = 15 else: prec = 7 if isinstance(a1.type(), N.ComplexType): af1, af2 = a1.flat.real, a2.flat.real for ind in xrange(af1.nelements()): self.assertAlmostEqual(af1[ind], af2[ind], prec) af1, af2 = a1.flat.imag, a2.flat.imag for ind in xrange(af1.nelements()): self.assertAlmostEqual(af1[ind], af2[ind], prec) else: af1, af2 = a1.flat, a2.flat for ind in xrange(af1.nelements()): self.assertAlmostEqual(af1[ind], af2[ind], prec) -- http://mail.python.org/mailman/listinfo/python-list
[Announce] boost.date_time library Python bindings
Hi. I am pleased to announce a new Python package - date_time. date_time package is a Python bindings for the boost.date_time C++ library. boost.date_time is a cross-platform and open source C++ library which is designed to provide a basis for performing efficient time calculations. The boost.date_time library has been created by Jeff Garland. boost.date_time library has: * good documentation * well defined interfaces * clear concepts * comprehensive unit tests The boost.date_time library home page: http://boost.org/doc/html/date_time.html. The date_time package also has comprehensive unit tests. Documentation of boost.date_time library can be re-used for the Python package. date_time package available for Linux(Python 2.3) and Windows(Python 2.4). Download: http://tinyurl.com/cp3lo http://sourceforge.net/project/showfiles.php?group_id=118209&package_id=167694&release_id=374482 The date_time package was created using boost.python library and new code generator - pyplusplus. The boost.python library home page: http://www.boost.org/libs/python/doc/index.html The pyplusplus package home page: http://www.language-binding.net/ Enjoy. Roman Yakovenko -- http://mail.python.org/mailman/listinfo/python-list
DB-API 2.0 in pysqlite and pgdb
Happy New Year to all Pythoneers! I am playing with pysqlite and pgdb and their DB-API conformancy. It was quite interesting to know: - sqlite doesn't have mandatory helper-functions Date, Tim, etc. (due to an error int it's __init__, but this is quite obvious to correct or just to use mx.Date, mx.Time) more serious mishaps with pgdb (postgresql-python): it doesn't know how to quote date-time data for the objects it has constructors itself. >>> import pgdb >>> c = pgdb.connect(database="template1") >>> cu = c.cursor() >>> o = pgdb.Time(10, 0, 0) >>> cu.execute("select %(o);", vars()) Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/site-packages/pgdb.py", line 189, in execute self.executemany(operation, (params,)) File "/usr/local/lib/python2.3/site-packages/pgdb.py", line 201, in executemany sql = _quoteparams(operation, params) File "/usr/local/lib/python2.3/site-packages/pgdb.py", line 283, in _quoteparams x[k] = _quote(v) File "/usr/local/lib/python2.3/site-packages/pgdb.py", line 275, in _quote raise InterfaceError, 'do not know how to handle type %s' % type(x) pgdb.InterfaceError: do not know how to handle type This doesn't happen for strings or numbers: >>> cu.execute("select %s;", ['s']) >>> cu.execute("select %s;", [1]) >>> cu.execute("select %(k)s;", {'k': 123}) >>> o Thus, pgdb doesn't know how to handle DateTimeDelta. The same with >>> cu.execute("select %(o)s;", {'o': pgdb.Date(2005,1,1)}) . . . line 201, in executemany sql = _quoteparams(operation, params) File "/usr/local/lib/python2.3/site-packages/pgdb.py", line 283, in _quoteparams x[k] = _quote(v) File "/usr/local/lib/python2.3/site-packages/pgdb.py", line 275, in _quote raise InterfaceError, 'do not know how to handle type %s' % type(x) pgdb.InterfaceError: do not know how to handle type (It was after I commented out exception catch: # except: # raise OperationalError, "internal error in '%s'" % sql in pgdb.py to see where the error occurs) Am I missing something obvious or is it really a bug/feature of pgdb? python2.3 postgresql-7.2.1 almost fresh mx.DateTime Thank you! Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Lambda as declarative idiom (was RE: what is lambda used for in real code?)
Hi all, BTW, Alex Martelli and me have created a PEP 312 some time ago (when the debate of inline if was hot). I wish lambdas will not be deprecated in Python but the key to that is dropping the keyword (lambda). If anybody could think of a better syntax for lambdas _with_ arguments, we could develop PEP 312 further. I DO like the idea of support for universal declaratives in Python. (This way SQL, Prolog, grammar, DTD, lazy expressions, decision tables (advanced switch statements) etc things could be added in a Pythonic way.) We only need brief lambdas and lets (for closures), IMHO. Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Lambda as declarative idiom (was RE: what is lambda used for in real code?)
On Mon, 3 Jan 2005, Steven Bethard wrote: > Roman Suzi wrote: > > I wish lambdas will not be deprecated in Python but the key to that is > > dropping the keyword (lambda). If anybody could think of a better syntax for > > lambdas _with_ arguments, we could develop PEP 312 further. > > Some suggestions from recent lambda threads (I only considered the ones > that keep lambda as an expression): > > * Args Before Expression * > > Nick Coghlan: def-to syntax [1] > (def (a, b, c) to f(a) + o(b) - o(c)) > (def (x) to x * x) Wow! Is there any wiki-page these could be put on? By the way, I think to satisfy least-surprise principle, our declarative idiom must be compatible with type declarations GvR is planning for Python 3.0. This way Python will have ONE style for declarations, be it type declarations, logical declarations or database-queries, etc. This means, that there is a need for a LISP's quote, when code is only written and parsed but may be processed not only by Python interpreter itself but by any user-made interpreter. For example, type-checker, cursor.execute, lazy-Python-subinterpreter, DOM-manipulator etc. I do not know how it could be done syntactically, but it could be done if thought about long enough. Lambdas is one of the ways, arguably not the most pleasant one for a "quote". Maybe this is too outlandish, but I see lambdas as a "quote" mechanism, which presents a possibility to postpone (precisely control, delegate) evaluation. That is, an ovehead for lambda must be much lower but at the same time visible to the programmer: d = a + (lambda x, y: x+ y)(3, 4) if this expression is to be viewed in hypotetical syntax-highlighting editor, "(lambda x, y: x+ y)" need to be painted with another color than the rest of the expression, as it represents defining part of the expression, not the part which is being evaluated right away. What if we deprecate ` in it's repr() function and reserve it for inline lambdas (for Python 3.0, of course): d = a + (` x, y: x+y) (3, 4) Thus, implicit lambdas will be one more symbol, e.g. (`: None) instead of (: None) What does Guido think? ;) Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:[EMAIL PROTECTED] - -- http://mail.python.org/mailman/listinfo/python-list
RE: Python evolution: Unease
On Tue, 4 Jan 2005, Batista, Facundo wrote: Maybe OP doesn't yet fully comprehend the ways of Python universe? As for his claims, I am quite surprised that Python lacks something in the docs. Concerning better hierarchy in the standard library, it is interesting that there are some movements in this direction: xml package, email package, etc. Probably Iwan thinks that letting more "hierachiesness" into std lib Python will be "cleaner". Yes, it will probably look "more organized" this way, but I do not like the idea: import time.time import time.calendar ... import web.url.openers import net.http ... import datatypes.string import textprocessing.re etc. > [Iwan van der Kleyn] > > #- need: a better standard ide, an integrated db interface with > #- a proper > #- set of db drivers (!!), a better debugger, a standard widget/windows > #- toolkit, something akin to a standard for web programming, better > #- documentation, a standard lib which is better organized, a > #- formalized > #- set of protocols and patterns for program construction. And an > #- interpreter which is fast enough to avoid using C or Pyrex in most > #- obvious cases. > > Let's take one by one: > > - IDE: Better than what? Than IDLE? Than Eclipse? Than SPE? Than Pythonwin? > > - Integrated DB interface with a proper set of db drivers (what means the > "!!"?): What do you mean with an integrated db interface? An standard API to > access different DB engines? Something like the Database API specification > (http://www.python.org/topics/database/DatabaseAPI-2.0.html)? There's a SIG > on DB at http://www.python.org/sigs/db-sig/ you may want to look at. > Regarding drivers, to what DB do you miss one? > > - Debugger: Again, better than what? I use the debugger in IDLE and it's > pretty ok. > > - Standard widget/windows toolkit: More standard than Tk? > > - Something akin to a standard for web programming: specifically? > > - Better documentation: Did you find *any* issue in the docs? And why you > didn't post a bug on that? > > - Better organization of the std lib: What do you propose (specifically)? > Please, in your proposal, take in consideration migration plans and how the > migration affect actual systems. And of course, why the new organization is > better than the old one. BTW, I also think that it should be better > organized, but don't know how. > > - a formalized set of protocols and patterns for program construction: a > what? > > - an interpreter which is fast enough to avoid using C or Pyrex in most > obvious cases: CPython is More Than Fast Enough. In which obvious cases it's > not enough for you? > > Don't misinterpret this response. I know it was a rambling. But *maybe* you > have something to contribute to Python development, even good ideas only and > no work. > > .Facundo Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:[EMAIL PROTECTED] - -- http://mail.python.org/mailman/listinfo/python-list
Re: Lambda as declarative idiom (was RE: what is lambda used for in real code?)
On Tue, 4 Jan 2005, Steven Bethard wrote: >Roman Suzi wrote: >> On Mon, 3 Jan 2005, Steven Bethard wrote: >> >> >>>Roman Suzi wrote: >>> >>>>I wish lambdas will not be deprecated in Python but the key to that is >>>>dropping the keyword (lambda). If anybody could think of a better syntax for >>>>lambdas _with_ arguments, we could develop PEP 312 further. >>> >>>Some suggestions from recent lambda threads (I only considered the ones >>>that keep lambda as an expression): >> >> Wow! Is there any wiki-page these could be put on? > >It's now on: > >http://www.python.org/moin/AlternateLambdaSyntax > >and I added Bengt Richter's and your recent suggestions. Hmmm... what if we kill two rabbits in one blow: lambda will be even more implicit, if we just mark parameters by a back-quote while using PEP 312 convention: (:f(`a) + o(`b) - o(`c)) (:`x * `x) (:x) (:x.bar(*`a, **`k)) Not sure about default args: ((fun(x=x, a=a, k=k): x(*a, **k)) for x, a, k in funcs_and_args_list) Maybe this needs to be done with closures. Otherwise I think Python interpreter is quite capable to determine which parameters the function has... Only their order become a problem. Probably, ","-s could be used there: (`a,`b,`c : f(`a) + o(`b) - o(`c)) The whole expressions could be quoted: `(x, y, z) meaning a parameter with such structure. >Steve > Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python evolution: Unease
On Tue, 4 Jan 2005, Dave Brueck wrote: >> It may be optional in the sense that the language will >> accept missing declarations but as soon as the feature >> is available it will become "mandatory" to use it >> (peer pressure, workplace practices). What about generic programming coming into fashion anytime soon? >That's my fear - type declarations could become one of the most abused language >features because they'd get used too often. > >-Dave > Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional Static Typing: Part II
On Tue, 4 Jan 2005, John Roth wrote: >Guido has posted a second blog entry on the optional static typing >initiative. >I like this a lot better than the first. Declarative approach is even more human-oriented than algorithmic one. If Python is to support declarations, let it support declarative programming paradigm with full-blown inference engine . So, why not add some logic approach to type declarations? I hope that "type" is understood in a generic programming way: it will be a big win for Python to provide grounds for GP 'concept' concept ;) Why not? Python program right now are nearer to GP than C++'s. 'Concept' is not mere "interface", but interface + semantic behaviour. And to describe that behaviour logic is needed (right now it could be done with asserts). I propose to skip 'interface' support with Python and go stright to GP concepts :> This way Python will be ahead with innovation and type/interface/concept declarations will not be seen as atavisms but a step forward from OOP. I hope GvR waited so long not implementing interfaces to implement something better, concepts for example ;-) Right now concepts are expressed informally in the docstrings. Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python evolution: Unease
On Tue, 4 Jan 2005, Dave Brueck wrote: >Roman Suzi wrote: >>>>It may be optional in the sense that the language will >>>>accept missing declarations but as soon as the feature >>>>is available it will become "mandatory" to use it >>>>(peer pressure, workplace practices). >> >> >> What about generic programming coming into fashion anytime soon? > >Roman, I think I've read every single thread in the past year or three wherein >you've brought up generic programming, and I think you'd do well to choose a >new >term for the idea you're trying to convey. IIRC, I did it only once: at fall 2004. >The term "generic programming" is too... er... generic. :) Nope. It is not generic. It has it's definition made by the co-author of STL - A.Stepanov. And the Boost C++ library (many of us know it as Boost Python) standardise on the approach, AFAIK. >As you know, Python >already includes a _lot_ of support for generic programming (a function that >iterates over a sequence can easily process a list, or a string, or a tuple as >input; a function that takes a file-like object can often work just as will >with >a true file object or a cStringIO object; etc.). So when you bring up "generic >programming", it's too easy to dismiss the comment because (1) it's too vague >and (2) Python already does a lot of it. > >So, what is your term for the type of generic programming that Python doesn't >yet support? Interfaces? Protocols? Adapters? Metatype hierarchies? Python could have honest support of concepts. Everything else will be available with them. That is the whole point that Python supports GP. It is only one step to do concepts right (and GvR it seems want type-checking into Python 3.0 anyway), so support for concepts/concept checking is very logical, isn't it? Right now concepts in Python are things which experienced Python programmers know from practise. Sometimes, they feel them unconsciously. Concepts could be veryfied and this, for example, could prevent errors like DB-API-complient module doesn't have some small, but necessary to comply, attributes. Standard concepts could be part of standard concept "metalibrary", along with verification mechanisms (this could be done even on C++, why not in a candy like Python?). So every programmer could verify that his/her class, created to satisfy concept XYZ is (formally) such. Your example - cStringIO - does it really satisfy concept of STRING? It does. Partially. Those "partially" here and there could lead to madness. Unit testing will be simplified too, because structural tests will be built into concept-checking mechanism. And BTW, are we really disputing? What do you propose instead? Old-fashioned Pascal-like type definitions? Java-like interface/implementaion ...? IMHO it could be a big mistake to play catch-up. Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python evolution: Unease
On Tue, 4 Jan 2005, Dave Brueck wrote: >> What about generic programming coming into fashion anytime soon? >Roman, I think I've read every single thread in the past year or three >wherein you've brought up generic programming, and I think you'd do well to >choose a new term for the idea you're trying to convey. Or, yes, and I forgot to mention that generic programming is much clearer idea than OO programming, as it is not so vague. At least for me: I still don't fully comprehend OOP (after N years of "studying" it!) and understanding of GP came after just one book on the topic. Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python evolution: Unease
On Tue, 4 Jan 2005, Ian Bicking wrote: >Umm... this isn't helpful. "Generic" and "concept" are not terms that >belong to Boost or STL or whatever. They are just words. Coining the >term doesn't mean anyone else knows what it means, nor that anyone >*should* know what they mean -- personally I get very suspicious of >ideas that are based on redefined words, that tends to be a way of >hiding complexity or fuzziness. > >But anyway, if you use these terms, you really must provide references, >otherwise no one will know what you mean. "Python could have honest >support of concepts" is simply an incomplete sentence. "Python could >have honest support of Concepts (url)" would be more reasonable. Sorry. I use definitions from there sources: 1. http://www.cs.rpi.edu/~musser/gp/ 2. "A Formalization of Concepts for Generic Programming" (google could find PDF of that). If I am correct, this one: http://www.osl.iu.edu/publications/pubs/2004/willcock04:_formal_concep_gener_progr.pdf (it is safe to skip till example on Fig.1 to grasp the idea behind a concept. Relations between concepts are also very logical and remind of inheritance, association and aggregation) 3. "The Boost Graph Library" by Jeremy Siek, et al with A.Stepanov's foreword is a good way to see GP != STL. Probably Boost docs contain some knowledge on the topic, at least Boost Graph Library's ones (which I read). >"Python could have honest support of Concepts (url)" - of course, right now those sources are C++-specific. But I could see that Python has even greater potential to have concepts ahead of C++ and with greater usefulness at the same time. Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python evolution: Unease
On Tue, 4 Jan 2005, Dave Brueck wrote: >Roman Suzi wrote: >>>The term "generic programming" is too... er... generic. :) >> Nope. It is not generic. It has it's definition made by the co-author >> of STL - A.Stepanov. And the Boost C++ library (many of us know it as >> Boost Python) standardise on the approach, AFAIK. > >Ok, "too broad" then; Python already supports at least some aspects of generic >programming (at least, in the sense that I think you mean it), so it'd be good >to spell out what specific features you're referring to. > >> Python could have honest support of concepts. Everything else will be >> available with them. > >"Concepts" is a pretty generic term too! ;-) Do you mean concepts as defined >here: http://www.boost.org/more/generic_programming.html >? Yes. >> And BTW, are we really disputing? > >No, not at all - I'm just trying to better understand what you mean. Words >like "generic" and "concepts" don't yet have a widely recognized, strict >definition in the context of programming. If somebody has assigned some >specific definition to them, that's great, it's just not universal yet so >references and additional explanations are helpful. I apologize for not providing URLs to the exact definitions in the first place! I really think there is ONE understanding of GP vs. multitudes of understandings of OOP. Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: args (was Re: Lambda as declarative idiom (was RE: what is lambda used for in real code?))
On Tue, 4 Jan 2005, Michael Spencer wrote: >Roman Suzi wrote: > >> Maybe this is too outlandish, but I see lambdas as a "quote" mechanism, >> which presents a possibility to postpone (precisely control, delegate) >> evaluation. That is, an ovehead for lambda must be much lower but at the >> same time visible to the programmer: >> >> d = a + (lambda x, y: x+ y)(3, 4) >[...] > >I believe that this "possibility to postpone" divides into two related but >separate concepts: controlling the moment of evaluation, and assembling the >arguments required at that moment. Yes. I have the same understanding. >They are both species of 'eval', but >managing arguments is more specialized, because it includes possibly renaming >parameters, assigning default values, processing positional and keyword >arguments, and, perhaps in the future dealing with argument types. Very precise! >Meanwhile, GvR wrote (about defining Interfaces in the context of Optional >Static Type Checking) As for GvR's writing, I think he is exploring the ground. What he wrote is too complex for Python and he guesses it is. There i another thread in c.l.p where I propose generic programming approach for Python's "type checking": IMHO, a much simpler and more natural for Python than programming by contract, just interfaces and such. And the syntactic way to express concepts is going thru declarations. That is why lambdas are to be on steroids for this task. More than that, compile vs. evaluation/parameter dispetching must not muddy the waters for programmer. It must always be clear (syntactically too) for him what is going on in the expression at hand. (But I do not know how this could be elegantly done sytactically) Is declaration-chewing engine built into Python an overkill? There are at least 2 specialized ones in it: parser and re.compile + many for different formats, like xml.dom. Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
coding conventions, PEP vs. practice
Dear python-list, while looking for some coding conventions for python programs, i found the PEP8 at http://www.python.org/peps/pep-0008.html. It defines the rules very well and leaves no space for interpretations. I guess thats a good thing :-) But when i started playing a bit with python and frameworks like Zope, Webworks, etc., i noticed, that a lot frameworks are using a different convention for methodnames. These frameworks are using "mixedCase" but PEP8 suggests "lower_case_with_underscores" except "in contexts where that's already the prevailing style" which is not the case here IMHO. So, are there any specific reasons for breaking the rules here? I think consistent conventions are very important. Being a Java developer in the last couple of years, i learned how practical it can be to have only one naming style. Best regards, Roman -- http://mail.python.org/mailman/listinfo/python-list
Concepts RE: Python evolution: Unease
On Wed, 5 Jan 2005, EP wrote: >Roman wrote: > >> Maybe OP doesn't yet fully comprehend the ways of Python universe? > > > >> > Don't misinterpret this response. I know it was a rambling. But >> *maybe* you >> > have something to contribute to Python development, even good ideas >> only and >> > no work. >> > >> > .Facundo > > >Am I selling Snake Oil? > >What I do have is a "forest" instead of an "in the trees" perspective, and >from a forest view I see a lot of defensiveness about Python's hypothetical >shortcomings. No one needs be defensive, Python is an amazing programming >language, and everyone involved with its development, evolution, support and >codebase ought to feel quite good about it. -skip- It's c.l.p and people are free to express their opinions. Even negative. This helps improve Python. As for concepts, they are from Generic Programming (by Musser and Stepanov) and I feel that Python is in position to implement them to the fullest extent. And IMHO it will be nicer than just Java-like interfaces or Eiffel's contract approach. I can try to write a PEP "Generic Programming Concepts". Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python evolution: Unease
On Wed, 5 Jan 2005, Alex Martelli wrote: >Dave Brueck <[EMAIL PROTECTED]> wrote: > ... >> No, not at all - I'm just trying to better understand what you mean. Words >> like "generic" and "concepts" don't yet have a widely recognized, strict >> definition in the context of programming. If somebody has assigned some >> specific definition to them, that's great, it's just not universal yet so >> references and additional explanations are helpful. > >Googling for "generic programming" (with the quotes) gets 100,000 + >hits. The first couple pages of hits, at least, seem to all be speaking >about exactly the same thing. The terminology appears to be settled >enough that Oxford's St Anne College feels they can organize a "Summer >School on Generic Programming", Nottingham University a "Workshop on >Generic Programming", etc, etc, without fearing ambiguity. That is why I was pretty sure people undestand me. >Exactly what extra support Roman would want from Python for 'concepts', >beyond that offered by, say, C++, I'm not sure. Protocols, interfaces >and design-by-contract are other terms often used to try and capture >pretty similar issues. I just happen to like the term 'concept' more than Protocols, interfaces, and design-by-contract ;-) Alex, I think you are +10 for adding interfaces into Python. "Concept" is more compact word and I am sure it is not used as a name in existing projects, unlike other words. Also, Python concept collection could be used as a teaching example or templates for high quality code. Concepts need not appear in every script out there, but as a result of design. What else Python needs to support GP? A possibility to formally define a concept (and concept relations) with (optionally) checks of implementations. I do not even insist in making it all run-time! Perhaps concepts could be checked in PyChecker. And (perhaps) the whole type-checking could be done this way. However sweety it is, I also hope to have keystrokes saved when I use ready-maid concept in my program. Just imagine we have a concept for table and use (as adaptor) it for db-connectivity, CSV-readers/writers, XML/HTML parsers/writers, arrays, lists, ... Right now Python _almost_ has it. However, small differences in small details do not allow to interchange even different dbm-modules! I remember getting into trouble when I switched from bsddb to gdbm: some places needed 'r' to be explicitly specified! Same problems with db-api 2.0 "almost" conformant modules, datetime types and other small details which are similar but differ in small details at the same time. I think the same has place with XML-DOM implementations and such. I think concepts could be guards against such things and also make life easier for those who implement some standard protocols. That is, concepts could be internal (Python) standardizing and quality control technique. We can use constant publicId, systemId a-la XML for concepts, so upgrade path will be similar to HTMLs. This will make concept-changing visible between versions. Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Concepts RE: Python evolution: Unease
On Wed, 5 Jan 2005, Paul Rubin wrote: >Paul Rubin <http://[EMAIL PROTECTED]> writes: >> There is nothing in Wikipedia about [Generic programming]. > >Oops: http://en.wikipedia.org/wiki/Generic_programming > >This helps. But I don't see how it's different from what used to >be called polymorphism. I already posted these links. They seem to give more fundamental definitions than wikipedia: ''' 1. http://www.cs.rpi.edu/~musser/gp/ 2. "A Formalization of Concepts for Generic Programming" (google could find PDF of that). If I am correct, this one: http://www.osl.iu.edu/publications/pubs/2004/willcock04:_formal_concep_gener_progr.pdf (it is safe to skip till example on Fig.1 to grasp the idea behind a concept. Relations between concepts are also very logical and remind of inheritance, association and aggregation) 3. "The Boost Graph Library" by Jeremy Siek, et al with A.Stepanov's foreword is a good way to see GP != STL. ''' As for polymorphism, yes, polymorphism. But any decent language has some sort of polymorphism today. The essense of concepts is that they provide formalities for (call them) contracts, interfaces, etc. Concepts from GP gather all these together and call it a concept: a family of similar types. Python already uses concepts implicitly, by convention. And we know them well: file-like objects, sequences, maps, sets, queues, arrays, etc. My "marketing" of GP is directed to formalise on concepts instead of partial cases (design-by-contract, interfaces etc). Thus, concepts control polymorphism not only from liberation side, but from constraint side too. Right now concepts in Python are reused here and there without explicit mentioning. Concepts could help make code even more reusable. Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python evolution: Unease
On Fri, 6 Jan 2005, Paul Rubin wrote: >software when I buy a new computer, or at least a new hard drive. I >don't try to migrate system or configuration files. I just install >the OS distro from scratch and migrate my user files. > >> There are several parts to those frustrations. But you are presuming >> that they would have been solved for you and put on a DVD with all >> dependency problems resolved. Ok, let's assume that. In that case, >> an installation stub module could just as well have the solution built >> into it as to what versions etc are needed to make the module work. I do not like the idea of having stubs. Once I had an experience working with CPAN (I tried to install SpamAssassin and it required some specific modules.) "Magic" install shell, provided by Perl, upgraded half the Perl distro, including newer version of Perl! So, I do like Python distutils better. it is not a major problem to install something even if it required something else. Of course, this depends on the package authors. >How can it work just as well, when it requires a high-speed internet >connection which I might not have? And why is "just as well" good >enough, given how inconvenient and error-prone it is, compared with >just installing from a DVD once and for all? To have any attraction >what ever, the installation stub scheme (for me at least) has to work >"an order of magnitude better", not "just as well", as a one-time >complete install. > >> To bring a large collection into version-alignment ISTM you need a version >> freeze across too many libraries of different kinds with different >> development schedules and resources to make it reliable. > >One part of the problem is excessive version dependence between >package X and package Y. That's why I think there should be more >integration within packages, i.e. the Python distro should include a >lot more modules that you currently have to download from other >places. > >> I realize this problem has been "solved" with various RPM and >> app-loading methods, but I think python could wrap its solution >> nicely. I don't think distutils and setup.py is easy enough to >> create (at least I have been somewhat frustrated in using it >> effectively), though it deals with a lot of what has to be done. > >Since all these schemes have failed whenever they've been tried, all I >can think is that it's a harder problem than it sounds. I have installed many packages with Distutils, and usually there were no problems. If there were, they were no greater than installing some devel library and/or adding an include directory. So, Distutils, IMHO, are successful. Yes, probably there could be a no-brainer script to run install directly from zip and/or tar.gz/bz2 file, but I usually check md5, pgp sigs and look inside anyway before running something. Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
interpreter Py_Initialize/Py_Finalize mem leak?
In pure curiosity I tried to compile loop.c from Demo/embed and started it with 'print 2+2'. It seems, that both 2.3 and 2.4 pythons have memory leaks in Py_Initialize/Py_Finalize calls. (That is, interpreter doesn't clean up well after itself). This is my setup: gcc -fpic loop.c -DHAVE_CONFIG_H -lm -lpython2.4 \ -lpthread -lutil -ldl \ -I/usr/local/include/python2.4 \ -L/usr/local/lib/python2.4/config \ -o looptest (It's on Linux RedHat 7.3) I do not know if this is of any importance though. Probably it is for embedded Python uses. Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python3: on removing map, reduce, filter
On Sun, 9 Jan 2005, Paul Rubin wrote: >Andrey Tatarinov <[EMAIL PROTECTED]> writes: I hope there will be from __past__ import functional_paradigma in Python 3 ;-) And, also, what is the best way to replace reduce() ? Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
RE: interpreter Py_Initialize/Py_Finalize mem leak?
On Mon, 10 Jan 2005, Delaney, Timothy C (Timothy) wrote: >Roman Suzi wrote: > >> In pure curiosity I tried to compile loop.c from Demo/embed >> and started it with 'print 2+2'. It seems, that both 2.3 and 2.4 >> pythons have memory leaks in Py_Initialize/Py_Finalize calls. >> (That is, interpreter doesn't clean up well after itself). > >What's your evidence for this (i.e. what are the symptoms)? - memory usage grows over time. >If you have a repeatable test case, please raise a bug report on >SourceForge. I tested only under Linux. And it is 100% repeatable. >Tim Delaney > Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: java 5 could like python?
On Wed, 12 Jan 2005, vegetax wrote: >-No naming convention. The speech of "it fits in my head" is no longer valid >when i use a lot of functionality,modules,classes in a large proyect. >For example if i remember a function i want ie:get attribute, i dont >remember if the module implementer coded it as >getAttribute,GetAttribute,get_attribute, then i have to go and check the >doc, every time,which is a waste of time. Or yes, I hate those 'get' too. Why not to use just obj.attribute instead? Otherwise, the pluralism present in Python, makes me feel more at home. >-library Organization,we have modules that can have 20 classes(I imagine >that is because of the commodity of having all in one file) which makes >reading the doc horribly painfull and is very hard to find the stuff >coupled with the "pool" of modules that is the python installation >directory,all throwed away at the installation directory without a >categorization. Probably some Really Large Corporation could add Python Standard Library Enterprise Edition and win big. >-Is python library half object oriented? half functional oriented? I can Right now it change its orientation to iterator/generators... I image a nice box with Python 3 in it, where there will be no more inconsistencies with naming, etc. >understand that python allows some functional programing components when >they are necesary,but there are libraries that totaly ignore object >orientation which makes them problematic to use.for example,Whats with the >os.path module and files? why do i have to say os.path.getfilesize(f.name) >all the time? why cant i say f.size? Why does urlparse returns a tuple of 7 >items instead of an URL object? why there isnt an URL object? and so on.. This reminds me of attributes vs. tags debate of how to structure XML. size(f) or f.size() - that is the question >I havent figured out a way to overcome those factors,the delaying and lost >of focus that is having to check the docs all the time,every 5 seconds and >having to make object oriented wrapers for several libraries or having to >go and read the source code to know what the heck a function returns or >what are its arguments makes coding unpleasant an very slow , i often have >15 pydocs windows open at the same time. What should i do? Do not use windows. Sit for an evening add read all the docs. Coding will becaome much faster. >-Realying on ides is imposible due to python dinamic nature,very litle(next >to nothing) assistance can be espected from them. Class browsing and auto-completion are probably the only features I sometime miss. But otherwise what IDEs are for? >-Memorazing all the function names,parameters,return values,conventions of >the modules i use doesnt look like a good solution. But it is a must: how do you communicate if you do not nother to remember words? >Join it with poor and outdated documention and we have a very unpleasant >standard library. >class C{ > public void func(){ > print("hello world"); // instead of System.out.println("hello world"); Probably print statement will not make it into Python 3.0. Very sad. > print(run("ls /tmp")); > } >} > >Same for almost all python builtin functions. > >Also there is the generics support and so on.. > >But for some reason i dont know,the switch back feels wrong =( ,would it be >posible to imitate python's behavior with the new java features and some >hacks? would be worth the effort? If not what can i do to use efficiently >python modules and libraries? I recall, i didnt had this problem when doing >small applications with a small set of modules. > >Sorry for my bad english. That is it. I hate English. It has sooo much exceptions to remember! Esperanto is much cleaner language. UN should drop all it's official languages and use Esperanto instead. Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
RuntimeError: dictionary changed size during iteration
I think, the behaviour below is misfeature: >>> [e for e in vars()] Traceback (most recent call last): File "", line 1, in ? RuntimeError: dictionary changed size during iteration >>> e = None >>> [e for e in vars()] ['e', '__builtins__', 'rlcompleter', '__file__', '_[1]', 'atexit', '__name__', 'readline', '__doc__'] Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
RE: RuntimeError: dictionary changed size during iteration
On Thu, 20 Jan 2005, Batista, Facundo wrote: >For me, the point is: vars() returns the local variables as a list or is a >generator? > >In the docs don't say nothing about this. > >If it returns a list, it should NOT raise an error; if it's a generator, the >error is fine. > >.Facundo > Probably, e need not appear in vars() at all... This is why generator closure works fine. Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: question about deleting records from mysql
# [EMAIL PROTECTED] / 2005-07-27 05:12:46 -0700: > ok. did this > > >>> cursor.execute("DELETE FROM table WHERE autoinc > 1000") > 245L > >>> cursor.commit() > > i got an AttributeError 'Cursor' object has no attribute 'commit' > > hmm. what should i do now? RTFM, e. g. here: http://cvs.sourceforge.net/viewcvs.py/mysql-python/MySQLdb/doc/MySQLdb.txt?rev=1.1&view=auto -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- http://mail.python.org/mailman/listinfo/python-list
Re: Extended Language c++ in pyhton
Decide your self: http://seal.web.cern.ch/seal/snapshot/work-packages/scripting/evaluation-report.html My recomendation is boost.python. If you choose boost.python then there are a few code generator tools for it. One of them is pyplusplus ( see http://pygccxml.sourceforge.net/pyplusplus/pyplusplus.html ) Roman On 9/1/05, elho <[EMAIL PROTECTED]> wrote: > I found serveral tool for using C++ as extended languate in python - but > what's the best / easiest to use? > > With C I used wrappy - not sure if it's the wright name, it's included > since Python 1.6 and it ist pretty ease to use. You know an example with > this util for C++ or isn't it possible for C++. > > Would be nice to get your opinion. thx > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Is email package thread safe?
Hi! Just to be sure, is email package of Python 2.3 thread-safe or not (to use, for example, in python-milter?) Sincerely yours, Roman A.Souzi -- http://mail.python.org/mailman/listinfo/python-list
Re: Choosing the right parser for parsing C headers
try http://sourceforge.net/projects/pygccxml There are a few examples and nice ( for me ) documentation. Roman On Tue, 8 Feb 2005 13:35:57 +0100, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > Jean de Largentaye wrote: > > > GCC-XML looks like a very interesting alternative, as Python includes > > tools to parse XML. > > The mini-C compiler looks like a step in the right direction for me. > > I'm going to look into that. > > I'm not comfortable with C++ yet, and am not sure how I'd use Pyste. > > to clarify, Pyste is a Python tool that uses GCCXML to generate bindings; it > might > not be something that you can use out of the box for your project, but it's > definitely > something you should study, and perhaps borrow implementation ideas from. > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Is email package thread safe? (fwd)
(this is a repost with an addition - probably noone noticed my message first time) Hi! Just to be sure, is email package of Python 2.3 thread-safe or not (to use, for example, in python-milter?) P.S. And where can I find information on particular piece of standard library if it is thread-safe or need locking? I recall 'random' module is (was?) unsafe - which isexplicitly stated in the docs. Can I assume that everything else without such notice is thread-safe? Sincerely yours, Roman A.Souzi -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Is email package thread safe? (fwd)
On Wed, 9 Feb 2005, Antoon Pardon wrote: Op 2005-02-09, Roman Suzi schreef <[EMAIL PROTECTED]>: Just to be sure, is email package of Python 2.3 thread-safe or not (to use, for example, in python-milter?) Can I assume that everything else without such notice is thread-safe? I doubt it. There is no indication that the email package uses any kind of locking. So multiple thread working on the same message will probably screw things up. Of course, I do not let threads to work on the same message! I meant that the package doesn't pose other kinds of restrictions. Can it work in _any_ situation work on two different messages at the same time, without any interference? Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Is email package thread safe? (fwd)
On Thu, 10 Feb 2005, Antoon Pardon wrote: Op 2005-02-09, Roman Suzi schreef <[EMAIL PROTECTED]>: On Wed, 9 Feb 2005, Antoon Pardon wrote: Op 2005-02-09, Roman Suzi schreef <[EMAIL PROTECTED]>: Just to be sure, is email package of Python 2.3 thread-safe or not (to use, for example, in python-milter?) Can I assume that everything else without such notice is thread-safe? I doubt it. There is no indication that the email package uses any kind of locking. So multiple thread working on the same message will probably screw things up. Of course, I do not let threads to work on the same message! Why should that be: "off course"? The random module you spoke about was also only thread unsafe if you called the same random generator from various threads. Using a randon generator per thread shouldn't have been a problem. Since you mentioned that, I thought that was the kind of thread safety you were after. I meant that the package doesn't pose other kinds of restrictions. Can it work in _any_ situation work on two different messages at the same time, without any interference? I can't give a guarantee, but there are no global statements and there doesn't seem to be assignments to cross module variables I think it would be a safe bet. Thanks to all who discussed this. Really, I had the same thoughts about 1:1 object-thread relation being thread safe. I am doing further research and if it will give interesting results, I shall post [solved] here. Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Recursive __cmp__ in different Python versions
#The following Python code: class X: def __cmp__(self, y): print "cmp", self, y return cmp(self, y) x = X() print x < 10 # gives interesting results under different Python version. The most common sense in the result in Python 2.4: recursion limit reached. Python 2.3 tries 20+ times and then give up. Python1.5 gives segmentation fault... Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Bug in email package?
I was playing with email package and discovrered this strange kind of behaviour: import email.Message m = email.Message.Message() m['a'] = '123' print m From nobody Mon Feb 21 00:12:27 2005 a: 123 for i in m: print i ... Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/email/Message.py", line 304, in __getitem__ return self.get(name) File "/usr/local/lib/python2.3/email/Message.py", line 370, in get name = name.lower() AttributeError: 'int' object has no attribute 'lower' I think that if any object (from standard library at least) doesn't support iteration, it should clearly state so. My guess is that 'for' causes the use of 'm[0]', which is (rightfully) an error... Can this behaviour of email be considered a bug? Is there a good case to iterate over something useful in a message? P.S. rfc822 has the same behaviour, at least on Python 2.3 Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Bug in email package?
On Sun, 20 Feb 2005, Steven Bethard wrote: Erik Max Francis wrote: Roman Suzi wrote: I think that if any object (from standard library at least) doesn't support iteration, it should clearly state so. My guess is that 'for' causes the use of 'm[0]', which is (rightfully) an error... Can this behaviour of email be considered a bug? Is there a good case to iterate over something useful in a message Why would it be a bug if the documentation never stated that the object was iterable? I think the bug is not that an error is produced, but that the _wrong_ error is produced. Trying to iterate over something that is not iterable should Well, that was what I meant. produce a TypeError saying so (not an Attribute error): py> class C(object): ... pass ... py> iter(C()) Traceback (most recent call last): File "", line 1, in ? TypeError: iteration over non-sequence I've actually seen something like this come up before (I think with email.Message even...) I say call it a bug and submit a patch. Ok. A bug minute on the next bug day ;-) It's pretty easy to fix -- just add an __iter__ method to Message that raises a TypeError. That makes it clear that Message doesn't intend to support the getitem protocol -- it just does so accidentally because it provides __getitem__. STeVe Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Decorators for multimethods
hi! I've found one more nice use case for decorators. I feel multimethods could be made even nicier by defining multimethods inside special class. But I have not figured out how to do it yet. #!/bin/env python2.4 if "We have Neel Krishnaswami module Multimethod.py": import Multimethod class Foo: pass class Bar(Foo): pass def multimethod(g, *args): def make_multimethod(func): mm = Multimethod.Method(tuple(args), func) g.add_method(mm) return mm return make_multimethod g = Multimethod.Generic() @multimethod(g, Foo, Foo) def m1(a, b): return 'foofoo' @multimethod(g, Foo, Bar) def m2(a, b): return 'foobar' @multimethod(g, Bar, Foo) def m3(a, b): return 'barfoo' try: print 'Argtypes ', 'Result' print 'Foo, Foo:', g(Foo(), Foo()) print 'Foo, Bar:', g(Foo(), Bar()) print 'Bar, Foo:', g(Bar(), Foo()) print 'Bar, Bar:', g(Bar(), Bar()) except Multimethod.AmbiguousMethodError: print 'Failed due to AmbiguousMethodError' Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
A puzzle Re: Decorators for multimethods
For those who want to exercize Python skills, there is a problem below for defining multimethod g with as simple syntax as possible: @MULTIMETHOD def g(x, y): @PART(Foo, Foo) def m1(a, b): return 'foofoo' @PART(Foo, Bar) def m2(a, b): return 'foobar' @PART(Bar, Foo) def m3(a, b): return 'barfoo' What are definitions of MULTIMETHOD and PART in this case? (if such are at all possible). My best result was with class G(MMCLASS): def define(self): @self.PART(Foo, Foo) def m1(a, b): return 'foofoo' @self.PART(Foo, Bar) def m2(a, b): return 'foobar' @self.PART(Bar, Foo) def m3(a, b): return 'barfoo' g = G() where class MMCLASS(Multimethod.Generic): def __init__(self): Multimethod.Generic.__init__(self) def PART(*args): def make_multimethod(func): mm = Multimethod.Method(tuple(args), func) print func self.add_method(mm) return mm return make_multimethod self.PART = PART self.define() On Fri, 10 Dec 2004, Roman Suzi wrote: > >hi! > >I've found one more nice use case for decorators. I feel multimethods >could be made even nicier by defining multimethods inside special >class. But I have not figured out how to do it yet. > >#!/bin/env python2.4 >if "We have Neel Krishnaswami module Multimethod.py": > >import Multimethod > >class Foo: pass > >class Bar(Foo): pass > >def multimethod(g, *args): > def make_multimethod(func): >mm = Multimethod.Method(tuple(args), func) >g.add_method(mm) >return mm > return make_multimethod > >g = Multimethod.Generic() > >@multimethod(g, Foo, Foo) >def m1(a, b): return 'foofoo' > >@multimethod(g, Foo, Bar) >def m2(a, b): return 'foobar' > >@multimethod(g, Bar, Foo) >def m3(a, b): return 'barfoo' > >try: >print 'Argtypes ', 'Result' >print 'Foo, Foo:', g(Foo(), Foo()) > print 'Foo, Bar:', g(Foo(), Bar()) >print 'Bar, Foo:', g(Bar(), Foo()) >print 'Bar, Bar:', g(Bar(), Bar()) >except Multimethod.AmbiguousMethodError: >print 'Failed due to AmbiguousMethodError' > > >Sincerely yours, Roman Suzi > Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
LD_LIBRARY_PATH - how to set?
Hi. I have small problem. I need to load extension module that depends on shared library. Before actually importing module I tried to edit os.environ or to call directly to os.putenv without any success - shared library was not found. I tried to search the Internet for the answer. The only approach I saw was to set LD_LIBRARY_PATH before invoking python script. I don't like this solution. Roman -- http://mail.python.org/mailman/listinfo/python-list
Re: LD_LIBRARY_PATH - how to set?
On Mar 31, 2005 9:20 AM, John Abel <[EMAIL PROTECTED]> wrote: > What OS? Linux? Solaris? Does it matter? If so, please explain why ( lack of knowledge ) I am using Linux ( Debian Surge ) Thanks > J > > Roman Yakovenko wrote: > > >Hi. I have small problem. I need to load extension module that depends > >on shared library. Before actually importing module I tried to edit > >os.environ or to call directly to os.putenv without any success - > >shared library was not found. I tried to search the Internet for the > >answer. The only approach I saw was to set LD_LIBRARY_PATH before > >invoking python script. I don't like this solution. > > > >Roman > > > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: LD_LIBRARY_PATH - how to set?
Thanks for help. But it is not exactly solution I am looking for. I would like to do it from python script. For example update_env() #<- this function will change LD_LIBRARY_PATH import extension_that_depends_on_shared_library Roman On Mar 31, 2005 9:35 AM, John Abel <[EMAIL PROTECTED]> wrote: > With Solaris 8+ you would use the command crle, with Linux > (RedHat/SuSE/Mandrake) you need to add the relevant directories > /etc/ld.so.conf and run ldconfig. I've not got a Debian box to hand, so > I can't say if it matches, but that should give you a pointer. I think I should have permissions to do it. (more over users of my scripts should have permissions ) > HTH > > J > > Roman Yakovenko wrote: > > >On Mar 31, 2005 9:20 AM, John Abel <[EMAIL PROTECTED]> wrote: > > > > > >>What OS? Linux? Solaris? > >> > >> > > > >Does it matter? If so, please explain why ( lack of knowledge ) > >I am using Linux ( Debian Surge ) > > > >Thanks > > > > > > > > > >>J > >> > >>Roman Yakovenko wrote: > >> > >> > >> > >>>Hi. I have small problem. I need to load extension module that depends > >>>on shared library. Before actually importing module I tried to edit > >>>os.environ or to call directly to os.putenv without any success - > >>>shared library was not found. I tried to search the Internet for the > >>>answer. The only approach I saw was to set LD_LIBRARY_PATH before > >>>invoking python script. I don't like this solution. > >>> > >>>Roman > >>> > >>> > >>> > >>> > > > > > > > > -- > *John Abel > Senior Unix Administrator* > PA News Limited > www.pa.press.net <http://www.pa.press.net> > E-Mail address: [EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]> > Telephone Number : 01430 43 > Fax Number : 0870 1240192 > Mobile Number : 07971 611356 > The Bishop's Manor, Market Place, Howden, DN14 7BL > PA News Limited, 292 Vauxhall Bridge Road, London SW1V 1AE. Registered > in England No. 3891053. > -- http://mail.python.org/mailman/listinfo/python-list
Re: LD_LIBRARY_PATH - how to set?
On 31 Mar 2005 00:51:21 -0800, Serge Orlov <[EMAIL PROTECTED]> wrote: > Roman Yakovenko wrote: > > Hi. I have small problem. I need to load extension module that > depends > > on shared library. Before actually importing module I tried to edit > > os.environ or to call directly to os.putenv without any success - > > shared library was not found. I tried to search the Internet for the > > answer. The only approach I saw was to set LD_LIBRARY_PATH before > > invoking python script. I don't like this solution. > > Looks like it's glibc linker inflexibility: > http://hathawaymix.org/Weblog/2004-12-30 > """ > There is no provision for modifying the library search path once your > program has started. > """ Thanks, well small script around my program will make the trick. I think I have no other choise. > Python does update enviromental variables if you change os.environ or > call os.putenv, but the linker ignores the changes. > Serge. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
sys.stdout / sys.stderr, subprocess, redirection
Hello, I have a piece of code that gets run in a script that has its stdout closed: import sys sys.stdout = sys.stderr c = subprocess.Popen (..., stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.STDOUT) and this is what I get: SendingSVNR/permissions Transmitting file data .svn: Commit failed (details follow): svn: 'pre-commit' hook failed with error output: Traceback (most recent call last): (...) File ".../__init__.py", line 40, in run stderr = subprocess.STDOUT) File "/usr/local/lib/python2.4/subprocess.py", line 554, in __init__ errread, errwrite) File "/usr/local/lib/python2.4/subprocess.py", line 986, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory This is the child_traceback: File "/usr/local/lib/python2.4/subprocess.py", line 955, in _execute_child File "/usr/local/lib/python2.4/os.py", line 341, in execvp File "/usr/local/lib/python2.4/os.py", line 379, in _execvpe func(fullname, *argrest) OSError: [Errno 2] No such file or directory Is this a problem in subprocess (I'm using the FreeBSD port of Python-2.4 and subprocess that comes with that release) or is this expected? If my expectations are broken (likely), what should the standard descriptor massaging look like? Subversion code that runs the script can be seen at http://svn.collab.net/viewcvs/svn/trunk/subversion/libsvn_repos/hooks.c (run_hook_cmd()). -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- http://mail.python.org/mailman/listinfo/python-list
Re: Super Newbie Question
# [EMAIL PROTECTED] / 2005-04-04 16:39:27 -0700: > In short, how might I go about deleting just the contents of a file? > I tried several methods with my limited knowledge but had no luck. fd = open("your-file") fd.truncate() fd.close() or open("your-file", "w").close() -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- http://mail.python.org/mailman/listinfo/python-list
Re: email and smtplib modules
# [EMAIL PROTECTED] / 2005-04-09 16:42:04 -0500: > "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes: > > > Hi, > > > > I'm writing a small script that generates email and I've noticed that: > > > > 1) one should add the 'To' and 'CC' headers to the email message > > 2) one needs to specify the recipients in the smtplib sendmail() method > > > > Can someone explain how these are related? ... > This design makes many things possible. Most used these days is spam > delivered to one address while apparently to another. What about mailing lists? Quoting from your message as it arrived here: Return-Path: [EMAIL PROTECTED] X-Original-To: [EMAIL PROTECTED] From: Mike Meyer <[EMAIL PROTECTED]> To: python-list@python.org For the OP: Return-Path: header contains the envelope sender (SMTP MAIL command) X-Original-To: is the envelope recipient (SMTP RCPT command) So, despite the email claiming to be sent from Mike to the list, it's actually from the list to me. Please take Mike's note about spam with two grains of salt, the distinction between headers and envelope is vital to the SMTP protocol and many services built around it. -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- http://mail.python.org/mailman/listinfo/python-list
Re: Signals and system
# [EMAIL PROTECTED] / 2005-04-10 20:55:05 +1000: > Hi folks, > > My python program needs to download a number of files. Each file comes > as a list of mirrors of that file. > > Currently, I am using system (os.system) to run wget. The mechanism is > in a loop, so that it will try all the mirrors while wget is exiting > with a non-zero exit status. This is working fine as long as the user > feels there is no need to interrupt it. > > If wget receives a SIGINT, it stops (as expected) and returns non-zero > (1 from memory). The call to system returns the same status code, > indicating that wget failed, but the program has no knowledge that it > was a signal the killed wget, rather than a failed download, and as such > it tries the next mirror. I would like to be notified if wget received > any signals, so that the user doesn't need to repetitively press Ctrl-C > for each and every mirror to get the downloading process to stop. > > Can someone point me in the right direction? http://docs.python.org/lib/os-process.html#l2h-1682 "On Unix, the return value is the exit status of the process encoded in the format specified for wait()." http://docs.python.org/lib/os-process.html#l2h-1684 "return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced" -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- http://mail.python.org/mailman/listinfo/python-list
Re: semicolons
# [EMAIL PROTECTED] / 2005-04-12 00:14:03 +0200: >Hello, > > I amafraid of I will stop using semicolons in other languages after one > or two months of python. Writing in multiple programming languages is just like writing or speaking in multiple human languages: you just need to obey the rules of the different grammars and pronounciations. > However I see that python simply ignores the semicolons atd the end of > the lines. That's not true. > What's your advice? I don't want to write full-of-typo php scripts Then don't. > but I see the logic of the python syntax too. Different languages have different "logics". You need to stick to the right set of rules appropriate for the language you're using. -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- http://mail.python.org/mailman/listinfo/python-list
Re: [perl-python] Python documentation moronicities (continued)
# [EMAIL PROTECTED] / 2005-04-12 03:25:33 -0700: > QUOTE > compile( > pattern[, flags]) > > Compile a regular expression pattern into a regular expression object, > which can be used for matching using its match() and search() methods, > described below. > > The expression's behaviour can be modified by specifying a flags > value. Values can be any of the following variables, combined using > bitwise OR (the | operator). > UNQUOTE > And what the fuck is it unclearly meant by "OR" operator with the > mother fucking bitwise jargon? "bitwise OR (the | operator)": it doesn't speak about an "OR operator", does it? > for a exposition of IT's fucking stupid docs and their fuckhead coders, > see: > http://xahlee.org/Periodic_dosage_dir/t2/xlali_skami_cukta.html Interesting reading, I might send you a few of my pet peeves for inclusion. > you want to ask yourself this question: > Can a seasoned programer, who is expert at least 2 languages, who is > also a expert at Perl and knew regex well, and have just read the doc, > must he, resort to many trial and error to see exactly what the doc is > talking about? While I understand your frustration (I curse the same when I try to use the Python documentation), you are spoiling your message by the (IMNSHO well granted, but still) unhelpful profanity. Unfortunately, the python community seems to bathe in the misorganized half-documentation, see e. g. http://marc.theaimsgroup.com/?l=python-list&m=111303919606261&w=2 especially the reply that (as I read it) suggested reverse engineering as a viable alternative to documentation. -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- http://mail.python.org/mailman/listinfo/python-list
Re: Compute pi to base 12 using Python?
# [EMAIL PROTECTED] / 2005-04-13 03:27:06 -0700: > Bengt Richter wrote at 03:19 4/13/2005: > This is not homework, nor am I a student, though I am trying to learn > Python. I'm just trying to help an artist acquaintance who needs (I just > learned) the first 3003 digits of pi to the base 12. > > >Hint: Lambert Meertens. Tweak the algorithm you find ;-) > > Sorry. Your hint is beyond me. it says "use google". -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- http://mail.python.org/mailman/listinfo/python-list
Freezing python application
Hi. I would like to freeze python application on linux. There are a few tools that make the job to be done: freeze ( comes with python ) cx_Freeze Gordon McMillan's installer Is it possible to freeze python application on linux in such way that it doesn't depends on python installed on cu -- http://mail.python.org/mailman/listinfo/python-list
Re: Freezing python application
Sorry for previous post - hit the wrong button Hi. I would like to freeze python application on linux. There are a few tools that make the job to be done: freeze ( comes with python ) cx_Freeze Gordon McMillan's installer I have one problem with all of them: they require python to be installed on target machine. May be I missed something or did not understand right the docs? Also if I am right could you point me to "freeze" tool that doesn't require python installed on customer computer? For windows I have py2exe. What should I use for linux to get same affect? Thanks Roman -- http://mail.python.org/mailman/listinfo/python-list
Re: A little request about spam
# [EMAIL PROTECTED] / 2005-04-14 08:22:48 -0600: > The listowner could turn on the [PYTHON] headers. I hope they don't. > I'm not using spambayes yet, although I'm leaning toward it, but that > step alone could save me some work when trying to decide based on > subject line alone whether or not an email is spam. As it stands now, > it's too easy to decide incorrectly that "Subject: Inelegant" is a > spamdunk. Don't base your decisions (only) on subject then. Oh, and spam sent through the list would have the [PYTHON] space eater too, so what would it buy you? -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- http://mail.python.org/mailman/listinfo/python-list
Re: A little request about spam
# [EMAIL PROTECTED] / 2005-04-14 09:06:08 -0600: > Roman Neuhauser wrote: > > > > # [EMAIL PROTECTED] / 2005-04-14 08:22:48 -0600: > > > The listowner could turn on the [PYTHON] headers. > > > > I hope they don't. > > > > What's your reasoning? It's 9 characters ("[PYTHON] ") of screen real estate wasted. Of course it's mail from the python-list, it has the appropriate List-Id header! > > > As it stands now, it's too easy to decide incorrectly that > > > "Subject: Inelegant" is a spamdunk. > > > > Don't base your decisions (only) on subject then. Oh, and spam sent > > through the list would have the [PYTHON] space eater too, so what > > would it buy you? > > Of course I wouldn't base decisions _only_ on whether or not [PYTHON] > appears in the subject. But I ordinarily do base decisions on the whole > subject line, and I think that's perfectly reasonable. There's nothing > else to go on without opening the message, and for HTML-based mail > there's no surer way to let spammers know they've found a live email > addres than to open it. You know that. I have no problem opening HTML emails: I (intentionally) don't have a viewer for them configured in mutt which means I see their source. And I delete them all without reading. For Content-Type: multipart/alternative emails, the text/plain part is displayed, and I mostly don't even get to notice there's a html part. If the text/plain part says something hilarious, like "This is a MIME email, get a better email client" which I've seen in a spam, I get to laugh as well. -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- http://mail.python.org/mailman/listinfo/python-list
Re: [perl-python] Python documentation moronicities (continued)
# [EMAIL PROTECTED] / 2005-04-13 08:07:06 +1000: > On Tue, 12 Apr 2005 13:06:36 +0200, Roman Neuhauser > <[EMAIL PROTECTED]> wrote: > > >Unfortunately, the python community seems to bathe in the > >misorganized half-documentation, see e. g. > >http://marc.theaimsgroup.com/?l=python-list&m=111303919606261&w=2 > >especially the reply that (as I read it) suggested reverse > >engineering as a viable alternative to documentation. > > As I read the reply, it was a smart-arse attempt at humour, a *PUN* on > the word "list" (mailing list versus Python list). What I would call > "introspection" (not "reverse engineering") was then suggested. > > Moreover, both of the concepts mentioned in the quoted thread > (sequence.index() and the "in" operator) are IMESHO adequately > documented. > > Do you have any examples of what you regard as "misorganized > half-documentation"? Description of classes: * What's with "Programmer's Note", is the other paragraph of the description aimed at salesmen? * Why isn't there a link to a description of "new-style classes" (presumably to the "New-style Classes" essay since, as http://www.python.org/doc/newstyle.html says, NSC aren't integrated into the standard documentation. * Aren't class objects instances of a builtin type? What should I read into ""? distutils: * sections 10.26 through 10.45 are completely empty * http://docs.python.org/dist/listing-packages.html: "when you say packages = ['foo'] in your setup script" couldn't be any more vague I guess. Does the statement belong in the global scope? * http://docs.python.org/dist/listing-packages.html: "Then you would put package_dir = {'': 'lib'} in your setup script.": does that statement belong in the global scope, or is it a keyword argument for setup(), which would mean that the listing at http://docs.python.org/dist/module-distutils.core.html cannot be trusted as complete? lists: this is a matter of taste, but I find the split of list description between http://docs.python.org/lib/typesseq.html and http://docs.python.org/lib/typesseq-mutable.html (without pointers from typesseq.html to typesseq-mutable.html where I would expect them, such as mentioning append()) confusing. The above applies to other mutable sequential types as well, of course. In general, various parts of the documentation often refer the reader to other parts without using html anchors, what should be concise, accurate, and complete description is a meandering essay with vague formulations (see quotes from the distutils manual above), etc. There's also this thing with easy access to individual nodes: I often miss being able to type something like http://docs.python.org/os.path.expanduser and be redirected to http://docs.python.org/lib/module-os.path.html#l2h-1731 Mebbe it's just me, but I've been trying python on and off for several years now, and it's always been precisely its documentation that has made me back out. I know I'll get to know the language quite well some time, but it'll be through scars, and I'll have many f*cks behind me. > Here's a puzzle for you: Where does this list appear? What's missing? > > "..., Mullender, Nagata, Ng, Oner, Oppelstrup, ..." Sorry, I don't have time for puzzles. -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- http://mail.python.org/mailman/listinfo/python-list
Re: [perl-python] Python documentation moronicities (continued)
# [EMAIL PROTECTED] / 2005-04-17 14:59:50 +0200: > Roman Neuhauser wrote: > > >>Here's a puzzle for you: Where does this list appear? What's missing? > >> > >>"..., Mullender, Nagata, Ng, Oner, Oppelstrup, ..." > > > > Sorry, I don't have time for puzzles. > > nor for contributing, it seems. otherwise, your name would be on that list. Right. There's a finite number of hours in a day, and I chose to spend most of it on FreeBSD, and my name is on that operating system's contributor list. You're welcome to use the results of the work. But anyway, I was honestly asked about what I considered suboptimal in the python documentation, and I honestly answered. Does that bother you? -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- http://mail.python.org/mailman/listinfo/python-list
Re: To decode the Subject =?iso-8859-2?Q?=... in email in python
# [EMAIL PROTECTED] / 2005-04-20 00:30:35 -0700: > When parsing messages using python's libraries email and mailbox, the > subject is often encoded using some kind of = notation. Apparently, the > encoding used in this notation is specified like =?iso-8859-2?Q?=... or > =?iso-8859-2?B?=. That's RFC 2047 encoding, both examples introduce an ISO8859-2 string, the first variant says it's ascii-ized using "Q"uoted-Printable, the other says the string is "B"ase64-encoded. > Is there a python library function to decode such a > subject, returning a unicode string? The use would be like > > human_readable = cool_library.decode_equals(message['Subject']) quoting from http://docs.python.org/lib/module-email.Header.html >>> from email.Header import decode_header >>> decode_header('=?iso-8859-1?q?p=F6stal?=') [('p\xf6stal', 'iso-8859-1')] -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- http://mail.python.org/mailman/listinfo/python-list
Re: Noobie Question: Using strings and paths in mkdir (os.mkdir("/test/"a))
# [EMAIL PROTECTED] / 2005-04-22 00:13:05 -0700: > Hello! > > I can't seem to get paths and variables working together: > > import os > a = 'books' > os.chdir( '/test') > os.mkdir("/test/"a) > > the last line does not seem to work. os.mkdir(a) makes the directory > books, but i want this directory as a subdirectory of test. > > I also tried: os.mkdir("/test/",a), and trying to make b = 'test' and > then os.mkdir(a b). > > Does someone have any ideas or a link they can give me, I looked under > strings in the python tutorial and library manual but I guess not in > the right spot. http://docs.python.org/ref/string-catenation.html -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- http://mail.python.org/mailman/listinfo/python-list
Re: regarding system function
# [EMAIL PROTECTED] / 2005-04-22 08:35:33 +0100: > > --- Robert Kern <[EMAIL PROTECTED]> wrote: > > praba kar wrote: > > > In Php If I send a command to system function > > > then It will return 1 on success and 0 on failure. > > > So based upon that value I can to further work. > > > > > > But In Python If I send a command to system > > > function then It will return 0 only for both > > > conditions(success and failure). > > > > Are you sure about that? > > > > In [3]:os.system('cat foo') > > cat: foo: No such file or directory > > Out[3]:256 > > > > I agree above statement but When I delete a directory > os.system('rm -rf test') > 0 > if directory is not present then I again try to > delete > os.system('rm -rf test') > now this time also It will print > 0 that's the standard behavior of the -f switch -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python or PHP?
# [EMAIL PROTECTED] / 2005-04-23 15:53:17 +0200: > Lad wrote: > > >Is anyone capable of providing Python advantages over PHP if there are > >any? > > I am also new to python but I use php for 4 years. I can tell: > > - python is more *pythonic* than php > - python has its own perfume > http://www.1976.com.tw/image/trussardi_python_uomo.jpg and it's nice. > php doesn't have any smell > - writing python programs you feel much better No, *you* feel better. :) > check this: http://wiki.w4py.org/pythonvsphp.html The comparison found there is biased, the author is a Python partisan. -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- http://mail.python.org/mailman/listinfo/python-list
[Announce] pydsc
Hi, I would like to announce new module - pydsc. pydsc is Python documentation spell checker. This modules checks documentation string and comments for spelling errors. pydsc uses PyEnchant (http://pyenchant.sourceforge.net/) as spell checking engine. Example of usage: import pydsc #all modules that will be imported from now will be checked import readline More complex example ( taken from pygccxml project ): import pydsc #test only pygccxm package for spelling errors #package_directory defined earlier pydsc.doc_checker.filter.append( package_directory ) pydsc.doc_checker.filter_type = pydsc.FILTER_TYPE.INCLUDE #ignore next words map( pydsc.doc_checker.speller.ignore_always , [ 'org', 'http', 'bool', 'str', 'www', 'param' , 'txt', 'decl', 'decls' ] ) pydsc is released under Boost Software License( http://boost.org/more/license_info.html ) You can download it from here: http://sourceforge.net/project/showfiles.php?group_id=118209 Pay attention: before installing pydsc you need to install PyEnchant (http://pyenchant.sourceforge.net/). Ideas, comments, suggestions or help are welcomed. Best regards, Roman Yakovenko -- http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
Tim Hochberg wrote: > py pan wrote: > >>When you guys say 127~150 characters, did you guys mean >>usinging test_vectors.py in some way? Or there's no import at all? >> > > > No import at all. The shortest solution reported so far is 131 > characters. Getting down to 127 is just a guess as to where the lower > bound is likely to be. > > Note that in principle it's possible to encode the data for how to > display a digit in one byte. Thus it's at least theoretically possible > to condense all of the information about the string into a string that's > 10 bytes long. In practice it turns out to be hard to do that, since a > 10 byte string will generally have a representation that is longer than > 10 bytes because of the way the escape sequences get printed out. As a > result various people seem to be encoding the data in long integers of > one sort or another. The data is then extracted using some recipe > involving shifts and &s. > > -tim Condensing is good but only as far as code for decompressing is small... By the way, after I noticed that I program for 2.3, I tried with 2.4 and get out extra characters thanks for generator expression and .join() integration. So now I am at 147. Probably a lot of reserve as I have 3 fors... One for just for the purpose of getting a name: ...x for x in [scalar] Probably its time rething solution from scratch... Roman Susi -- http://mail.python.org/mailman/listinfo/python-list