Re: Pickled objects over the network
Hendrik van Rooyen ha scritto: > But more seriously - is there any need for a simple serialiser that will > be able to be used to transfer a subset of the built in types over an > open network in a safe manner, for the transfer of things like lists of > parameters? Yes, there seems to be a need for XML/YAML/JSON :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Haskell like (c:cs) syntax
Ricardo Aráoz ha scritto: > L = ['one', 'two', 'three', 'four', 'five'] > > print L[0]# This would be 'head' > print L[1:] # This would be 'tail' > > Caution : L[0] and L[1:] are COPIES of the head and tail of the list. This might surprise people who see L[1:] = [], since changing a copy is not supposed to change the original. -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
Py-Fun wrote: > I'm stuck trying to write a function that generates a factorial of a > number using iteration and not recursion. Any simple ideas would be > appreciated. As opposed to what, a complicated one? -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
Py-Fun wrote: > def itforfact(n): > while n<100: > print n > n+1 > n = input("Please enter a number below 100") You function should probably return something. After that, you can see what happens with the result you get. -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
From the cookbook, this time. It satisfies the requirements nicely ;) http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 def tail_recursion(g): ''' Version of tail_recursion decorator using no stack-frame inspection. ''' loc_vars ={"in_loop":False,"cnt":0} def result(*args, **kwd): loc_vars["cnt"]+=1 if not loc_vars["in_loop"]: loc_vars["in_loop"] = True while 1: tc = g(*args,**kwd) try: qual, args, kwd = tc if qual == 'continue': continue except (TypeError, ValueError): loc_vars["in_loop"] = False return tc else: if loc_vars["cnt"]%2==0: return ('continue',args, kwd) else: return g(*args,**kwd) return result @tail_recursion def factorial(n, acc=1): "calculate a factorial" if n == 0: return acc res = factorial(n-1, n*acc) return res -- http://mail.python.org/mailman/listinfo/python-list
Re: Check File Change Every 10 Seconds
Robert Rawlins - Think Blue wrote: > That certainly looks to be the type of thing that I'm looking to achieve, > however, I forgot to mention I'm running this on a Linux platform and not a > Win32 one :-( Sorry. Did you try python-gamin? "Gamin is a file and directory monitoring system defined to be a subset of the FAM (File Alteration Monitor) system." -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
Tim Golden wrote: >> From the cookbook, this time. >> It satisfies the requirements nicely ;) >> >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 > > [... snip the ultimate general-purpose answer to the OP's question ... > > I really hope that's a wink up there, Marco. The wink is in the second line of my post... more for the "do the least amount of work to meet the requirements" people that for the OP > The poor guy was just trying to get his homework done! I don't see how my answer is in any way worse than those based on lambda. Maybe I'm just envious because when I was his age I couldn't google for answers. He should at least be able to do that, shouldn't he? But wait. That would mean understanding what a factorial is. That would require a second search, or a textbook, or an understanding of arithmetics before programming with or without recursion. Should we blame the teachers? -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
Tim Chase wrote: fact = lambda i: i > 1 and reduce(mul, xrange(1, i+1)) or not > i and 1 or None > > Stunts like this would get a person fired around here if they > were found in production code :) eheh, indeed. def fact(n): try: return eval('*'.join(str(x) for x in range(1,n+1))) except: return 1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
Roberto Bonvallet wrote: > import urllib > import re > urllib.URLopener.version = "Mozilla/4.0" > > def fact(x): > r = re.compile(r"%d ! = (\d+)" % x) > for line in urllib.urlopen("http://www.google.cl/search?q=%d%%21"; % x): > m = r.search(line) > if m: > return int(m.group(1)) You solution reminds me the web-based WTF calculator. http://worsethanfailure.com/Articles/OMGWTF-Finalist-05-WTF-Web-Calc.aspx -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
[EMAIL PROTECTED] wrote: > Needs work. Uh... ok.. this one gives an exception ;-) def fact(n): try: return eval('*'.join(str(x) for x in range(1,n+1))) except: return n>=0 or ValueError print fact(-1) -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
[EMAIL PROTECTED] wrote: > class fact_0(object): > value = 1 [... > def __new__(self, n_): > class spanish_inquisition(object): > __metaclass__ = fact_meta > n = n_ > return spanish_inquisition() You wrote lots of boilerplate to hide the fact you're cheating, didn't you? The OP explicitly asked for an iterative procedure. btw... writing a test unit to check the tested code is not calling itself.. could be interesting -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
Nick Craig-Wood wrote: > Note you can write your middle loop as > > for i in range(I): > number = myNumer[:] > random.shuffle(number) > if number == myNumer: > count+=1 Nice. Try 'em all, then count 'em. Another wtfery would be a SQLAlchemy solution, generating dynamic queries, using only OUTER JOINs and COUNT(). Could be a way to justify hardware upgrades. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonic ORM with support for composite primary/foreign keys?
Wolfgang Keller wrote: > so far it seems to me as if the only ORM module for Python which > supports composite primary/foreign keys was SQLAlchemy. Which looks a > little bit "overbloated" for my needs: I "just" need to be able to > define a "logical model" (à la UML) in Python and have the ORM connect > to a database (running on PostgreSQL in my case) which uses a > corresponding (pre-defined) "physical model" as its schema. I think if your model is complex enough that you need composite foreign keys, the project might deserve SQLAlchemy. Mapping a bunch of python classes to an efficient DBMS schema is not easy by any definition of "easy". Google for "orm vietnam"... it might also be useful to read "The Art of SQL" even if you don't plan to write SQL by hand. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is anyone happy with csv module?
John Machin wrote: > For that purpose, CSV files are the utter pox and then some. Consider > using xlrd and xlwt (nee pyexcelerator) to read (resp. write) XLS > files directly. xlwt is unreleased (though quite stable, they say) at the moment, so the links are: easy_install xlrd svn co https://secure.simplistix.co.uk/svn/xlwt/trunk -- http://mail.python.org/mailman/listinfo/python-list
Re: Is anyone happy with csv module?
massimo s. wrote: > As for people advicing xlrd/xlrwt: thanks for the useful tip, I didn't > know about it and looks cool, but in this case no way I'm throwing > another dependency to the poor users of my software. Csv module was > good because was built-in. The trouble with sending CSV files to Excel (or OpenOffice, or Gnumeric, or whatever) is that there is no way to specify the data types. Unless you're using a predefined worksheet (and refreshing its data from the CSV file) the spreadsheet program _won't_ get the data types right. Strings will become numbers (and stripped of precious leading zeroes), dates may (or may not) become floats or something entirely different. Fixed point decimals might grow eyes and bite you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python really a scripting language?
Bruno Desthuilliers wrote: > As far as I'm concerned, anyone (I mean, anyone pretending to be a > programmer) being ignorant enough to ask such a question ranks high in > my bozo list. Don't waste time with bozos. Alan Kay said it well enough without using words like "pretending", "ignorant" and "bozo" :) http://acmqueue.com/modules.php?name=Content&pa=showpage&pid=273 It's worth a read. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie observations
[EMAIL PROTECTED] wrote: > 10 days is not enough. But I don't have any more clarity in my Python > classes than I did in Java. You do when you start using classes the python way, and do things that are not even thinkable in java or any static language. -- http://mail.python.org/mailman/listinfo/python-list
Re: Double underscores -- ugly?
Ben Finney wrote: >> I realise that double underscores make the language conceptually >> cleaner in many ways (because fancy syntax and operator overloading >> are just handled by methods), but they don't *look* nice. > > That's a good thing, in that it draws attention to the names. Well, double underscore is awful when you have to read code with the wrong typeface, possibly printed. -- http://mail.python.org/mailman/listinfo/python-list
Re: The big shots
Sergio Correia wrote: > I don't get this thread. At all. I want my 15 minutes back. I think it's a sort of Turing test, to fine-tune some spammer's text generating algorithm. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a file with $SIZE
Robert Bossy wrote: > Indeed! Maybe the best choice for chunksize would be the file's buffer > size... I won't search the doc how to get the file's buffer size because > I'm too cool to use that function and prefer the seek() option since > it's lighning fast regardless the size of the file and it takes near to > zero memory. And makes a hole in the file, I suppose, hence the fragmentation. The OP explicitly asked for an uncompressed file. -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb LIKE '%%%s%%' problem
Steve Holden wrote: 3. I can't be certain my experience with PostgreSQL extends to MySQl, but I have done experiments which prove to my satisfaction that it isn't possible to parameterize LIKE arguments. So the only way to do it appears to be to build the query yourself. Or using Postgres through SQLAlchemy. Actually, the only thing SQLAlchemy cannot do (yet) is withstand a zombie army. -- http://mail.python.org/mailman/listinfo/python-list
Re: English-like Python
The Music Guy wrote: Just out of curiousity, have there been any attempts to make a version of Python that looks like actual English text? Many have tried that in the decades, but IMHO the best approach is to just rename the language. We cannot do that since it's already been trademarked for that very reason. From Wikipedia: ENGLISH (actually trademarked in all caps) is a database retrieval and reporting language somewhat like SQL, but with no actual programming or update capabilities. Originally released by Microdata in 1973 and named so that the company's brochures could claim that developers could generate reports on their implementation of the Pick operating system using English. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get first/last day of the previous month?
Hussein B wrote: I'm creating a report that is supposed to harvest the data for the previous month. So I need a way to get the first day and the last day of the previous month. Would you please tell me how to do this? Thanks in advance. dateutil can do this and much, much more. >>> from datetime import date >>> from dateutil.relativedelta import relativedelta >>> today = date.today() >>> d = today - relativedelta(months=1) >>> date(d.year, d.month, 1) datetime.date(2008, 12, 1) >>> date(today.year, today.month, 1) - relativedelta(days=1) datetime.date(2008, 12, 31) >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get first/last day of the previous month?
Carsten Haese wrote: In order to not deprive you of the sense of accomplishment Sorry for spoiling that. If you still want the sense of accomplishment, try to reimplement dateutil (and rrule). It's not as easy as it seems :-o -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get first/last day of the previous month?
Carsten Haese wrote: dateutil can do this and much, much more. Using dateutil for this is like using a sledgehammer to kill a fly. The task at hand can (and IMHO should) be solved with the standard datetime module. Sure, but many python programmers are not even aware of the existence of that particular sledgehammer, it deserved to be mentioned. It should be part of the standard library I think. -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing modules
Mudcat wrote: This is something I've wondered about for a while. I know that theoretically Python is supposed to auto-recognize duplicate imports; however I've run into problems in the past if I didn't arrange the imports in a certain way across multiple files. I think you've probably had issues with circular imports (i.e. mutual dependencies), unless you can precisely remember what you were doing and what went wrong. As a result, I worry about conflicts that arise because something has been imported twice. So...I'm not sure if Python *always* gets this correct. It doesn't import twice, and never did. Also, I understand what you're saying about the organization of files based on modules and maybe regrouping based on use. However I like the organization of my files to be a grouping of logical components in my application. I can make up three or four different logical groupings in my applications... so what is 'logical' could not be the same for everyone, or from every point of view. -- http://mail.python.org/mailman/listinfo/python-list
Re: ORM recommendation when using "live"/predefined DB?
Phillip B Oldham wrote: Can you recommend an ORM (or similar) package to look into? SQLAlchemy with reflected tables. You can use straight SQL, generate it dynamically via python expressions, go with the ORM, or everything together (in a bucket :) It really pays due respect to the RDBMS, and does not try to avoid the OO-SQL gap. -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
Thorsten Kampe wrote: This scenario is highly "supposing" and doesn't look like a real-world- case to me. But anyway: the obvious solution in my humble opinion would be to do something like "public_attribute = _private_attribute". But that would be too simple, too "unjavaesque", right?! Yes, the use of @property is.. cheating!! Shame on you! :) -- http://mail.python.org/mailman/listinfo/python-list
Re: what IDE is the best to write python?
Russ P. wrote: highlighting. Not that it really helps much, but it "spices up" the code and stimulates the eyes and brain. When I see the same code without color highlighting, it just seems bland, like something is missing. It seems like just "text" rather than "code." Plus, it can be configured to induce seizures when the programmer tries to write private methods ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: len()
Pat wrote: Why didn't you answer the len() question? It's a bit of a FAQ: len() cannot be a method of list objects because it works on any sequence or iterable. -- http://mail.python.org/mailman/listinfo/python-list
Re: A little bit else I would like to discuss
azrael wrote: I know that there is already a standard python library, But why not extending it. classify the standard library into subcategories like Networking, DataBase, Computation, .. If the standard library where that huge, python 3.0 would have been late by a couple of years. Why not using this number of people and accomplish something great. If anyone of us would write 10 line of good code, it would result a very great and powerfull environment. I totally want to write my 10 lines of great image processing or speech recognition software, but it's not how development works. -- http://mail.python.org/mailman/listinfo/python-list
Re: best set of modules for web automation without javascript
News123 wrote: I would just like to retrieve all the field names and default values of a form. (Some forms are huge) and wondered thus whether there's already a python module parsing a html documents for forms , form fields and field vaules, returning an objcet. that could be modified and posted. http://wwwsearch.sourceforge.net/ClientForm/ http://wwwsearch.sourceforge.net/mechanize/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python surpasses Perl in popularity?
Steve Holden wrote: In fact all that's really happened is that Perl has slid down the ranks, at least temporarily. Python has been around the 6/7 mark for a while now. Also.. can someone attempt to explain the funny correlation in popularity over time between, for instance, Python and Delphi? :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonic design patterns
George Sakkis wrote: This is all very good, but don't drink the design pattern Kool-Aid and start pushing design patterns everywhere. (Not everything needs to be a singleton. No, really.) Obligatory reading: http://www.mortendahl.dk/thoughts/blog/view.aspx?id=122 By the way, it's a fact that many low-level patterns, as they are described, are useful mainly/only in statically typed languages. The ones in PEAA, for instance, are high-level enough to be useful in any environment. http://www.amazon.com/Enterprise-Application-Architecture-Addison-Wesley-Signature/dp/0321127420 -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't you just love writing this sort of thing :)
Steven D'Aprano wrote: Gosh Lawrence, do tell, which category do YOU fall into? I suppose a mix-up between a cowbody (or Fonzie) coder and a troll. His programs have an inner poetry that we're obviously too stupid to understand. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
Giampaolo Rodola' wrote: The real (and still unsolved) problem with PyPy is the installation which requires something like a dozen of third-party packages to be installed. Unfortunately it seems there are no plans yet for releasing any Windows/Linux/Mac installer in the near future. I'm not using it, but at least Ubuntu 8.10 has the .deb packages of pypy 1.0. And I remember installing a release last year in a few minutes, during a conference talk. -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing None objects from a sequence
Filip Gruszczyński wrote: I am not doing it, because I need it. I can as well use "if not elem is None", I suggest "if elem is not None", which is not quite the same. If you slip such an error in a post, I suggest to practice some time writing correct code before having one-liner contests with your perl-loving friends :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing None objects from a sequence
Kirk Strauser wrote: So what's the difference exactly? "foo is not None" is actually surprising to me, since "not None" is True. "0 is True" is False, but "0 is not None" is True. Why is that? Cause I was tired of course, and got the not precedente not right!! Argh -- http://mail.python.org/mailman/listinfo/python-list
Re: Selecting a different superclass
psaff...@googlemail.com wrote: The problem is that IDPointSet and MicroArrayPointSet will need to inherit from PointSet or TraceablePointSet based on whether I'm handling traceable points or not. Can I select a superclass conditionally like this in Python? Am I trying to do something really evil here? Any other bright ideas on my application also welcome. I think you should investigate something different than subclassing, like a "Strategy" domain pattern or something similar. -- http://mail.python.org/mailman/listinfo/python-list
Re: Selecting a different superclass
Marco Mariani wrote: I think you should investigate something different than subclassing, like a "Strategy" domain pattern or something similar. s/domain/design/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's popularity
walterbyrd wrote: I have read that python is the world's 3rd most popular language, and that python has surpassed perl in popularity, but I am not seeing it. In 20 days, you've gone from trying to import a module by using: > load "test.py" to questioning the popularity of python. You have many other subject you want to enlighten us about, I suppose? Cause I wonder what you'll come up with, next. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's popularity
Richard Riley wrote: One does not have to by a language maestro to try and assess its popularity. While his numbers or his reading of the numbers might be open to some questions, to suggest that one needs to be totally familiar with a language to determine its popularity is, frankly, ridiculous. I was not judging his competency. But when I am naive on a subject, I don't usually show off like that. The polemic intents in his previous messages are quite clear (python is slow, py3k is an utter failure because it doesn't solve the whitespace issue, etc), and this thread is not different. It seems like a rehash of issues that have been dragged around here by generations of trolls for the last 10 years. Sorry for adding noise to the signal :-/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Line completion with custom commands
gu wrote: I see, but how does django-admin work, then? from bash: complete -W "doSomething doSomethingElse doSomethingDifferent" myProgram -- http://mail.python.org/mailman/listinfo/python-list
Re: "Battleship" style game
Shawn Milochik wrote: > I'm not claiming it's bulletproof, but it works. I just kind of came up with all the methods off of the top of my head, so if anyone has any suggestions for more elegant or efficient code, please let me know. Yes it's in Python alright, but it's not Pythonese yet. You could try avoiding the getter/setter stuff, and camelCase method naming, things like that, for a start. -- http://mail.python.org/mailman/listinfo/python-list
Re: monitoring/restarting an application
Ghirai wrote: I need to keep x number of instances of an external applications running, say /bin/x, but also kill and restart each one after y seconds. What would be the best way to do this (with python 2.5.x)? easy_install supervisor it should do everything for you -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about binary file reading
vibgyorbits wrote: l=map(lambda x: '%02x' %ord(x),d) s=string.join(l,sep='') PS#. Endedup learning little bit of Lambda functions. :-) That's so 2007... The 2.5-esque way to write that is s = ''.join('%02x' % ord(x) for x in d) -- http://mail.python.org/mailman/listinfo/python-list
Re: While loop
Fab86 wrote: Is it possible to get the program to catch the exception, wait 10 seconds, then carry of from where it was rather than starting again? something like this? probably works in PASCAL as well :) i=0 while i < len(stuff): try: do_with(stuff[i]) except SomeError: sleep(10) continue i+=1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Indentations and future evolution of languages
Steven D'Aprano wrote: You can have one, or the other, but not both, unless you're willing to have a "practicality beats purity" trade-off and create a second way of grouping blocks, I propose /* and */ as block delimiters. There, you have auto-documenting code, ahah! -- http://mail.python.org/mailman/listinfo/python-list
Re: Can Python do shopping cart?
Lie Ryan wrote: Python is Turing Complete Well, actually no, because it doesn't support an infinite amount of memory. Add this to "things to check before wasting a lot of money in hardware". -- http://mail.python.org/mailman/listinfo/python-list
Re: Can Python do shopping cart?
Tim Wintle wrote: Python is Turing Complete Well, actually no, because it doesn't support an infinite amount of memory. Surely you can address an infinite amount of storage using infinite length integers and a wrapper to files on disk - then it's just your OS's limits that hold it back - so python is turing/register complete. Oh, but you would eventually need to pass those integers around somewhere in RAM. Even counting (referencing) an infinite amount of items leads to infinitely long indexes. And counting the indexes as well. But I propose to stop here, we're way off-topic and I have to write a shopping cart application in Malbolge. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python worth learning as a second language?
ZikO wrote: Do you think python would be good complementary language for C++? Do you think it's worth learning it Absolutely, but it tends to become the first language over time. Don't underestimate its reach. I've re-learned Python 3 or 4 times already, over 11 years :-/ -- http://mail.python.org/mailman/listinfo/python-list
Re: A better way to timeout a class method?
John O'Hagan wrote: Is there a concise Pythonic way to write a method with a timeout? No need for threading. Just define a signal handler and call signal.alarm(). See the example at the end of the page: http://docs.python.org/library/signal.html -- http://mail.python.org/mailman/listinfo/python-list
Re: functions - where to store them
plsulliv...@gmail.com wrote: I have several functions which I would like to store in a different directory so several programs can use them. I can't seem to find much information about how to call a function if the function code is not actually in the script itself. read the tutorial, look for "modules" and "packages" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python + PostgreSQL
Lobo wrote: I now have a new project to develop web applications using the latest/ best possible versions of Python (3.x?) with PostgreSQL (8.x?, with pgAdmin 1.10?). You want to use Python 2.5.x (or 2.6 if your framework of choice already supports it), Postgres 8.3 and have a look at SQLAlchemy (please do). As for the framework of choice, "it depends" :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating 50K text files in python
venutaurus...@gmail.com wrote: for k in range (1,1001): ... k = k+1 Man, you have a trouble with loops, all over. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating 50K text files in python
venutaurus...@gmail.com wrote: for k in range (1,1001): ... k = k+1 Man, you have a trouble with loops, all over. But the situation demands it.:-( No. I mean, the for loops are wrong. Compare with the following and see why import os base = '/tmp/foo' for outer in xrange(1,6): for inner in xrange(1,11): d = os.path.join(base, str(outer), str(inner)) os.makedirs(d) for fnum in xrange(1,1001): file(os.path.join(d,str(fnum)), 'w').close() -- http://mail.python.org/mailman/listinfo/python-list
Re: Style formating of multiline query, advise
someone wrote: Also, for SQL, (A) why are you using nested joins?, and inner select produce smaller set which is then joined with other table, kind a optimization Did you time it? I've done some "kind of a optimization" that slowed queries by tenfold, because postgres didn't need my advice, and knew better. RDBMS performance is non-intuitive, really. If you're using mysql, YMMV, because its optimizer is not as good. Yes, my original question was about formatting. It's not original query (only a part). Try this: http://www.dpriver.com/pp/sqlformat.htm My 2c: I use textwrap.dedent to strip leading spaces from every line. -- http://mail.python.org/mailman/listinfo/python-list
Re: Use of HTMLparser to change language
pranav wrote: I am sure there is a python way of solving this problem. The common sense approach (nothing to do with python) would be to rewrite everything to be dynamically generated with a template language - in python those would be TAL, mako, genshi, jinja, whatever ... anything is better than the current solution. -- http://mail.python.org/mailman/listinfo/python-list
Re: Use of HTMLparser to change language
pranav wrote: I am sure there is a python way of solving this problem. The common sense approach (nothing to do with python) would be to rewrite everything to be dynamically generated with a template language - in python those would be TAL, mako, genshi, jinja, whatever ... anything is better than the current solution. Hmm ya, that is THE best thing, if this were an application. These are plain HTML files and needs to be shipped with CDs. So what? Template engines are perfectly able to generate files instead of sending them off the net. Also, it is not in the design to use anything executable. Do you mean "put executable in the CDs", but I'm not proposing that. Anyway, I would probably start by looping all of the files with 'tidy' - to have the same formatting and hopefully attribute order, examining a few them with something like 'vimdiff' and see if I could come up with some rules to implement with BeautifulSoup. False positives (i.e. files that should be equal but aren't) are ok because they can give new rules to implement. With the same retro-engineered rules I could create the templates from the static files. -- http://mail.python.org/mailman/listinfo/python-list
Re: Introducing Python to others
Paddy O'Loughlin wrote: All of the audience will be experienced (4+ years) programmers, almost all of them are PHP developers (2 others, plus myself, work in C, know C#, perl, java, etc.). Show them the same classical design patterns in Java and Python. Explain how it's much more flexible. Any other suggestions for a possible "wow" reaction from an audience like that? SQLAlchemy / SQLSoup, and XML handling with lxml. -- http://mail.python.org/mailman/listinfo/python-list
Re: difflib and intelligent file differences
hayes.ty...@gmail.com wrote: My first thought is to do a sweep, where the first sweep takes one line from f1, travels f2, if found, deletes it from a tmp version of f2, and then on to the second line, and so on. If not found, it writes to a file. At the end, if there are also lines still in f1 that never were matched because it was longer, it appends those as well to the difference file. At the end, you have a nice summary of the lines (i.e., records) which are not found in either file. Any suggestions where to start? You can adapt and use this, provided the files are already sorted. Memory usage scales linearly with the size of the file difference, and time scales linearly with file sizes. #!/usr/bin/env python import sys def run(fname_a, fname_b): filea = file(fname_a) fileb = file(fname_b) a_lines = set() b_lines = set() while True: a = filea.readline() b = fileb.readline() if not (a or b): break if a == b: continue if a in b_lines: b_lines.remove(a) elif a: a_lines.add(a) if b in a_lines: a_lines.remove(b) elif b: b_lines.add(b) for line in a_lines: print line if a_lines or b_lines: print '' print '***' print '' for line in b_lines: print line if __name__ == '__main__': run(sys.argv[1], sys.argv[2]) -- http://mail.python.org/mailman/listinfo/python-list
Re: difflib and intelligent file differences
Marco Mariani wrote: while True: a = filea.readline() b = fileb.readline() if not (a or b): break BTW, watch out for this break. It might not be what you want :-/ -- http://mail.python.org/mailman/listinfo/python-list
Re: difflib and intelligent file differences
Dave Angel wrote: If the lines are really sorted, all you really need is a merge, D'oh. Right. The posted code works on unsorted files. The sorted case is even simpler as you pointed out. -- http://mail.python.org/mailman/listinfo/python-list
Re: difflib and intelligent file differences
Marco Mariani wrote: If the lines are really sorted, all you really need is a merge, For the archives, and for huge files where /usr/bin/diff or difflib are not appropriate, here it is. #!/usr/bin/env python import sys def run(filea, fileb): p = 3 while True: if p&1: a = filea.readline() if p&2: b = fileb.readline() if not a or not b: break elif a == b: p = 3 elif a < b: sys.stdout.write('-%s' % a) p = 1 elif b < a: sys.stdout.write('+%s' % b) p = 2 for line in filea.readlines(): sys.stdout.write('-%s' % line) for line in fileb.readlines(): sys.stdout.write('+%s' % line) if __name__ == '__main__': run(file(sys.argv[1]), file(sys.argv[2])) -- http://mail.python.org/mailman/listinfo/python-list
Re: script question
Piet van Oostrum wrote: funclist = [func01, func02, func03, ... ] for i in range(1,n): funclist[i]() Or myscript.funclist[i]() from another module. Ehm, calling a bazillion things in the right order should be a responsibility of the myscript module anyway. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a programming language that is combination of Python and Basic?
Michael Torrie wrote: http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html Somebody better tell the Linux kernel developers about that! They apparently haven't read that yet. Better tell CPU makers too. In assembly it's all gotos. I'm sure you are joking. Using goto for error handling in C is a reasonable practice, Avoiding that for the sake of it would be like, say, avoiding "raise" in python because "a procedure should only have one exit point". -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a programming language that is combination of Python and Basic?
baykus wrote: those "lines" as numbered steps or numbered bricks that are sitting on eachother but I see them as timelines or like filmstrips. Anyways it sounds like such a toy programming language does not exists except Arnaud surprisingly efficient code. and I will search my dream somewhere else :) Actually, your dreams have already been implemented in Python. As an april fool's joke. Really. It works, but is so silly and depraved that I'm not going to provide a link. -- http://mail.python.org/mailman/listinfo/python-list
Re: Memory footpring of python objects
BlueBird wrote: I have a program that manages several thousands instances of one object. To reduce memory consumption, I want of course that specific object to have the smallest memory footpring possible. Have you thought of using something like the flyweight pattern and a compact data representation like a numpy array? -- http://mail.python.org/mailman/listinfo/python-list
Re: namespace query
Dr Mephesto wrote: Why are the class files I created not seeing the top namespace? Because it's how python works. What you think is a top namespace, it's not "at the top". It's just the namespace of the module you run the program with. You must import numpy from the all the modules that make use of it. I doubt your "global" fixed something, I'd like to see an example. -- http://mail.python.org/mailman/listinfo/python-list
Re: namespace query
Dr Mephesto wrote: ok, sorted. I had thought that when a module was imported, it was added to a larger shared namespace used by all the modules. Now, that would be awfulll Because one of the most important things about python (and the reason I can live without an IDE) is that I can point my finger to an object somewhere and tell you where it comes from, without loading a different source file. For the same reason, import * is frowned upon, especially because it's transitive (and contagious). -- http://mail.python.org/mailman/listinfo/python-list
Re: New fonts for python docs site
Mark wrote: e.g. see http://docs.python.org/library/index.html Please tell me this is a mistake? 3.X docs are the same. Looks ok. What do you see? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Packages : A looming problem? packages might no longer work? (well not on your platform or python version anyway)
David Lyon wrote: What if I decide to write only to Python 3? Fair enough. But don't forget it is open source. So what? Let me ask these two questions... - What about the use case where somebody likes the code and wants to use it on Python 2.5? A patch, a fork, whatever. - Should not that user be able to share back with other Python 2.5 users? Probably. But not necessarily on the same project or repository. Especially if the port is not supported by the original/trunk developer. If anything my suggestion promotes preserving the resources of the original developer rather than letting them expire just because their operating system does I think your idea would be very costing in terms of man-years, and the net result would be... entropy, chaos, and a lot of CO2 :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode in writing to a file
Carbon Man wrote: Py 2.5 Trying to write a string to a file. self.dataUpdate.write(u"\nentry."+node.tagName+ u" = " + cValue) cValue contains a unicode character. node.tagName is also a unicode string though it has no special characters in it. So what's the encoding of your file? If you didn't open dataUpdate with codecs.open, and you don't encode the string someway - i.e. text.encode('utf-8') python has no way to know it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why can function definitions only use identifiers, and not attribute references or any other primaries?
Jeremy Banks wrote: I've read those discussion before, but somehow never made the connection between those and this. I'll give that article a read, it probably details exactly the perspective I'm looking for. Thank you! You could also read this: http://unlimitednovelty.com/2009/03/indentation-sensitivity-post-mortem.html The author is writing a language for the Erlang VM inspired by Python and Ruby. He had some trouble (at the grammar level) in keeping both "indentation working like in python" (dear to Guido and many of us) and "anonymous blocks" (dear to functional languages). So he got braces and was happy :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Why can function definitions only use identifiers, and not attribute references or any other primaries?
Scott David Daniels wrote: I am afraid it will make it too easy to define functions in other modules remotely, a tempting sharp stick to poke your eye out with. It's not very hard at the moment, and I don't see lots of eyes flying by. I don't know about Ruby where monkeypatching seems to be common practice, though. Imagine debugging a pile of code that includes a module with: import random def random.random(): return .42 No need to imagine. I can do the same, one line shorter: >>> import random >>> random.random = lambda: .42 -- http://mail.python.org/mailman/listinfo/python-list
Re: if statement, with function inside it: if (t = Test()) == True:
Ulrich Eckhardt wrote: t = Test() if (t == 'Vla': print t # must contain Vla What's wrong with that? It unnecessarily injects the name 't' into the scope. Since there is no concept in Python of a scope local to block statements, I don't understant what you would like to happen instead. -- http://mail.python.org/mailman/listinfo/python-list
Re: Lisp mentality vs. Python mentality
Scott David Daniels wrote: I don't remember who, but something famously said, in effect: Debugging is hard, maybe twice as hard as writing the code in the first place. Unless you are one of those nonexistent few He would be the K in K&R. -- http://mail.python.org/mailman/listinfo/python-list
Re: Web based application development using python
Rahul wrote: 1) Do you have any idea about web based support (like mod_python) provided by python.org (official web site) Details: - As we know mod_python is used for embeding python code into apache server. so, i want to know whether mod_python is officially supported by python.org or if there is other such framework for embeding python on web server Forget about mod_python, everything else is better. This list (the first result upon googling for "python web frameworks") is actually up to date, and a good start. http://wiki.python.org/moin/WebFrameworks Just don't ask which one is best for everything, or which one is The Official Standard Way Of Doing Things. -- http://mail.python.org/mailman/listinfo/python-list
Re: Geohashing
djc wrote: Python 2.5.2 (r252:60911, Oct 5 2008, 19:29:17) geohash(37.421542, -122.085589, b'2005-05-26-10458.68') ^ SyntaxError: invalid syntax The byte type is new in 2.6 -- http://mail.python.org/mailman/listinfo/python-list
Re: Why bool( object )?
Bruno Desthuilliers wrote: Lawrence D'Oliveiro a écrit : What is the rationale for considering all instances true of a user- defined type? It's a stupid idea, Nope, it's a very sensible default (given you can redefine the 'nothingness' value of your types instances), specially when the language doesn't have a proper boolean type (which was the case for Python until 2.2 or 2.3, can't remember exactly). Man, you've given a serious answer to a sarcastic reply to an OP who has been -- for years -- second in trolliness only to Xah Lee. Either that, or I have to replace my humor detector. -- http://mail.python.org/mailman/listinfo/python-list
Re: Geohashing
norseman wrote: The posting needs (its creation) ... DATE. ... The code needs to state OS and program and version used to write it. And from there - user beware." Which would reduce the confusion greatly. I got the same error message and decided it was from an incompatible version, using incompatible modules. Looks as if I guessed right. I pity the poor first timer. Raymond is living in a parallel universe (Fahrenheit 3K) where all the previous Python releases have been burned ;) dystopianl-ly yours, -- http://mail.python.org/mailman/listinfo/python-list
Re: Tools for web applications
Mario wrote: I used JCreator LE, java IDE for windows because, when I add documentation of some new library, I have it on a F1 and index. So how you manage documentation and code completion ? I asume that you are geek but not even geeks could know every method of every class. What you call "code completion" cannot work in many cases with dynamic languages. Nobody knows which methods are available to an object until the program is running. Dynamic access to attributes/methods that don't explicitly exist in Python code, is much more common than you might think. As an example, your object might be an instance of a class mapped to SQL tables that are reflected at runtime. Attributes would represent database columns and other things that are never declared in Python code. Or suppose the object is returned by an XML/HTML/JSON parser from a document the program has just downloaded from Argentina. Methods here would be the sub-elements or tag attributes for traversing the document. The instance we're talking of might even be deserialized from ... somewhere, without any need to declare type or any interface at all. I must admit that I've never used completion of anything while developing. I routinely it do with the IPython shell, and I would suffer if I didn't have it in postgres, but not while editing python. -- http://mail.python.org/mailman/listinfo/python-list
Re: what's the best way to call a method of object without a guarantee of its existence
Leon wrote: One way, define the object before it is used, like this: object = None This is a good practice anyway. Conditional existance of objects is quite evil. Resorting to if defined('foo') is double-plus-ugly. The other way, using try ... catch try: object.method() catch NameError: pass Except you should trap AttributeError because you defined the thing as None before. NameErrors should be fixed as bugs, not trapped (IMHO -- but in python there is always a use case for everything). Keep in mind that AttributeError might come from inside the method(), which could be confusing By using the if stuff: stuff.run() idiom, you avoid the last issue and keep it simple enough. for big programs, which is better, or any other way? Define "big", as in scope, LOCs, or number of committers? -- http://mail.python.org/mailman/listinfo/python-list
Re: what's the best way to call a method of object without a guarantee of its existence
Leon wrote: So I need to go back to the module including "parent" class to define the objects that I maybe use in future as None, You can assign them to a placeholder, with a method that always exists but does nothing. class NullObject(object): def method(self, *args, **kw): pass actually, the module including "parent' class works very well without those definitions, from parent class's point of view, those definitions are kind of noisy. If you don't feel the need to define the instances there, maybe they don't belong to that class after all. -- http://mail.python.org/mailman/listinfo/python-list
Re: How should I use grep from python?
Matthew Wilson wrote: consensus. I could os.popen, commands.getstatusoutput, the subprocess module, backticks, etc. Backticks do_not_do what you think they do. And with py3k they're also as dead as a dead parrot. -- http://mail.python.org/mailman/listinfo/python-list
Re: OOP & Abstract Classes
Mike Driscoll wrote: I've never used (or heard of) the Abstract type...and the guy who wrote the FAQ was being a jerk. Who, Peter Norvig? (from wikipedia) Peter Norvig is an American computer scientist. He is currently the Director of Research (formerly Director of Search Quality) at Google Inc. He is a Fellow and Councilor of the American Association for Artificial Intelligence and co-author, with Stuart Russell, of Artificial Intelligence: A Modern Approach, now the standard college text. He previously was head of the Computational Sciences Division (now the Intelligent Systems Division) at NASA Ames Research Center, where he oversaw a staff of 200 scientists performing NASA's research and development in autonomy and robotics, automated software engineering and data analysis, neuroengineering, collaborative systems research, and simulation-based decision-making. Before that he was Chief Scientist at Junglee, where he helped develop one of the first Internet comparison shopping services; Chief designer at Harlequin Inc.; and Senior Scientist at Sun Microsystems Laboratories. etc. etc. Yes, I usually look up in wikipedia before calling anyone a jerk :) :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Pycon Tre, grazie!
daniele wrote: Si è concluso ieri la pycon tre, è stata molto interessante, un bel evento per una bella comunità. Sempre meglio.. anche se mi preoccupa un po' un eventuale cambio di location Ho visto con grande piacere, oltre all'incremento dei partecipanti, anche un sensibile incremento delle partecipanti! Si'... in particolare durante il talk di Raymond :) -- http://mail.python.org/mailman/listinfo/python-list
Re: introspection question: get return type
Bruno Desthuilliers wrote: Oh, you meant the "return type" ? Nope, no way. It just doesn't make sense given Python's dynamic typing. I thought that the OP was writing a tool to document not-very-dynamic code. Unless he's really trying to write in Nohtyp, the language where value types are more important than values ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Just wondering
Gediminas Kregzde wrote: def doit(i): pass def main(): a = [0] * 1000 t = time() map(doit, a) print "map time: " + str(time() - t) Here you are calling a function ten million times, build a list with of ten million None results, then throw it away. def main2(): t = time() a = [0] * 1000 for i in a: pass print "loop time: " + str(time() - t) Here you do nothing but iterating 'i' over the 'a' list. main() # takes approximately 5x times longer than main2() main2() I'm wondering were is catch? Function calls are not free in python. They cost a lot more than they do in C, Delphi or other languages. -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeking old post on developers who like IDEs vs developers who like simple languages
Steve Ferg wrote: I periodically think of that blog, usually in circumstances that make me also think "Boy, that guy really got it right". But despite repeated and prolonged bouts of googling I haven't been able to find the article again. I must be using the wrong search terms or something. Does anybody have a link to this article? I think you mean this clbuttic post: http://osteele.com/archives/2004/11/ides -- http://mail.python.org/mailman/listinfo/python-list
Re: ? 'in' operator and fallback to __getitem__
timh wrote: However strange things happen to the name passed to __getitem__ in the following example (and in fact in all varients I have triend the name/ key passed to __getitem__ is always the integer 0 I think it's scanning the container as a sequence and not as a mapping, hence the access by index. -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeking old post on developers who like IDEs vs developers who like simple languages
Chris Rebert wrote: On the other hand there are developers who much prefer to keep things light-weight and simple. Would it be fair to say the first type tends to congregate in herds, particularly in corporate IT departments, while the latter tends to operate on a more individual basis? That would certainly explain Lisp hackers! *(ducks)* Oh, come on! Corporate environments are usually positive towards Lisp hackers, and Lisp hackers are OTOH very positive towards corporate environments. That's why they repel. -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlite3, qmarks, and NULL values
Mitchell L Model wrote: def lookupxy(x, y): if y: conn.execute("SELECT * FROM table WHERE COL1 = ? AND COL2 = ?", (x, y)) else: conn.execute("SELECT * FROM table WHERE COL1 = ? AND COL2 IS NULL", (x,)) The more question marks involved the more complicated this would get, especially if question marks in the middle of several would sometimes need to be NULL. With SQLAlchemy you could write: table.select().where((table.c.col1==x) & (table.c.col2==y)) where x or y are None, the sql engine generates the appropriate "IS NULL" clause. I hope I'm missing something and that someone can tell me what it is. Yes, you are missing SQLAlchemy ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to understand a very simple class - from the book "dive into python"
walterbyrd wrote: > I am sure this is totally simple, but I missing something. Do you know what a dictionary is? -- http://mail.python.org/mailman/listinfo/python-list
Re: source beautifier
Stefan Behnel wrote: http://www.polystyle.com/features/python-beautifier.jsp I've never used it, but the example is quite clear. I tend to believe that running these tools on some average Python code would not even change whitespace. ;) I bet it's idempotent against _your_ code, but not in the context of python beginners or people who just made up their mind about what coding style to use. -- http://mail.python.org/mailman/listinfo/python-list
Re: module global variables
pistacchio wrote: On 12 Mag, 10:01, alex23 <[EMAIL PROTECTED]> wrote: On May 12, 5:17 pm, pistacchio <[EMAIL PROTECTED]> wrote: hi to all! can i load a module passing to it, automatically and as default, all the caller's global variables to act as module's global variables? Are you positively sure you need this? Modifying imported modules is already quite fragile, but this.. it's basically a reversed(import *) It's quite messy. Where quite equals to "very" -- http://mail.python.org/mailman/listinfo/python-list
Re: Now what!?
notbob wrote: frustrated and give up on learning programming, not really caring much for coding, anyway. But, dammit, I'm gonna stick with it this time. I'll learn python if it kills me! No, it won't kill you but make you stronger ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Some comparison operators gone in Python 3.0?
[EMAIL PROTECTED] wrote: Is that true that this comparison operators are gone in Python 3.0: <(is less than) (is greater than) <= (is less than or equals) = (is greater than or equals) Is it true? Nope. -- http://mail.python.org/mailman/listinfo/python-list
Re: array in class
alefajnie wrote: class B: this_is_common_for_all_instances = [] def __init__(self, v): self.this_is_common_for_all_instances.append(v) now I can create some instances of B, but all of them have the same array, why Because you didn't reassign the attribute 'this_is_common_for_all_instances', but appended to it. and how create array in class - normal array, "private variable" 1) it's called a list, not an array 2) you do that in the __init__ method: self.blabla = [] 3) still, it won't be a "private" attribute, just an instance attribute -- http://mail.python.org/mailman/listinfo/python-list
Re: The 'is' identity operator checking immutable values caution
[EMAIL PROTECTED] wrote: We have to avoid the use of the 'is' identity operator with basic, immutable values such as numbers and strings. I'm glad for you. Did you really write checks like "if foo is 27" ? The point is, you have to learn technologies to use them. It's not like technologies learn you (not even in soviet Russia) How is with this issue in Python 3.0? Is it fixed? There is nothing to fix. Does Python handle this things properly now? It always did. -- http://mail.python.org/mailman/listinfo/python-list