Re: newbie question
Dody Suria thank u. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Dao Language v.0.9.6-beta is release!
On 2005-12-11, Rick Wotnaz <[EMAIL PROTECTED]> wrote: > > Make a grocery list. Do you terminate each item with > punctuation? Write a headline for a newspaper. Is > actually, I do. i write as much as fits in one line and separate items with comma. > > may find Python's set strange at first. Please try it, and > don't fight it. See if your objections don't fade away. If > you're like most Python newbies, you'll stop thinking about > I'm not Python newbie. I wrote a good deal of non-trivial python code, and I still don't like it and still find it very annoying. > > brackets before long, and if you're like a lot of us, > you'll wonder what those funny squiggles mean when you are > forced to revert to one of those more primitive languages. > Actually, after I learned Python, I value "funny squiggles" in other languages even more. It's very annoying, for example, that I can't split a long line in the following way: print a + b + c + d print "other statement" I guess I'm required to insert some unneccessary () around the long expression to disable the white space parsing.. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using XML w/ Python...
Yes i know, i did check out a couple but i could never understand it. They were confusing for me and i wasnt hoping for a full typed tutorial, just like some help with excactly wat im trying to do, not the whole module... but watever, Thx alot for the feedbak. -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: Inline Import
On Sat, 10 Dec 2005 19:40:08 -0800, Robert Kern <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: > >> Are you willing to type a one-letter prefix to your .re ? E.g., >> >> >>> class I(object): >> ... def __getattr__(self, attr): >> ... return __import__(attr) > >[snip] > >> There are special caveats re imports in threads, but otherwise >> I don't know of any significant downsides to importing at various >> points of need in the code. The actual import is only done the first time, >> so it's effectively just a lookup in sys.modules from there on. >> Am I missing something? > >Packages. > Ok, if you're willing to add a trailing '._' to indicate the end of a package path, and start it with a P instead of an I, you could try the following (just a hack, not tested beyond what you see, (again ;-) ) < impexpr.py > class I(object): __cache = {} def __getattr__(self, attr, cache = __cache): try: return cache[attr] except KeyError: cache[attr] = ret = __import__(attr) return ret getdotted = __getattr__ class P(I): def __init__(self): self.elems = [] def __getattr__(self, attr): if attr == '_': dotted = '.'.join(self.elems) mod = self.getdotted(dotted) for attr in self.elems[1:]: mod = getattr(mod, attr) self.elems = [] return mod else: self.elems.append(attr) return self P, I = P(), I() -- >>> from ut.impexpr import I, P >>> I.math.pi 3.1415926535897931 >>> I.os.path.isfile >>> P.ut.miscutil._.prb >>> type(I)._I__cache.keys() ['ut.miscutil', 'os', 'math'] >>> P.ut.miscutil._.disex >>> type(I)._I__cache.keys() ['ut.miscutil', 'os', 'math'] >>> I.ut.miscutil >>> I.ut I am not recommending this particularly. I just like to see how close python already is to allowing the spelling folks initially think requires a language change ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: Inline Import
Shane Hathaway wrote: > Mike Meyer wrote: > > Shane Hathaway <[EMAIL PROTECTED]> writes: > >>I'd like a way to import modules at the point where I need the > >>functionality, rather than remember to import ahead of time. This > >>might eliminate a step in my coding process. Currently, my process is > >>I change code and later scan my changes to make matching changes to > >>the import statements. The scan step is error prone and time > >>consuming. By importing inline, I'd be able to change code without the > >>extra scan step. > > > > > > As others have pointed out, you can fix your process. That your > > process doesn't work well with Python isn't a good reason for changing > > Python. > > Do you have any ideas on how to improve the process of maintaining > imports? Benji's suggestion of jumping around doesn't work for moving > code and it interrupts my train of thought. Sprinkling the code with > import statements causes a speed penalty and a lot of clutter. > Is using import near where you need it really such a hit to speed ? May be it is critical inside a function(may be called in a loop) but what about something like this : import def this_func: use it here In this way, it is no different than the @decorator in terms of "moving codes around", i.e. just copy the extra import/@decorator lines if you want to move this to a new module. In terms of speed, it won't be part of the function but a module so the speed penalty would be only when other import this module(one time or multiple time but still not the same as calling a function in a loop), no different than putting everything at the top of the file(well a bit but should be neglecgible). -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Heiko Wundram wrote: > Brian Beck wrote: > >>>class D1(Base): >>> def foo(self): >>> print "D1" >>> >>>class D2(Base): >>> def foo(self): >>> print "D2" >>>obj = Base() # I want a base class reference which is polymorphic >>>if (): >>> obj = D1() >>>else: >>> obj = D2() >> >>I have no idea what you're trying to do here and how it relates to >>polymorphism. >> > > > He's translating C++ code directly to Python. obj = Base() creates a > variable of type Base(), to which you can assign different object types (D > (), D2()) which implement the Base interface (are derived from Base). > Err... At least I think it's what this code is supposed to mean... > > In C++ you'd do: > > Base *baseob; > > if( ) { > baseob = (Base*)new D1(); > } else { > baseob = (Base*)new D2(); > } > > baseob->foo(); > > (should, if foo is declared virtual in Base, produce "d1" for D1, and "d2" > for D2) > > At least IIRC, it's been quite some time since I programmed C++... ;-) > *shudder* Yes, that's what I tried to express (the cast to Base* is redundant here by the way, since D1/D2 are also of type Base; you can always hold a base class pointer to derived types without type conversion). I have also read the other answers to my question, and I am really sorry if I have sounded ignorant in my post, but it's harder than I thought to move to a language where all these techniques one had learned in years of hard work suddenly become redundant :) I'm so used to statically typed languages that the shift is very confusing. Looks as if it isn't as easy to learn Python afterall, for the mere reason of unlearning rules which don't apply in the world of Python anymore (which seem to be quite a lot!). Regards, Matthias -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Brian Beck wrote: > def foo(self): > raise NotImplementedError("Subclasses must implement foo") That's actually a good idea, though not as nice as a check at "compile-time" (jesus, I'm probably talking in C++ speech again, is there such a thing as compile-time in Python at all?!) Another thing which is really bugging me about this whole dynamically typing thing is that it seems very error prone to me: foo = "some string!" # ... if (something_fubar): fo = "another string" Oops, the last 'o' slipped, now we have a different object and the interpreter will happily continue executing the flawed program. I really see issues with this, can anyone comment on this who has been working with Python more than just a day (like me)? Regards, Matthias -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
That was quite insightful Martin, thanks. Regards, Matthias -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Hallöchen! Matthias Kaeppler <[EMAIL PROTECTED]> writes: > [...] > > Another thing which is really bugging me about this whole > dynamically typing thing is that it seems very error prone to me: > > foo = "some string!" > > # ... > > if (something_fubar): >fo = "another string" > > Oops, the last 'o' slipped, now we have a different object and the > interpreter will happily continue executing the flawed program. > > I really see issues with this, can anyone comment on this who has > been working with Python more than just a day (like me)? There are even a couple of further checks which don't happen (explicitly) in a dynamic language like Python, and which do happen in most statically typed languages like C++. And yes, they are a source of programming mistakes. However, in everyday programming you don't feel this. I don't make more difficult-to-find mistakes in Python than I used to make in my C++ code. But what you do feel is the additional freedom that the dynamic approach gives to you. Basically it's a matter of taste and purpose whether you want to be controlled heavily or not. Python is particularly liberal, which I appreciate very much. Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetusICQ 264-296-646 -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: Inline Import
Shane Hathaway wrote: > Do you have any ideas on how to improve the process of maintaining > imports? Benji's suggestion of jumping around doesn't work for moving > code and it interrupts my train of thought. Sprinkling the code with > import statements causes a speed penalty and a lot of clutter. You didn't detail your implementation strategy for that feature very much, but the most natural way of implementing it would also cause the same speed penalty as sprinkled import statements. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Dao Language v.0.9.6-beta is release!
Zeljko Vrba wrote: > On 2005-12-11, Rick Wotnaz <[EMAIL PROTECTED]> wrote: > >>Make a grocery list. Do you terminate each item with >>punctuation? Write a headline for a newspaper. Is >> > > actually, I do. i write as much as fits in one line and separate items > with comma. > > >>may find Python's set strange at first. Please try it, and >>don't fight it. See if your objections don't fade away. If >>you're like most Python newbies, you'll stop thinking about >> > > I'm not Python newbie. I wrote a good deal of non-trivial python code, > and I still don't like it and still find it very annoying. > > >>brackets before long, and if you're like a lot of us, >>you'll wonder what those funny squiggles mean when you are >>forced to revert to one of those more primitive languages. >> > > Actually, after I learned Python, I value "funny squiggles" in other > languages even more. It's very annoying, for example, that I can't split > a long line in the following way: > > print a + b + > c + d > print "other statement" > > I guess I'm required to insert some unneccessary () around the long expression > to disable the white space parsing.. I don't suppose there's any good reason, then, why (for example) outlining tools use indentation to indicate different levels of significance. I'm sorry you find the indentation unnatural and inconvenient, but you may have to accept that for this feature you are actually in a minority. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Another newbie question
Paul Rubin wrote: > Steven D'Aprano <[EMAIL PROTECTED]> writes: > >>The fact that sys is a module and not a class is a red herring. If the >>"Law" of Demeter makes sense for classes, it makes just as much sense for >>modules as well -- it is about reducing coupling between pieces of code, >>not something specific to classes. > > > I don't see that. If a source line refers to some module you can get > instantly to the module's code. But you can't tell where any given > class instance comes from. That's one of the usual criticisms of OOP, > that the flow of control is obscured compared with pure procedural > programming. > > >>One dot good, two dots bad. > > > Easy to fix. Instead of sys.stdout.write(...) say > > from sys import stdout > > from then on you can use stdout.write(...) instead of sys.stdout.write. The fact that you are prepared to argue for one of two mechanisms rather than the other based simply on the syntax of two semantically equivalent references is unworthy of someone who knows as much about programming as you appear to do. The "Law" of Demeter isn't about *how* you access objects, it's about what interfaces to objects you can "legally" manipulate without undue instability across refactoring. In other words, it's about semantics, not syntax. And it's led a lot of Java programmers down a path that makes their programs less, not more, readable. Python's ability to let the programmer decide how much encapsulation is worthwhile is one of its beauties, not a wart. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
wxpython book
I have seen some brief mention of the new book by Robin Dunn in one or two posts. But none that highlight that the book is to be published sometime at then end of Jan 2006. I hope that turns out to be an accurate date. It has been long-awaited so I thought it ought to get a proper mention. I must admit that I've been waiting a long time for some solid documentation that is up to date with the current release of wxwidgets. I hope this list will be the right one to post to since there are always posts about what gui tool to use. The link is http://www.manning.com The front page of the site has a brief outline of the book. What would be good is if it had a list of contents so we could be clearer as to what subjects were covered and in what depth. I can't thank Robin and his colleague enough for the effort to produce the book. So I hope it proves very popular. John Aherne -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: Inline Import
Shane Hathaway wrote: > Thoughts? I have two reasons to dislike it: 1. It's a language change. Others have pointed out that you can achieve the same without a language change; it would be easy to write name_expr = _import.re.compile('[a-zA-Z]+') 2. In the form in which you have written it, I believe it is unimplementable (or, else, an implementation would have counter-intuitive border cases). For example, what would .xml.sax.expatreader.ExpatParser.__init__(self) mean? From the description, it appears that it would be from xml.sax.expatreader.ExpatParser import __init__ as \ __hidden_xml_sax_expatreader_ExpatParser___init__ which, of course, wouldn't work, because ExpatParser is not a module. 3. As in any good list of two items, I have a third complaint: for packages, this would be tedious to type (as the sax example illustrates) Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: slice notation as values?
Brian Beck wrote: > Antoon Pardon wrote: >> Will it ever be possible to write things like: >> >> a = 4:9 > > I made a silly recipe to do something like this a while ago, not that > I'd recommend using it. But I also think it wouldn't be too far-fetched > to allow slice creation using a syntax like the above... > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/415500 > Another possibility would be to make the slice type itself sliceable, then you could write things like: >>> a = slice[4:9] >>> a slice(4, 9, None) Sample implementation: >>> class MetaSlice(object): def __getitem__(cls, item): return item def __init__(self, *args, **kw): return super(MetaSlice,self).__init__(self, *args, **kw) >>> class Slice(slice): __metaclass__=MetaSlice >>> Slice[2:3] slice(2, 3, None) >>> Slice[:3] slice(None, 3, None) >>> Slice[:3:-1] slice(None, 3, -1) -- http://mail.python.org/mailman/listinfo/python-list
Re: Using XML w/ Python...
Look at the standard python library reference http://docs.python.org/lib/dom-example.html the handleSlide function almost does what you want, except that you should use 'parse' and not 'parseString'. Original Message From: "Jay" <[EMAIL PROTECTED]> To: Subject: Re:Using XML w/ Python... Date: 11/12/2005 09:33 > Yes i know, i did check out a couple but i could never understand it. > They were confusing for me and i wasnt hoping for a full typed > tutorial, just like some help with excactly wat im trying to do, not > the whole module... but watever, Thx alot for the feedbak. > -- http://mail.python.org/mailman/listinfo/python-list
Re: double underscore attributes?
[EMAIL PROTECTED] wrote: > Entering > dir(5) > > > I get > ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', > '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', > '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', > '__hex__', '__init__', '__int__', '__invert__', '__long__', > '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', > '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', > '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', > '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', > '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', > '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', > '__truediv__', '__xor__'] > > Every time I use dir(some module) I get a lot of attributes with double > underscore, for example __add__. Ok, I thought __add__ must be a method > which I can apply like this > 5.__add(8) > Bzzt. Python 2.4.1 (#1, May 27 2005, 18:02:40) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> 5 . __add__(9) 14 >>> [...] regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Using XML w/ Python...
Jay wrote: > Yes i know, i did check out a couple but i could never understand it. > They were confusing for me and i wasnt hoping for a full typed > tutorial, just like some help with excactly wat im trying to do, not > the whole module... but watever, Thx alot for the feedbak. > Well I don't want to hold this up as an example of best practice (it was a quick hack to get some book graphics for my web site), but this example shows you how you can extract stuff from XML, in this case returned from Amazon's web services module. Sorry about any wrapping that mangles the code. regards Steve #!/usr/bin/python # # getbooks.py: download book details from Amazon.com # # hwBuild: database-driven web content management system # Copyright (C) 2005 Steve Holden - [EMAIL PROTECTED] # # This program is free software; you can redistribute it # and/or modify it under the terms of the GNU General # Public License as published by the Free Software # Foundation; either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public # License along with this program; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, # Boston, MA 02111-1307 USA # import urllib import urlparse import os import re from xml.parsers import expat from config import Config picindir = os.path.join(Config['datadir'], "pybooks") for f in os.listdir(picindir): os.unlink(os.path.join(picindir, f)) filpat = re.compile(r"\d+") class myParser: def __init__(self): self.parser = expat.ParserCreate() self.parser.StartElementHandler = self.start_element self.parser.EndElementHandler = self.end_element self.parser.CharacterDataHandler = self.character_data self.processing = 0 self.count = 0 def parse(self, f): self.parser.ParseFile(f) return self.count def start_element(self, name, attrs): if name == "MediumImage": self.processing = 1 self.imgname = "" if self.processing == 1 and name == "URL": self.processing = 2 def end_element(self, name): if self.processing == 2 and name == "URL": self.processing = 1 print "Getting:", self.imgname scheme, loc, path, params, query, fragment = urlparse.urlparse(self.imgname) itemno = filpat.match(os.path.basename(path)) fnam = itemno.group() u = urllib.urlopen(self.imgname) img = u.read() outfile = file(os.path.join(picindir, "%s.jpg" % fnam), "wb") outfile.write(img) outfile.close() self.count += 1 if self.processing ==1 and name == "MediumImage": self.processing = 0 def character_data(self, data): if self.processing == 2: self.imgname += data def main(search=None): print "Search:", search count = 0 for pageNum in range(1,5): f = urllib.urlopen("http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=&t=steveholden-20&SearchIndex=Books&Operation=ItemSearch&Keywords=%s&ItemPage=%d&ResponseGroup=Images&type=lite&Version=2004-11-10&f=xml"; % (urllib.quote(search or Config['book-search']), pageNum)) fnam = os.path.join(picindir, "bookdata.txt") file(fnam, "w").write(f.read()) f = file(fnam, "r") p = myParser() n = p.parse(f) if n == 0: break count += n return count if __name__ == "__main__": import sys search = None if len(sys.argv) > 1: search = sys.argv[1] n = main(search) print "Pictures found:", n -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Using XML w/ Python...
On Sat, 10 Dec 2005 21:12:04 -0800, Jay wrote: > OK, I have this XML doc, i dont know much about XML, but what i want > to do is take certain parts of the XML doc the most simple module I've found to do that is xmltramp from http://www.aaronsw.com/2002/xmltramp/ for example: #!/usr/bin/env python import xmltramp note = xmltramp.load('http://www.w3schools.com/xml/note.xml') print note.body -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Dao Language v.0.9.6-beta is release!
On 2005-12-11, Steve Holden <[EMAIL PROTECTED]> wrote: > > I don't suppose there's any good reason, then, why (for example) > outlining tools use indentation to indicate different levels of > significance. > Nobody bothers to figure out something better? Now you will argue that then the indendation is good enough.. and I can just reply that then it's an open research question.. A philisophical note: An obvious defficieny of the current way we write code now is its inherent tree-structure resulting from {}, indentation, begin/end markers or whatnot. But the flow of code is often not a tree but a cycle.. Yet we are always dealing with a tree-like representation of the code on screen. This note also applies to your remark about outlining tools. > > I'm sorry you find the indentation unnatural and inconvenient, but you > may have to accept that for this feature you are actually in a minority. > I have no problem accepting that I'm in a minority. I have a problem with offensive people using my example arguments to riducule me.. While they even don't want to open their minds and accept that there might be a remote possibility that indentation is not ideal. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Matthias Kaeppler wrote: > Brian Beck wrote: > >> def foo(self): >> raise NotImplementedError("Subclasses must implement foo") > > > That's actually a good idea, though not as nice as a check at > "compile-time" (jesus, I'm probably talking in C++ speech again, is > there such a thing as compile-time in Python at all?!) > > Another thing which is really bugging me about this whole dynamically > typing thing is that it seems very error prone to me: > > foo = "some string!" > > # ... > > if (something_fubar): >fo = "another string" > > Oops, the last 'o' slipped, now we have a different object and the > interpreter will happily continue executing the flawed program. > > I really see issues with this, can anyone comment on this who has been > working with Python more than just a day (like me)? > > Regards, > Matthias Matthias, maybe this article is of interest for you: http://www.mindview.net/WebLog/log-0025 Regards, Ernst -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Dao Language v.0.9.6-beta is release!
Zeljko Vrba wrote: > > > > I'm sorry you find the indentation unnatural and inconvenient, but you > > may have to accept that for this feature you are actually in a minority. > > > I have no problem accepting that I'm in a minority. I have a problem with > offensive people using my example arguments to riducule me.. While they > even don't want to open their minds and accept that there might be a > remote possibility that indentation is not ideal. Welcome to c.l.py -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Matthias Kaeppler wrote: > That was quite insightful Martin, thanks. > > Regards, > Matthias (Disclaimer: i didn't read thru whole thread, but i didn't see these links trotted out either, which're germane: http://naeblis.cx/rtomayko/2004/12/15/the-static-method-thing http://dirtsimple.org/2004/12/java-is-not-python-either.html http://dirtsimple.org/2004/12/python-is-not-java.html http://idevnews.com/PrintVersion_CaseStudies.asp?Search3=web+services&Go2=Go&ID=118 http://www.idevnews.com/PrintVersion_TipsTricks.asp?ID=107 http://www.eros-os.org/pipermail/e-lang/2001-June/005337.html -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
On Sun, 11 Dec 2005 10:02:31 +0100, Matthias Kaeppler wrote: > Brian Beck wrote: >> def foo(self): >> raise NotImplementedError("Subclasses must implement foo") > > That's actually a good idea, though not as nice as a check at > "compile-time" (jesus, I'm probably talking in C++ speech again, is > there such a thing as compile-time in Python at all?!) Yes. Python, like Java, compiles your code into byte code which is then executed by the Python runtime engine. Back in the early days of computing the distinction between compiled languages and interpreted languages might have been meaningful, but not so much today. There is significant fuzzy overlap between the two. > Another thing which is really bugging me about this whole dynamically > typing thing is that it seems very error prone to me: > > foo = "some string!" > > # ... > > if (something_fubar): > fo = "another string" > > Oops, the last 'o' slipped, now we have a different object and the > interpreter will happily continue executing the flawed program. Yes, this is one specific error which the Python compiler won't pick up for you. However, it will pick up the related error: foo = "some string!" # ... if (something_fubar): bar = fo # should be foo assuming there isn't some other name fo which already exists. > I really see issues with this, can anyone comment on this who has been > working with Python more than just a day (like me)? Python works well with test-driven development. Test-driven development will pick up this sort of error, and many other errors too, with less effort and more certainty than compile-time checking. The problem with static typed languages is that they make the programmer do a lot of the work, just so the compiler can pick up a few extra errors at compile time rather than at run time. But since the compiler can't save you from run time errors, you still should be doing test-driven development. But if you are doing test-driven development, the value of the static type checking is rather low. After all, "does it compile?" is only one test out of many, and really the least important. Lots of code compiles that doesn't work; however no code that works can possibly fail to compile. Having said that, static type checking is not utterly useless, and rumour has it that Python may some day include some version of it. Oh, if you are tempted to fill your Python code with manual type checks, using type() or isinstance(), I suggest that you learn about "duck typing" first. Otherwise known as "latent typing". -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Steven D'Aprano wrote: > Python works well with test-driven development. Test-driven development > will pick up this sort of error, and many other errors too, with less > effort and more certainty than compile-time checking. The problem with > static typed languages is that they make the programmer do a lot of the > work, just so the compiler can pick up a few extra errors at compile time > rather than at run time. > Any language would be benefited from test-driven development, python needs it because of its dynamic nature. And I don't think Haskell make the programmer do a lot of work(just because of its static type checking at compile time). -- http://mail.python.org/mailman/listinfo/python-list
Great books on Python?
I am not unfamiliar to programming but a newbie in Python. Could you recommend me (a) great book(s) to start with? Free online books or solid books are welcome. Thanx in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
On 12/11/05, Matthias Kaeppler <[EMAIL PROTECTED]> wrote: > Brian Beck wrote: > > def foo(self): > > raise NotImplementedError("Subclasses must implement foo") > > That's actually a good idea, though not as nice as a check at > "compile-time" (jesus, I'm probably talking in C++ speech again, is > there such a thing as compile-time in Python at all?!) > > Another thing which is really bugging me about this whole dynamically > typing thing is that it seems very error prone to me: > > foo = "some string!" > > # ... > > if (something_fubar): > fo = "another string" > > Oops, the last 'o' slipped, now we have a different object and the > interpreter will happily continue executing the flawed program. > > I really see issues with this, can anyone comment on this who has been > working with Python more than just a day (like me)? You are totally correct and this does cause errors. However, I'd like you to take a few minutes and go back over all your C and C++ and Java code and make note of how many lines of code and how many complicated constructs you've used over the years to subvert the type system in those languages. In my experience, and in many other peoples experience, dynamic ducky typing saves far more work than it costs, even when you factor in "typo bugs" which would be prevented by static typing. Thats not even counting bugs in the extra code you've written to work around the compiler. In fact, I'd say that a signifigant portion of my time in writing C++ code is spent convincing the compiler to do what I want, and not figuring out what I want. In Python, the opposite is true. My experience in that regard is pretty typical - you'll find scores of stories on the web of C++ programmers who switched to Python and breathed a sigh of relief. All that said, there are automated checkers that can assist in avoiding these kind of bugs (as well as several others). Look into PyChecker and PyLint. > > Regards, > Matthias > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Dao Language v.0.9.6-beta is release!
On 2005-12-11, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > > Welcome to c.l.py > Oh, thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Matthias Kaeppler wrote: > I really see issues with this, can anyone comment on this who has been > working with Python more than just a day (like me)? Maybe you should work with Python more than one day before you start looking for potential problems? ;-) (I suggest reimplementing some portion of some C++ program you've worked on recently, to get a feel for the language.) For any potential problem you can think of, you'll find people here who've never ever had any problems with it, and you'll find people who think that this specific problem is what prevents Python from going "mainstream" (and who love when someone else seems to support their view, whether they really do it or not). FWIW, having worked full time in and on Python for over 10 years, I can assure you that I don't have a problem with: - mistyped variable names - indentation ("SUCKS BIG TIME") - how to handle import statements - finding things in the library reference - the blue color on python.org - the size of the python DLL on windows - tabs vs. spaces - unnecessary colons - lambdas being removed in python 3.0 - lambdas not being removed in python 3.0 - limited support for GIF animation in PIL - the noise level on comp.lang.python - the global interpreter lock - the unsuitability of notepad as a programmer editor - the number of web frameworks available or any of the other "major" problems that you'll hear about on c.l.python from time to time. But that's me. Your milage may vary. The only way to find out is to use the language. Write code, not usenet posts. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
In article <[EMAIL PROTECTED]>, Matthias Kaeppler <"matthias at finitestate dot org"> wrote: > >Another thing which is really bugging me about this whole dynamically >typing thing is that it seems very error prone to me: > >foo = "some string!" > ># ... > >if (something_fubar): >fo = "another string" > >Oops, the last 'o' slipped, now we have a different object and the >interpreter will happily continue executing the flawed program. pychecker (or pylint, but I haven't tried that) -- Aahz ([EMAIL PROTECTED]) <*> http://www.pythoncraft.com/ "Don't listen to schmucks on USENET when making legal decisions. Hire yourself a competent schmuck." --USENET schmuck (aka Robert Kern) -- http://mail.python.org/mailman/listinfo/python-list
Using XML w/ Python...
If you just want to get into it and use it, I'd recommend the following: http://uche.ogbuji.net/uche.ogbuji.net/tech/4suite/amara/It requires the installation of the 4Suite module as well, but it's well worth it. I uses data binding techniques to convert your document into a large tree of named XML Object (for lack of a better explanation). You will then be able to output any portion by calling something like the following: document.body.text.xml()What you call, of course, will depend on the name of each of your nodes in the document. Keep in mind as well that currently there are a couple of issues with "freezing" this into a binary as well. If you just plan to let Python interpret it without "compiling" you will be fine. Amara is an amazing product. And being free doesn't hurt. ;)Regards,MichaelOn Dec 11, 2005, at 1:15 AM, [EMAIL PROTECTED] wrote:OK, I have this XML doc, i dont know much about XML, but what i want to do is take certain parts of the XML doc, such as blah and take just that and put onto a text doc. Then same thing doe the part. Thats about it, i checked out some of the xml modules but dont understand how to use them. Dont get parsing, so if you could please explain working with XML and python to me. Email me at [EMAIL PROTECTED] Aim- jayjay08balla MSN- [EMAIL PROTECTED] Yahoo- raeraefad72 Thx -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
On Sun, 11 Dec 2005 05:48:00 -0800, bonono wrote: > > Steven D'Aprano wrote: >> Python works well with test-driven development. Test-driven development >> will pick up this sort of error, and many other errors too, with less >> effort and more certainty than compile-time checking. The problem with >> static typed languages is that they make the programmer do a lot of the >> work, just so the compiler can pick up a few extra errors at compile time >> rather than at run time. >> > Any language would be benefited from test-driven development, python > needs it because of its dynamic nature. We can use "need" in the strict sense, as in "the language won't work without it". I think we can reject that as too strong, because clearly Python can work without unittests or any other sort of testing. In the looser sense of "this will benefit you", I think it is fair to say that *all* languages need test-driven development. If you want your code to do some non-trivial task X, and you don't actually test to see if it really does do X, then all the compiler tests in the world won't tell you that your code is doing X. Of course, the IT world is full of people writing code and not testing it, or at least not testing it correctly. That's why there are frequent updates or upgrades to software that break features that worked in the older version. That would be impossible in a test-driven methodology, at least impossible to do by accident. > And I don't think Haskell make the programmer do a lot of work(just > because of its static type checking at compile time). I could be wrong, but I think Haskell is *strongly* typed (just like Python), not *statically* typed. At least the "What Is Haskell?" page at haskell.org describes the language as strongly typed, non-strict, and allowing polymorphic typing. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Steven D'Aprano wrote: > > And I don't think Haskell make the programmer do a lot of work(just > > because of its static type checking at compile time). > > I could be wrong, but I think Haskell is *strongly* typed (just like > Python), not *statically* typed. At least the "What Is Haskell?" page at > haskell.org describes the language as strongly typed, non-strict, and > allowing polymorphic typing. > What is your definition of statically typed ? The non-strict as far as I know is not referring to type checking. It does check type at compile time though it is quite different from language like C, Java, the polymorphic typing. -- http://mail.python.org/mailman/listinfo/python-list
instance + classmethod question
Hello, Is it possible to tell, which instance was used to call the classmethod that is currently running? Background: I have a class called DatabaseConnection and it has a classmethod called process_create_tables. This method should create some database tables defined by a database definition object. The DatabaseConnection has many descendants, for example PostgreSQLConnection. Descendants know how to create tables in a given RDBMS type. I also use subclasses of the 'SQLProcessor' class, that processes SQL commands in different ways (print to stdout, write to file, execute directly in the database etc.) I would like to use the process_create_tables classmethod as is, because sometimes I only need to save a SQL script. However, I also want to use the same classmethod to create tables directly into an existing database. That database is presented as a DatabaseConnection instance. In that case, I only want to create the tables that do not exists yet. Examples: processor = SQLProcessors.StdOutProcessor() # Print to stdout PostgreSQLConnection.process_create_tables(processor,dbdef) # This sould create all tables, using the processor processor = SQLProcessors.DirectProcessor(conn) # Execute directly conn.process_create_tables(processor,dbdef) # This should create non-existing tables only, using the processor Is this possible? Maybe there is a better way to achieve this, I'm not sure. I was thinking about this construct: @classsmethod def process_create_tables(cls,processor,dbdef,conn=None) and then calling it as conn.process_create_tables(processor,dbdef,conn) but this looks very ugly to me. It would be much easier if I could tell which instance (if any) was used to call the classmethod. Thanks, Les -- http://mail.python.org/mailman/listinfo/python-list
Re: subset permutations
Steven D'Aprano wrote: > On Fri, 09 Dec 2005 16:03:46 +1100, Ben Finney wrote: > > >> Do you want the result to be: > >> AB, AC, AD, BC, BD, CD > > > > That is the complete set of combinations of the letters. > > > >> Or, do you want AB,BA,AC,CA,AD,DA,BC,CB,BD,DB,CD,DB ? > > > > That is the complete set of permutations of the letters. > > > Only if you are choosing without replacement. If you are choosing with > replacement, you also get AA, BB, CC, DD. > > Unfortunately, there is ambiguity in the terms "permutation" and > "combination", not just between English common usage and mathematics, but > even in mathematics. Why is that unfortunate? Now we can all post our favorite scripts and let them be severely criticized :-) Anton def ncycle(seq,n): while True: for x in seq: i = 0 while i < n: yield x i += 1 def cross(*args): p = 1 R = [] for seq in reversed(args): R.append(ncycle(seq,p)) p *= len(seq) R.reverse() i = 0 while i < p: yield tuple(x.next() for x in R) i += 1 def test(): s1='a1','a2','a3','a4' s2='b1','b2' s3='c1','c2','c3' for x in cross(s1,s2,s3): print x if __name__=='__main__': test() -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Fredrik Lundh wrote: > Write code, not usenet posts. QOTW! -- http://mail.python.org/mailman/listinfo/python-list
Re: Great books on Python?
Tolga wrote: > I am not unfamiliar to programming but a newbie in Python. Could you > recommend me (a) great book(s) to start with? Free online books or > solid books are welcome. > > Thanx in advance. > I'd call Dive Into Python a reference, it's an extremely clear yet pythonic book, and it's available online for free. And I guess that you already checked it, but the Python's Tutorial is -- of course -- imperative. -- http://mail.python.org/mailman/listinfo/python-list
Re: Great books on Python?
http://www.awaretek.com/tutorials.html#regular -- http://mail.python.org/mailman/listinfo/python-list
Re: Great books on Python?
Tolga wrote: > I am not unfamiliar to programming but a newbie in Python. Could you > recommend me (a) great book(s) to start with? Free online books or > solid books are welcome. > http://www.ibiblio.org/g2swap/byteofpython/read/index.html http://www.ibiblio.org/obp/thinkCSpy/ http://www.freenetpages.co.uk/hp/alan.gauld/ -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Ernst Noch wrote: > Matthias Kaeppler wrote: > > Brian Beck wrote: > > > >> def foo(self): > >> raise NotImplementedError("Subclasses must implement foo") > > > > > > That's actually a good idea, though not as nice as a check at > > "compile-time" (jesus, I'm probably talking in C++ speech again, is > > there such a thing as compile-time in Python at all?!) > > > > Another thing which is really bugging me about this whole dynamically > > typing thing is that it seems very error prone to me: > > > > foo = "some string!" > > > > # ... > > > > if (something_fubar): > >fo = "another string" > > > > Oops, the last 'o' slipped, now we have a different object and the > > interpreter will happily continue executing the flawed program. > > > > I really see issues with this, can anyone comment on this who has been > > working with Python more than just a day (like me)? > > > > Regards, > > Matthias > > Matthias, > > maybe this article is of interest for you: > http://www.mindview.net/WebLog/log-0025 > And two related ones. http://www.algorithm.com.au/mt/programming_languages/me_on_xoltar_on_static_typing.html Just follow the links. -- http://mail.python.org/mailman/listinfo/python-list
Re: Another newbie question
Mike Meyer <[EMAIL PROTECTED]> wrote: ... > It's not my cherished example - it actually came from someone You picked it to (try and fail to) show that there is DIFFICULTY, which I showed there isn't. > else. That you can change the requirements so that there is no extra > work is immaterial - all you've done is shown that there are examples > where that don't require extra work. I never said that such examples > didn't exist. All you've shown - in both the single concrete example > and in a generalized case - is that any requirement can be changed so > that it doesn't require any extra work. This doesn't change the fact > that such cases exist, which is all that I claimed was the case. Untrue: you claimed that the specific API (allowing attribute-setting) "makes changing the object more difficult", not the obvious fact that "there exist APIs so badly designed that they make changing more difficult". And I showed that, in the GENERAL case, since attributes worth being made assignable are obviously also worth being made settable in a constructor of some kind, having settable attributes doesn't and cannot introduce any DIFFICULTY -- the API with settable attributes only requires trivial methods, ones presenting no difficulty whatsoever, which delegate all the real work to methods you'd need anyway (particularly the obviously-needed constructor or factory). So, I claim I have totally disproven your claims about difficulty ("extra work", as you're trying to weaselword your way out, might be writing one or two trivial lines of code, but that's not DIFFICULT, and the claim you originally made was about DIFFICULTY, not tiny amounts of trivially easy "extra work" -- as I already mentioned, obviously ANY method you add is "extra work" for you compared to not adding it, but the interesting question is whether that entails any DIFFICULTY). My claim hinges on the fact that constructors are important -- more so, of course, for immutable instances, but even in the mutable case it's pretty bad design if the ONLY way to have an instance in the state you know is right is to make it in a state that's wrong and then call mutators on it until its state is finally right... obviously it's important to avoid imposing this busywork on all users of the class. If you further weaken your claim to "it's possible to design so badly that everybody involved faces more work and difficulties", I'll most obviously agree -- but such bad designs need not involve any attribute-setters, nor does including attribute-setters imply or even suggest that a design is bad in this way! Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
gene tani wrote: > http://naeblis.cx/rtomayko/2004/12/15/the-static-method-thing > http://dirtsimple.org/2004/12/java-is-not-python-either.html > http://dirtsimple.org/2004/12/python-is-not-java.html > > http://idevnews.com/PrintVersion_CaseStudies.asp?Search3=web+services&Go2=Go&ID=118 > http://www.idevnews.com/PrintVersion_TipsTricks.asp?ID=107 > http://www.eros-os.org/pipermail/e-lang/2001-June/005337.html First of all, thanks everybody for posting all these answers and links, much appreciated. What Bruce Eckel wrote about dynamic typing was quite convincing and reasonable. I stumbled over this paragraph in "Python is not Java", can anyone elaborate on it: "In Java, you have to use getters and setters because using public fields gives you no opportunity to go back and change your mind later to using getters and setters. So in Java, you might as well get the chore out of the way up front. In Python, this is silly, because you can start with a normal attribute and change your mind at any time, without affecting any clients of the class. So, don't write getters and setters." Why would I want to use an attribute in Python, where I would use getters and setters in Java? I know that encapsulation is actually just a hack in Python (common, "hiding" an implementation detail by prefixing it with the classname so you can't access it by its name anymore? Gimme a break...), but is that a reason to only write white box classes? ^^ - Matthias -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
[EMAIL PROTECTED] wrote: > Just follow the links. I'll try ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: instance + classmethod question
Laszlo Zsolt Nagy wrote: > > Hello, > > Is it possible to tell, which instance was used to call the classmethod > that is currently running? > [snip] > > processor = SQLProcessors.StdOutProcessor() # Print to stdout > PostgreSQLConnection.process_create_tables(processor,dbdef) # This > sould create all tables, using the processor > > processor = SQLProcessors.DirectProcessor(conn) # Execute directly > conn.process_create_tables(processor,dbdef) # This should create > non-existing tables only, using the processor > > Is this possible? It looks like you want a method that accepts either a class or an instance. I would typically create two methods, one for the class-based table-creating, and one for the instance-based table-creating. However, if you *have* to do it this way, you can introduce your own descriptor which should give you the behavior you want:: >>> class ClassOrInstanceMethod(object): ... def __init__(self, func): ... self.func = func ... self.classfunc = classmethod(func) ... def __get__(self, obj, objtype=None): ... func = obj is None and self.classfunc or self.func ... return func.__get__(obj, objtype) ... >>> class C(object): ... @ClassOrInstanceMethod ... def f(*args): ... print args ... >>> C.f() (,) >>> C().f() (<__main__.C object at 0x00E73D90>,) Basically, if the descriptor is called from a type (and thus ``obj is None``), we return a bound classmethod, and if the descriptor is called from an instance, we return a bound instance method. Of course this now means you should write your code something like:: @ClassOrInstanceMethod def process_create_tables(cls_or_self, processor, dbdef): ... whose "cls_or_self" parameter gives me a bad code smell. YMMV. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Another newbie question
Mike Meyer <[EMAIL PROTECTED]> wrote: ... > > Claim: doing X makes Y hard. > > Harder, not hard. The specific wording you used was "MORE DIFFICULT". > > Here is an example of doing X where Y is easy > > Y is very easy in any case. Making it incrementally harder doesn't > make it hard - it's still very easy. If it's very easy, then going out of your way, as you did, to claim it's "MORE DIFFICULT" (you did not use the words "incrementally harder") is rather weird. There's no DIFFICULTY -- sure, if you have ANY one extra trivial method there IS ``extra work'' (a few seconds to write the trivial method and its unittest), but no extra DIFFICULTY. Moreover, I believe I vindicated attribute-setters (and their lack of difficulty) specifically by pointing out the trivial pattern which lets you make them easily, by using a constructor that you must have anyway in a good design (if attributes are worth setting on the fly, they're worth setting at the birth of an instance) and a state-copying method (which is always a good idea for mutable-instance classes). Assuming this wasn't obvious at the start to all readers, I may thus have hoped to have taught something to some reader -- an unusual and pleasant fallout from a mostly "polemical" thread, since often such threads are not very instructive. On that vein, I'll continue by pointing out that there may well be opportunities for optimization -- constructing a new instance is easy, but in some cases, depending on the implementation details, there may be faster approaches. That's most of the case for our using languages with modifiable data rather than pure functional ones, after all...: that changing data (rather than always having to make new objects) sometimes affords better performance. Still, let's not optimize *prematurely*!-) Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
On Sun, 11 Dec 2005 07:10:27 -0800, bonono wrote: > > Steven D'Aprano wrote: >> > And I don't think Haskell make the programmer do a lot of work(just >> > because of its static type checking at compile time). >> >> I could be wrong, but I think Haskell is *strongly* typed (just like >> Python), not *statically* typed. At least the "What Is Haskell?" page at >> haskell.org describes the language as strongly typed, non-strict, and >> allowing polymorphic typing. >> > What is your definition of statically typed ? The non-strict as far as > I know is not referring to type checking. It does check type at compile > time though it is quite different from language like C, Java, the > polymorphic typing. Strongly typed means that objects have a type. All objects in Python have a type. Strongly typed languages like Python forbid you from performing operations on mismatched types, e.g. 1 + "1" does not work. In order to perform operations on mismatched types, you must explicitly perform a conversion, e.g. 1 + int("1"). Weakly typed languages do not prevent you performing operations on mismatched types, e.g. something like 1 + "1" is allowed in languages like Basic and Perl. Untyped languages do not have any type information at all -- everything is just bytes. The most obvious example is assembly language. It should be noted that strong and weak typing is a matter of degree: despite being mostly strongly typed, Python does do automatic coercion of ints and floats, and although it is (arguably) weakly typed, Perl won't allow you to treat scalars as arrays or vice versa. Dynamic typing means that variables can be dynamically set to objects of wildly different types. For Python, we would say that any name can be bound to any object of any type. Static typing is the opposite of dynamic typing. Once a variable or name is defined as a certain type (either by a declaration, or implicitly the first time it is used), it can only be assigned to values of that same type. These two articles may be helpful: http://www.voidspace.org.uk/python/articles/duck_typing.shtml http://www.artima.com/forums/flat.jsp?forum=106&thread=7590 A thoughtful defence of static typing is here: http://www.xoltar.org/misc/static_typing_eckel.html The fact that it is sub-titled "How Java/C++/C# Ruin Static Typing for the Rest of Us" should give some idea what it is about. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Dao Language v.0.9.6-beta is release!
Zeljko Vrba wrote: > Nobody bothers to figure out something better? Now you will argue that then > the indendation is good enough.. and I can just reply that then it's an > open research question.. huh? people mention existing research (including formal usability studies), and your response is that since you don't agree with the results, more re- search is needed. do you think this is a kansas school board meeting? > I have no problem accepting that I'm in a minority. I have a problem with > offensive people using my example arguments to riducule me.. http://www.google.com/search?q=duck+typing -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Heiko Wundram wrote: > Maybe I'm assuming things by thinking that others also follow my line of > thought, but I've actually had very positive responses so far when telling > people that a certain feature is a certain way and then pointing them to > the ZoP, they all pretty much told me after a certain time of thought that > "the decision made sense now." Sorry to come across all harsh on the subject. Perhaps you know people who are more meditative than I do, but I notice that you served up some concrete advice elsewhere in the thread, so if the ZoP doesn't provide any guidance to the questioner as it is, at least there's something else to read through and grasp. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Steven D'Aprano wrote: > On Sun, 11 Dec 2005 07:10:27 -0800, bonono wrote: > > > > > Steven D'Aprano wrote: > >> > And I don't think Haskell make the programmer do a lot of work(just > >> > because of its static type checking at compile time). > >> > >> I could be wrong, but I think Haskell is *strongly* typed (just like > >> Python), not *statically* typed. At least the "What Is Haskell?" page at > >> haskell.org describes the language as strongly typed, non-strict, and > >> allowing polymorphic typing. > >> > > What is your definition of statically typed ? The non-strict as far as > > I know is not referring to type checking. It does check type at compile > > time though it is quite different from language like C, Java, the > > polymorphic typing. > > Strongly typed means that objects have a type. All objects in Python have > a type. > > Strongly typed languages like Python forbid you from performing operations > on mismatched types, e.g. 1 + "1" does not work. In order to perform > operations on mismatched types, you must explicitly perform a conversion, > e.g. 1 + int("1"). > > Weakly typed languages do not prevent you performing operations on > mismatched types, e.g. something like 1 + "1" is allowed in languages like > Basic and Perl. This much I know but it was not what we are talking about. > > Untyped languages do not have any type information at all -- everything > is just bytes. The most obvious example is assembly language. > > It should be noted that strong and weak typing is a matter of degree: > despite being mostly strongly typed, Python does do automatic coercion of > ints and floats, and although it is (arguably) weakly typed, Perl won't > allow you to treat scalars as arrays or vice versa. > > Dynamic typing means that variables can be dynamically set to objects of > wildly different types. For Python, we would say that any name can be > bound to any object of any type. > > Static typing is the opposite of dynamic typing. Once a variable or > name is defined as a certain type (either by a declaration, or > implicitly the first time it is used), it can only be assigned to values > of that same type. > > These two articles may be helpful: > > http://www.voidspace.org.uk/python/articles/duck_typing.shtml > http://www.artima.com/forums/flat.jsp?forum=106&thread=7590 > > > A thoughtful defence of static typing is here: > > http://www.xoltar.org/misc/static_typing_eckel.html > > The fact that it is sub-titled "How Java/C++/C# Ruin Static Typing for the > Rest of Us" should give some idea what it is about. > And you would see in the xoltar link that Haskell is a language of static typing. You cannot call a function with parameters with incompatible types which would be checked at compile time. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Steven D'Aprano wrote: > Weakly typed languages do not prevent you performing operations on > mismatched types, e.g. something like 1 + "1" is allowed in languages like > Basic and Perl. Actually, Perl and at least the version of BASIC that I previously used are not weakly-typed languages either. The addition operator in Perl uses coercion much as Python does/supports for some operand types, and classic microcomputer BASICs generally suffixed variable names in order to impose some kind of static typing. One classic example of a weakly-typed language is BCPL, apparently, but hardly anyone has any familiarity with it any more. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Great books on Python?
On Sun, 11 Dec 2005 06:15:17 -0800, Tolga wrote: > > I am not unfamiliar to programming but a newbie in Python. Could you > recommend me (a) great book(s) to start with? Free online books or > solid books are welcome. > > Thanx in advance. O'Reilly's Learning Python Second Edition covers up to version 2.3 and presumes a bit of knowledge with C. I've found it well written with a rather low count of errors. - Nate >> -- "The optimist proclaims that we live in the best of all possible worlds, the pessimist fears this is true." -- http://mail.python.org/mailman/listinfo/python-list
Re: instance + classmethod question
Hello Steven, I already implemented this using the form @classmethod def methodname(cls,other_params,self=None) but your example code looks so neat! This is exactly what I needed. :-) In my methods, most code is about string manipulation and calling other classmethods. There are only a few places where I can use an instance, but it is not required. I would like to reuse as most code as possible, so I do not want to create two different methods. That would result in duplicating code. Now the only problem is how I name this. It is not a classmethod, but it is also not a normal method. All right, it is a "ClassOrInstanceMethod". Amazing! Probably Python is the only language that is flexible enough to do this. :-) Thanks again! Laszlo Steven Bethard wrote: >Laszlo Zsolt Nagy wrote: > > >> Hello, >> >>Is it possible to tell, which instance was used to call the classmethod >>that is currently running? >> >> > >>> class ClassOrInstanceMethod(object): >... def __init__(self, func): >... self.func = func >... self.classfunc = classmethod(func) >... def __get__(self, obj, objtype=None): >... func = obj is None and self.classfunc or self.func >... return func.__get__(obj, objtype) >... > > -- http://mail.python.org/mailman/listinfo/python-list
Re: XML and namespaces
Alan Kennedy wrote: [Discussing the appearance of xmlns="DAV:"] > But that's incorrect. You have now defaulted the namespace to "DAV:" for > every unprefixed element that is a descendant of the href element. [Code creating the no_ns element with namespaceURI set to None] > > I must admit that I was focusing on the first issue rather than this one, even though it is related, when I responded before. Moreover, libxml2dom really should respect the lack of a namespace on the no_ns element, which the current version unfortunately doesn't do. However, wouldn't the correct serialisation of the document be as follows? As for the first issue - the presence of the xmlns attribute in the serialised document - I'd be interested to hear whether it is considered acceptable to parse the serialised document and to find that no non-null namespaceURI is set on the href element, given that such a namespaceURI was set when the document was created. In other words, ... document = libxml2dom.createDocument(None, "doc", None) top = document.xpath("*")[0] elem1 = document.createElementNS("DAV:", "href") document.replaceChild(elem1, top) elem2 = document.createElementNS(None, "no_ns") document.xpath("*")[0].appendChild(elem2) document.toFile(open("test_ns.xml", "wb")) ...as before, followed by this test: document = libxml2dom.parse("test_ns.xml") print "Namespace is", repr(document.xpath("*")[0].namespaceURI) What should the "Namespace is" message produce? Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
On Sun, 11 Dec 2005 17:05:16 +0100, Matthias Kaeppler wrote: > Why would I want to use an attribute in Python, where I would use > getters and setters in Java? Oh boy! I've just come out of a rather long thread about that very issue. If you care enough to read a bunch of people arguing past each other, check the thread "Another newbie question", especially the posts about the so-called Law of Demeter. But for the short summary: suppose I write a class: class Parrot: def __init__(self, x): self._x = x print "please use instance.getx() and setx()" def getx(self): return self._x def setx(self, x): self._x = x What if I want to export methods of x other than get and set? Perhaps x is a numeric value: now I have to export a whole series of arithmetic operators: addx, subx, mulx, etc. And there may be other attributes I need to export as well... When I write getter and setter methods for an attribute, I make myself responsible for maintaining everything about that attribute. I create extra functions that need to be tested, debugged and documented. I expect my class users to learn how to use my class, and every method is another method they have to learn about. Writing getter and setter methods have costs -- I pay some of those costs, and my users pay some of those costs. Then I get fed up and write this class instead: class NorwegianBlue: def __init__(self, x): self.x = x print "please use public attribute instance.x" NorwegianBlue is a much smaller class. That means less development time for me, less test code to write, less documentation, less time needed for my users to learn the API -- they already know what the API for x is, because they supplied it. The costs to both class designer and class user are much less, the flexibility is greater, and I finish writing the class quicker. Is there a disadvantage to NorwegianBlue? Yes -- I am now locked in to one particular interface. I can't even do something as trivial as change the name of attribute x. But then I can't change the name of Parrot.getx either, not without breaking people's code. But still, sometimes I know that I will want to -- or even that I might want to -- radically change the implementation of my class. Perhaps x is a list now, but later it will be a binary tree. How much effort will be needed to fix the breakage if NorwegianBlue changes? If the expected effort to fix the breakage is more than the effort to write setters and getters, then it makes sense to write setters and getters. But contrariwise, if it will take less effort to fix the problem than to defend against it, then why defend against it? Getters and setters are insurance against you changing the private interface. You wouldn't pay $20,000 a year to protect a $20,000 car. You might not even pay $1,000 a year. So do your trade-offs, and make your decision. > I know that encapsulation is actually just > a hack in Python (common, "hiding" an implementation detail by prefixing > it with the classname so you can't access it by its name anymore? Gimme > a break...), I'll give you a much better break in C++: #def private = public So much for encapsulation, hey? Java makes it harder, but not that much more: http://www.informit.com/articles/article.asp?p=174217&seqNum=3&rl=1 > but is that a reason to only write white box classes? ^^ Why would you want to write black box classes? Python is not a bondage and discipline language. Remember kids, whips and chains are only for mummies and daddies who love each other very much. Python includes tools for preventing people *accidentally* shooting themselves in the foot. But the philosophy of the language is to allow, even to encourage, people to tinker under the hood. If that means that somebody *deliberately* shoots themselves in the foot, well, that's the price you pay for freedom: some people make stupid decisions. I look at it this way: as the class designer, I have ZERO idea what attributes and methods of my class will be just the perfect thing to solve somebody's problem, so it is rude of me to lock them up as private -- especially since they *will* find a way to hack my class and access my private attributes and methods anyway. All I'm doing is making their life miserable by making them go out and buy books like "Hacking Private Attributes In Java" or something. But as a class designer, I know perfectly well which of my class members are free for anyone to touch (instance.public), which should be considered private by convention (instance._private) and which need a great big sign on the door saying "Enter At Own Risk! Don't touch this unless you know what you are doing!!!" (instance.__mangled). -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
In article <[EMAIL PROTECTED]>, Matthias Kaeppler <"matthias at finitestate dot org"> wrote: > >Why would I want to use an attribute in Python, where I would use >getters and setters in Java? I know that encapsulation is actually just >a hack in Python (common, "hiding" an implementation detail by prefixing >it with the classname so you can't access it by its name anymore? Gimme >a break...), but is that a reason to only write white box classes? ^^ "Simple is better than complex." -- Aahz ([EMAIL PROTECTED]) <*> http://www.pythoncraft.com/ "Don't listen to schmucks on USENET when making legal decisions. Hire yourself a competent schmuck." --USENET schmuck (aka Robert Kern) -- http://mail.python.org/mailman/listinfo/python-list
Random Number Generation?
Hello All, I need some help with random number generation. What I need exactly is: To create a few thousand numbers, decimal and integers, between 5 and 90, and then to export them as a single column at a spreadsheet. I am newbie, I was not able to create decimals with the random modules of Python 2.3. Thanks, Dimos __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Matthias Kaeppler <[EMAIL PROTECTED]> wrote: ... > I stumbled over this paragraph in "Python is not Java", can anyone > elaborate on it: > > "In Java, you have to use getters and setters because using public > fields gives you no opportunity to go back and change your mind later to > using getters and setters. So in Java, you might as well get the chore > out of the way up front. In Python, this is silly, because you can start > with a normal attribute and change your mind at any time, without > affecting any clients of the class. So, don't write getters and setters." > > Why would I want to use an attribute in Python, where I would use > getters and setters in Java? I know that encapsulation is actually just > a hack in Python (common, "hiding" an implementation detail by prefixing > it with the classname so you can't access it by its name anymore? Gimme > a break...), but is that a reason to only write white box classes? ^^ Consider the difference between asking a user of your class to write: a.setFoo(1 + a.getFoo()) versus allowing him or her to write: a.foo += 1 I hope you can see how much more elegant and handy the second alternative is. The point is, in Python, you can easily make the semantics of the second alternative identical to those of the first: all you need to do is, within a's class, add ONE line: foo = property(getFoo, setFoo) and every access of a.foo will become a call to a.getFoo(), every setting of a.foo=bar a call to a.setFoo(bar). The ability to do this IF AND WHEN getFoo and setFoo really need to exist (i.e., they do something meaningful, not just boilerplate setting and getting of plain attributes) empowers you to always allow the users of your class to access attributes -- you will change an attribute to a property only in future versions of your class that do need some meaningful action upon the getting or setting or that attribute. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Matthias Kaeppler <[EMAIL PROTECTED]> wrote: ... > I'm so used to statically typed languages that the shift is very > confusing. Looks as if it isn't as easy to learn Python afterall, for > the mere reason of unlearning rules which don't apply in the world of > Python anymore (which seem to be quite a lot!). If you start your reasoning with Java for most aspects (and with C++ for just a few) it may get easier -- for example, garbage collection, the semantics of assignment and argument passing, as well as the immutability of strings, are very close in Java and Python, and they're such a "bedrock layer" parts of the languages that IMHO they're more likely to be stumbling blocks if you "think C++" rather than "think Java", while learning Python. If you can imagine a Java program where everything is declared to be Object, all method calls have an implicit cast to "some interface supplying this method", and all class declarations implicitly add many "implements IMethodFoo" for automatic interfaces supplying each of their methods foo, you're a good part of the way;-). Such a style would be unusual (to say the least) in Java, but it's clearly POSSIBLE... it's actually not that unusual in Objective C (except you say ID rather than Object, and implicit interfaces ARE sort of there) -- the main caveat i would give to an Objective C person learning Python (besides the garbage collection issues) is "in Python, you cannot call arbitrary methods on None and expect them to be innocuous noops" (like in Java or C++, calling anything on None, aka a NULL pointer aka null, is a runtime error in Python too; the language without this restriction in this case is Objective C!-). Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: binascii.crc32 results not matching
Thanks so much for the offer, I had a friend do this for me and it works great. Regards, Larry Bates Heiko Wundram wrote: > Larry Bates wrote: > >> >> >>The algorithm looks very much like the source code for >>binascii.crc32 (but I'm not a C programmer). > > > Well... As you have access to the code, you might actually just create a > thin Python-Wrapper around this so that you can get comparable results. In > case you're unable to do so, send me the C-file (I'm not so keen on > copy-pasting code which was reformatted due to mail), and I'll send you an > extension module back. > > --- Heiko. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Sun, 11 Dec 2005 17:05:16 +0100, Matthias Kaeppler wrote: > > > Why would I want to use an attribute in Python, where I would use > > getters and setters in Java? > > Oh boy! I've just come out of a rather long thread about that very issue. > If you care enough to read a bunch of people arguing past each other, > check the thread "Another newbie question", especially the posts about the > so-called Law of Demeter. > > But for the short summary: suppose I write a class: > > class Parrot: > def __init__(self, x): > self._x = x > print "please use instance.getx() and setx()" > def getx(self): > return self._x > def setx(self, x): > self._x = x > > What if I want to export methods of x other than get and set? Perhaps x > is a numeric value: now I have to export a whole series of arithmetic > operators: addx, subx, mulx, etc. And there may be other attributes I need > to export as well... Sorry, I don't see this. a.setx( b.getx() + c.getx() - d.getx() ) will work just as well as (in a better-designed class) would a.x = b.x + c.x - d.x It's just that the former style you force syntactic cruft and overhead which you may save in the latter. "Exporting a series of operators", which was an issue in the LOD thread, is not one here: once you have setter and getter, by whatever syntax, it's not germane. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Random Number Generation?
Dimos <[EMAIL PROTECTED]> wrote: > Hello All, > > I need some help with random number generation. What I > need exactly is: > > To create a few thousand numbers, decimal and > integers, between 5 and 90, > and then to export them as a single column at a > spreadsheet. > > I am newbie, I was not able to create decimals with > the random modules of Python 2.3. The random module lets you create floats and integers, not instances of class decimal.Decimal (surely not in 2.3, which didn't even HAVE a module decimal in its standard library!). If you want floats, the way to create a float with uniform distribution between 5 and 90 is to call random.uniform(5, 90). If you want 3000: r3k = [random.uniform(5, 90) for i in xrange(3000)] None of the 3k numbers will be integers, and it's unlikely that any of the 3k floats happens to have a fractional part that's exactly 0. If you do want integers as well as floats, you'll have to decide with what probability an integer must appear instead of a float, and do a second pass on r3k to enforce this. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Matthias Kaeppler wrote: > Why would I want to use an attribute in Python, where I would use > getters and setters in Java? I know that encapsulation is actually just > a hack in Python (common, "hiding" an implementation detail by prefixing > it with the classname so you can't access it by its name anymore? Gimme > a break...), but is that a reason to only write white box classes? ^^ > > - Matthias > If you've ever written non-trivial code in Java, you can't deny that most of the classes are littered by pages and pages of -- protected FooClass foo; FooClass getFoo() { return foo; } void setFoo(FooClass foo) { this.foo = foo; } -- This is more or less equivalent to a simple -- public FooClass foo; -- but allows you to change the implementation details of the class without having to bork your whole interface later. Now, you have no reason to do this in python, you can use a regular "real" attribute, and if you need to change the implementation details, you can remove the real attribute and replace it with a virtual attribute through properties without changing the class' interface. -- >>> class Bar(object): def __init__(self): self.foo = 5 >>> bar = Bar() >>> bar.foo 5 >>> >>> # now let's change the Bar class implementation and split foo in boo and far >>> >>> class Bar(object): def __init__(self): self.boo = 2 self.far = 3 def _getfoo(self): return self.boo + self.far foo = property(_getfoo) >>> bar = Bar() >>> bar.foo 5 -- And this is completely transparent for anyone using the Bar class, they don't give a damn about what happens inside. You can also use it to add checks on the allowed values, for example -- >>> class Bar(object): def __init__(self): self._foo = 5 def _getfoo(self): return self._foo def _setfoo(self,foo): if not 0 <= foo <= 10: raise ValueError("foo's value must be between 0 and 10 (included)") self._foo = foo foo = property(_getfoo, _setfoo) >>> bar = Bar() >>> bar.foo 5 >>> bar.foo = 2 >>> bar.foo 2 >>> bar.foo = 20 Traceback (most recent call last): File "", line 1, in -toplevel- bar.foo = 20 File "", line 8, in _setfoo raise ValueError("foo's value must be between 0 and 10 (included)") ValueError: foo's value must be between 0 and 10 (included) >>> -- or everything else you'd use Java's getters/setters for, but without having to over-engineer your classes and wrap everything just because the language doesn't allow you to change your mind if you ever realize you made mistakes in the previous implementations. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Steven D'Aprano wrote: > I look at it this way: as the class designer, I have ZERO idea what > attributes and methods of my class will be just the perfect thing to solve > somebody's problem, so it is rude of me to lock them up as private -- > especially since they *will* find a way to hack my class and access my > private attributes and methods anyway. Actually, one good aspect of "attribute privacy" is the lowered risk of instance attribute name clashes. When subclassing from some partly abstract class in order to specialise its behaviour (sgmllib.SGMLParser, for example), one has to make sure that one doesn't reuse some instance attribute name by accident - doing so could potentially cause behavioural issues in the superclass's mechanisms. That said, Python does at least let you look at which attributes are already defined in an instance due to the lack of privacy, so it does offer some kind of solution to that problem. Moreover, Python also lets you define double-underscore attribute names which behave give instance attributes privacy in all respects, being invisible to users of the instances concerned, accessible only within methods belonging to the defining class, and safely overloadable in subclasses without incurring conflicts. Generally, I'm in agreement with you, though: private, protected and final are all things which provide easy distractions from more serious and demanding issues. They can quite often prove to be "the bikeshed" in system design and implementation. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Random Number Generation?
Dimos wrote: > I need some help with random number generation. What I > need exactly is: > > To create a few thousand numbers, decimal and > integers, between 5 and 90, > and then to export them as a single column at a > spreadsheet. > > I am newbie, I was not able to create decimals with > the random modules of > Python 2.3. the random function returns a random number between 0.0 and 1.0, so >>> import random >>> help(random.random) Help on built-in function random: random(...) random() -> x in the interval [0, 1). so to get what you want, all you have to do is to multiply by (90-5) and add 5 at the end: v = random.random() * 85.0 + 5.0 the random.uniform() wrapper does exactly this: v = random.uniform(5.0, 90.0) -- http://mail.python.org/mailman/listinfo/python-list
Re: Random Number Generation?
Dimos wrote: > Hello All, > > I need some help with random number generation. What I > need exactly is: > > To create a few thousand numbers, decimal and > integers, between 5 and 90, > and then to export them as a single column at a > spreadsheet. > > I am newbie, I was not able to create decimals with > the random modules of > Python 2.3. You use randint(a,b) to generate an integer between a and b. For real numbers, the function is random(). But that result is always between 0.0 and 1.0, so you have to make the range adjustment yourself. >>> import random >>> for i in range(10): print random.random()*85 + 5 20.2844473176 83.5690712033 77.3459998722 8.79906993754 53.3672450881 25.2609744882 19.8894951301 39.9794852838 43.4056977237 21.7770662903 > > Thanks, Dimos > > > __ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: binascii.crc32 results not matching
I wrote: > this prints > > 0xF032519BL 0xF032519BL > 0x90E3070AL 0x90E3070AL > > no time to sort out the int/long mess for binascii.crc32, but it pro- > bably needs the same tweaking as PIL (which handles the CRC as > two 16-bit numbers, to avoid sign hell). I realized that I used 2.3 for testing. under 2.4, the following snippet runs without warnings: import binascii def test2(text, crc=0): return hex((binascii.crc32(text, crc^-1)^-1)&0x) in other words, crc = binascii.crc32(text, crc^-1)^-1)&0x should give the same result as larry's original CalculateCrc function. -- http://mail.python.org/mailman/listinfo/python-list
information needed to make a connection between computers
Hello again! I'm still working on that instant messenger (for science fair), and I have been reading about networking in some Java tutorials. In one part of it, it said to have a connection with another computer, you need to know the IP name of the computer you want to connect with. I don't know whether or not this is the same for Python, but could someone please tell me what information of the computer you want to connect with the you actually need for a connection? In other words (or plain english), what information do I need to get a connection with another computer (IP address, name, IP name)? Also, could you tell me how to find it on a computer? Since I'll be testing the instant messenger on the three computers in my house, I just need to know how to find the information on the computer I'd currently be on (not from any remote location). Thanks! :) -John Yahoo! Shopping Find Great Deals on Holiday Gifts at Yahoo! Shopping -- http://mail.python.org/mailman/listinfo/python-list
Re: Managing import statements
Shane Hathaway wrote: > Here's the real problem: maintaining import statements when moving > sizable blocks of code between modules is hairy and error prone. You can also evaluate a solution like this: http://codespeak.net/py/current/doc/misc.html#the-py-std-hook -- Giovanni Bajo -- http://mail.python.org/mailman/listinfo/python-list
Re: information needed to make a connection between computers
On 11/12/05, John Walton <[EMAIL PROTECTED]> wrote: Hello again! I'm still working on that instant messenger (for science fair), and I have been reading about networking in some Java tutorials. In one part of it, it said to have a connection with another computer, you need to know the IP name of the computer you want to connect with. I don't know whether or not this is the same for Python, but could someone please tell me what information of the computer you want to connect with the you actually need for a connection? In other words (or plain english), what information do I need to get a connection with another computer (IP address, name, IP name)? Also, could you tell me how to find it on a computer? Since I'll be testing the instant messenger on the three computers in my house, I just need to know how to find the information on the computer I'd currently be on (not from any remote location). Thanks! :) You need to know the hostname of the remote machine you are trying to make a connection to. From this you can work out the IP address of the machine and then connect to it directly. You could work with just the IP address, but these are liable to change, where as the hostname in theory won't. >>> import socket >>> socket.gethostbyname('www.yahoo.com') '216.109.117.207' >>> If the machine is on your network, using its name (eg 'JohnW' ) should give the same result HTH :) -- http://mail.python.org/mailman/listinfo/python-list
Re: python and VisualFox dbf
lux schrieb: > Hi, > I've a dfb written in VisualFox, > I need to send a "pack" and "reindex" > but in odbc is not supported... > > Anybody know how to do this? > > TIA, > Luca > I am quite sure this is supported in OLEDB. I thought this was also supported via ODBC, but you have to make sure that you are accessing the dbf's exclusively. HTH thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: pygene0.12 - Genetic Programming&Algorithms Library
aum wrote: > Hi all, > > This announcement supersedes an earlier announcement of pygene. > > pygene 0.2 now supports genetic programming, in addition to the classical > Mendelian genetic algorithms of the earlier version. I thank the > respondents to the earlier announcement for inspiring me to implement GP > functionality. > > http://www.freenet.org.nz/python/pygene Cool! I'll surly take a look at that :) -- eXt -- http://mail.python.org/mailman/listinfo/python-list
Re: Great books on Python?
Tolga wrote: > > I am not unfamiliar to programming but a newbie in Python. Could you > recommend me (a) great book(s) to start with? Free online books or > solid books are welcome. > > Thanx in advance. Some days ago there was an similar subject 'Learning Python', wish give you some usefull informations a hope. If you ask me for some greats book, a answer "O'Reilly !" 1) Learning Python 2) programming Python 3) Python Pocket Reference 4) Python in a Nuteshell 5) Python Essential Reference 6) Python Cookbook Begin to buy the first ('1)') book, then second ('2)') ... A fatal link that surelly help http://nl.wikipedia.org/wiki/Python_%28programmeertaal%29 . I know it's in Dutch language but there is a usefull link on the bottom of this page ... I hope you think in same manner (some troubles to explain me), try and buy... Buy if you like it and if you use it...I hope is clearly enought !!! N.B.: I have not make this page on Wikipedia. -- David Van Mosselbeen - Debian Sarge user [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: XML and namespaces
[Paul Boddie] > However, > wouldn't the correct serialisation of the document be as follows? > > > Yes, the correct way to override a default namespace is an xmlns="" attribute. [Paul Boddie] > As for the first issue - the presence of the xmlns attribute in the > serialised document - I'd be interested to hear whether it is > considered acceptable to parse the serialised document and to find that > no non-null namespaceURI is set on the href element, given that such a > namespaceURI was set when the document was created. The key issue: should the serialised-then-reparsed document have the same DOM "content" (XML InfoSet) if the user did not explicitly create the requisite namespace declaration attributes? My answer: No, it should not be the same. My reasoning: The user did not explicitly create the attributes => The DOM should not automagically create them (according to the L2 spec) => such attributes should not be serialised - The user didn't create them - The DOM implementation didn't create them - If the serialisation processor creates them, that gives the same end result as if the DOM impl had (wrongly) created them. => the serialisation is a faithful/naive representation of the (not-namespace-well-formed) DOM constructed by the user (who omitted required attributes). => The reloaded document is a different DOM to the original, i.e. it has a different infoset. The xerces and jython snippet I posted the other day demonstrates this. If you look closely at that code, the actual DOM implementation and the serialisation processor used are from different libraries. The DOM is the inbuilt JAXP DOM implementation, Apache Crimson(the example only works on JDK 1.4). The serialisation processor is the Apache Xerces serialiser. The fact that the xmlns="DAV:" attribute didn't appear in the output document shows that BOTH the (Crimson) DOM implementation AND the (Xerces) serialiser chose NOT to automagically create the attribute. If you run that snippet with other DOM implementations, by setting the "javax.xml.parsers.DocumentBuilderFactory" property, you'll find the same result. Serialisation and namespace normalisation are both in the realm of DOM Level 3, whereas minidom is only L2 compliant. Automagically introducing L3 semantics into the L2 implementation is the wrong thing to do. http://www.w3.org/TR/DOM-Level-3-LS/load-save.html http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html [Paul Boddie] > In other words, ... > > What should the "Namespace is" message produce? Namespace is None If you want it to produce, Namespace is 'DAV:' and for your code to be portable to other DOM implementations besides libxml2dom, then your code should look like:- > document = libxml2dom.createDocument(None, "doc", None) > top = document.xpath("*")[0] > elem1 = document.createElementNS("DAV:", "href") elem1.setAttributeNS(xml.dom.XMLNS_NAMESPACE, "xmlns", "DAV:") > document.replaceChild(elem1, top) > elem2 = document.createElementNS(None, "no_ns") elem2.setAttributeNS(xml.dom.XMLNS_NAMESPACE, "xmlns", "") > document.xpath("*")[0].appendChild(elem2) > document.toFile(open("test_ns.xml", "wb")) its-not-about-namespaces-its-about-automagic-ly'yrs, -- alan kennedy -- email alan: http://xhaus.com/contact/alan -- http://mail.python.org/mailman/listinfo/python-list
mail attachment with non-ascii name
I am using the "email" module to decode incoming messages. (with msg = email.message_from_file( msg_file )) Sometimes an attachment has its name (as returned by msg.walk().part.get_filename()) not in ASCII (e.g. '=?iso-8859-1?q?somefile=2ezip?=') How can I turn that into simply 'somefile.zip' ? I have looked into email.Utils and codecs, but cannot find what should work. TIA, Bernard. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Matthias Kaeppler a écrit : > Hi, > > sorry for my ignorance, but after reading the Python tutorial on > python.org, I'm sort of, well surprised about the lack of OOP > capabilities in python. I beg your pardon ??? > Honestly, I don't even see the point at all of > how OO actually works in Python. > For one, is there any good reason why I should ever inherit from a > class? To specialize it (subtyping), or to add functionnalities (code reuse, factoring) > ^^ There is no functionality to check if a subclass correctly > implements an inherited interface I don't know of any language that provide such a thing. At least for my definition of "correctly". > and polymorphism seems to be missing > in Python as well. Could you share your definition of polymorphism ? > I kind of can't imagine in which circumstances > inheritance in Python helps. For example: > > class Base: >def foo(self): # I'd like to say that children must implement foo > pass class Base(object): def foo(self): raise NotImplementedError, "please implement foo()" > class Child(Base): >pass # works > Does inheritance in Python boil down to a mere code sharing? Yes. inheritence is initially made for code sharing (cf Smalltalk). The use of inheritence for subtyping comes from restrictions of statically typed languages [1]. BTW, you'll notice that the GoF (which is still one of the best references about OO) strongly advise to program to interfaces, not to implementations. And you'll notice that some patterns only exists as workarounds for the restrictions enforced by statically typed languages. [1] should say : for *a certain class of* statically typed languages. There are also languages like OCaml that relies on type inference. > And how do I formulate polymorphism in Python? In OO, polymorphism is the ability for objects of different classes to answer the same message. It doesn't imply that these objects should inherit from a common base class. Statically typed languages like C++ or Java *restrict* polymorphism. > Example: (snip) You don't need any of this. class Foo: def walk(self): print "%s walk" % self.__class__.__name__ class Bar: def walk(self): print "I'm singing in the rain" def letsgoforawalk(walker): walker.walk() f = Foo() b = Bar() letsgoforawalk(f) letsgoforawalk(b) Here, the function (BTW, did you know that in Python, functions are objects too ?) letsgoforawalk expect an object that has the type 'object that understand the message walk()'. Any object of this type will do - no need to have a common base class. > I could as well leave the whole inheritance stuff out and the program > would still work (?). Of course. Why should polymorphism need anything more ? > Please give me hope that Python is still worth learning :-/ It is, once you've unlearned C++/Java/ADA/whatever. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating referenceable objects from XML
Michael Williams wrote: > Hi All, > I'm looking for a quality Python XML implementation. All of the DOM > and SAX implementations I've come across so far are rather > convoluted. Are there any quality implementations that will (after > parsing the XML) return an object that is accessible by name? Such as > the following: > xml = """ > >MyBook >the author > > """ > And after parsing the XML allow me to access it as so: > book.title > I need it to somehow convert my XML to intuitively referenceable > object. Any ideas? I could even do it myself if I knew the > mechanism by which python classes do this (create variables on the fly). Looks as if MIchael is working with Amara now, but I did want to note for the record that APIs that allow one to access a node in the "book.title" fashion are what I call Python data bindings. Python data bindings I usually point out are: Amara Bindery: http://www.xml.com/pub/a/2005/01/19/amara.html Gnosis: http://www.xml.com/pub/a/2003/07/02/py-xml.html generateDS: http://www.xml.com/pub/a/2003/06/11/py-xml.html Based on updates to EaseXML in response to my article another entry might be: EaseXML: http://www.xml.com/pub/a/2005/07/27/py-xml.html ElementTree ( http://www.xml.com/pub/a/2003/02/12/py-xml.html ) is a Python InfoSet rather than a Python data binding. You access nodes using generic names related to the node type rather than the node name. Whether data bindings or Infosets are your preference is a matter of taste, but it's a useful distinction to make between the approaches. It looks as if Gerald Flanagan has constructed a little specialized binding tool on top of ElementTree, and that's one possible hybrid approach. xmltramp ( http://www.aaronsw.com/2002/xmltramp/ ) is another interesting hybrid. -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.nethttp://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Using XML w/ Python...
Jay: """ K, I have this XML doc, i dont know much about XML, but what i want to do is take certain parts of the XML doc, such as blah and take just that and put onto a text doc. Then same thing doe the part. Thats about it, i checked out some of the xml modules but dont understand how to use them. Dont get parsing, so if you could please explain working with XML and python to me. """ Someone already mentioned http://www.oreillynet.com/pub/wlg/6225 I do want to update that Amara API. As of recent releases it's as simple as import amara doc = amara.parse("foo.opml") for url in doc.xpath("//@xmlUrl"): print url.value Besides the XPath option, Amara [1] provides Python API options for unknown elements, such as node.xml_child_elements node.xml_attributes This is all covered with plenty of examples in the manual [2] [1] http://uche.ogbuji.net/tech/4suite/amara/ [2] http://uche.ogbuji.net/uche.ogbuji.net/tech/4suite/amara/manual-dev -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.nethttp://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Paul Boddie <[EMAIL PROTECTED]> wrote: ... > offer some kind of solution to that problem. Moreover, Python also lets > you define double-underscore attribute names which behave give instance > attributes privacy in all respects, being invisible to users of the > instances concerned, accessible only within methods belonging to the > defining class, and safely overloadable in subclasses without incurring > conflicts. Unfortunately, that depends on the subclasses' naming: in module bah.py: class Foo(object) ... in module zot.py: import bah class Foo(bah.Foo) ... and alas, the "privacy in all respects" breaks down. Now, the idea of "class Foo(bah.Foo)" may look silly with such artificial names, but it IS somewhat likely to happen in the real world when the classes' names are meaningful. I guess pychecker or the like might check for this and issue a warning if needed... but I do wish we had better ways to prevent accidental naming conflicts (not that I can easily think of any). Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Matthias Kaeppler a écrit : (snip) > I stumbled over this paragraph in "Python is not Java", can anyone > elaborate on it: > > "In Java, you have to use getters and setters because using public > fields gives you no opportunity to go back and change your mind later to > using getters and setters. So in Java, you might as well get the chore > out of the way up front. In Python, this is silly, because you can start > with a normal attribute and change your mind at any time, without > affecting any clients of the class. So, don't write getters and setters." > > Why would I want to use an attribute in Python, where I would use > getters and setters in Java? Because you don't *need* getters/setters - you already got'em for free (more on this latter). > I know that encapsulation is actually just > a hack in Python (common, "hiding" an implementation detail by prefixing > it with the classname so you can't access it by its name anymore? Gimme > a break...), You're confusing encapsulation with information hiding. The mechanism you're refering to is not meant to 'hide' anything, only to prevent accidental shadowing of some attributes. The common idiom for "information hiding" in Python is to prefix 'protected' attributes with a single underscore. This warns developers using your code that this is implementation detail, and that there on their own if they start messing with it. And - as incredible as this can be - that's enough. True, this won't stop stupid programmers from doing stupid thing - but no language is 'idiot-proof' anyway (know the old '#define private public' C++ trick ?), so why worry ? > but is that a reason to only write white box classes? ^^ First, what is a 'white box' class ? public class WhiteBox { protected integer foo; protected integer bar; public integer getFoo() { return foo; } public void setFoo(integer newfoo) { foo = newfoo; } public integer getBar() { return bar; } public void setBar(integer newbar) { bar = newbar; } } Does this really qualify as a 'blackbox' ? Of course not, everything is publicly exposed. You could have the exact same result (and much less code) with public attributes. Now what is the reason to write getters and setters ? Answer : so you can change the implementation without breaking the API, right ? Python has something named 'descriptors'. This is a mechanism that is used for attribute lookup (notice that everything being an object, methods are attributes too). You don't usually need to worry about it (you should read about if you really want to understand Python's object model), but you can still use it when you need to take control over attribute access. One of the simplest application is 'properties' (aka computed attributes), and here's an exemple : class Foo(object): def __init__(self, bar, baaz): self.bar = bar self._baaz = baaz def _getbaaz(self): return self._baaz baaz = Property(fget=_getbaaz) This is why you don't need explicit getters/setters in Python : they're already there ! And you can of course change how they are implemented without breaking the interface. Now *this* is encapsulation - and it doesn't need much information hiding... -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating referenceable objects from XML
[Michael Williams] > I need it to somehow convert my XML to intuitively referenceable > object. Any ideas? I could even do it myself if I knew the mechanism > by which python classes do this (create variables on the fly). You seem to already have a fair idea what kind of model you need, and to know that there is a simple way for you to create one. I encourage you to progress on this path: it will increase the depth of your understanding. One mistake I think that some people make about XML is relying on other peoples interpretations of the subject, rather than forming their own opinions. The multitude of document models provided by everyone and his mother all make assumptions about how the components of the model will be accessed, in what order those components will be accessed, how often and when, how memory efficient the model is, etc, etc. To really understand the trade-offs and strengths of all the different models, it is a good exercise to build your own object model. It's a simple exercise, due to pythons highly dynamic nature. Understanding your own model will help you understand what the other models do and do not provide. You can then evaluate other off-the-shelf models for your specific applications: I always find different XML tools suit different situations. See this post of mine from a couple years back about different ways of building your own document/data models. http://groups.google.com/group/comp.lang.python/msg/e2a4a1c35395ffec I think the reference to the ActiveState recipe will be of particular interest, since you could have a running example very quickly indeed. See also my tutorial post on extracting document content from a SAX stream. I gave the example of a simple stack-based xpath-style expression matcher. http://groups.google.com/group/comp.lang.python/msg/6853bddbb9326948 Also contained in that thread is an illuminating and productive discussion between the effbot and myself about how wonderfully simple ElementTree makes this, not to mention unbeatably efficient. this-week-i-ave-been-mostly-using-kid-for-templating-ly'yrs, -- alan kennedy -- email alan: http://xhaus.com/contact/alan -- http://mail.python.org/mailman/listinfo/python-list
Re: instance + classmethod question
Laszlo Zsolt Nagy wrote: > In my methods, most code is about string manipulation and calling other > classmethods. > There are only a few places where I can use an instance, but it is not > required. > I would like to reuse as most code as possible, so I do not want to > create two different > methods. That would result in duplicating code. I would tend to do this by creating a wrapper method for the instance that did the appropriate stuff for the instance, and then called the classmethod, e.g.: class C(object): ... @classmethod def do_stuff(cls, *args): ... def do_instance_stuff(self, *args): # instance stuff ... self.do_stuff(*args) # more instance stuff ... But it does require some factoring of the classmethod so that it makes sense to call it in this manner. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Displaying error message in a try except?
Fairly new to python. In a try except how do you display the true (raw) error message so it can be displayed back to the user? -- http://mail.python.org/mailman/listinfo/python-list
Re: mail attachment with non-ascii name
Bernard Delmée: > I am using the "email" module to decode incoming messages. > (with msg = email.message_from_file( msg_file )) > Sometimes an attachment has its name (as returned by > msg.walk().part.get_filename()) not in ASCII (e.g. > '=?iso-8859-1?q?somefile=2ezip?=') How can I turn that into > simply 'somefile.zip' ? I have looked into email.Utils and > codecs, but cannot find what should work. >>> import email.Header >>> x = '=?iso-8859-1?q?somefile=2ezip?=' >>> email.Header.decode_header(x) [('somefile.zip', 'iso-8859-1')] Neil -- http://mail.python.org/mailman/listinfo/python-list
Re: Displaying error message in a try except?
[EMAIL PROTECTED] wrote: > Fairly new to python. In a try except how do you display the true > (raw) error message so it can be displayed back to the user? assuming that "true" means "the message you would get if you hadn't used a try/except", the traceback module is what you want: import traceback try: raise SyntaxError("example") except: traceback.print_exc() prints Traceback (innermost last): File "module.py", line 4, in ? SyntaxError: example more here: http://effbot.org/librarybook/traceback.htm you can also inspect the exception status via the sys.exc_info() call. e.g. import sys try: 1/0 except: print "%s: %s" % sys.exc_info()[:2] prints exceptions.ZeroDivisionError: integer division or modulo by zero for more info, see the library reference. hope this helps! -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
"Paul Boddie" <[EMAIL PROTECTED]> writes: > One classic example of a > weakly-typed language is BCPL, apparently, but hardly anyone has any > familiarity with it any more. Actually, BCPL is what Stevenn D'Aprano called "untyped". Except his definition is suitable for after everyone followed IBM's footsteps in building general-purpose byte-addressable machines. In BCPL, everything is a word. Given a word, you can dereference it, add it to another word (as either a floating point value or an integer value), or call it as a function. A classic example of a weakly-typed language would be a grandchild of BCPL, v6 C. Since then, C has gotten steadily more strongly typed. A standard complaint as people tried to move code from a v6 C compiler (even the photo7 compiler) to the v7 compiler was "What do you mean I can't ". Of course, hardly anyone has familiarity with that any more, either. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: XML and namespaces
Alan Kennedy wrote: > Serialisation and namespace normalisation are both in the realm of DOM > Level 3, whereas minidom is only L2 compliant. Automagically introducing > L3 semantics into the L2 implementation is the wrong thing to do. I think I'll have to either add some configuration support, in order to let the user specify which standards they have in mind, or to deny/assert support for one or another of the standards. It's interesting that minidom plus PrettyPrint seems to generate the xmlns attributes in the serialisation, though; should that be reported as a bug? As for the toxml method in minidom, the subject did seem to be briefly discussed on the XML-SIG mailing list earlier in the year: http://mail.python.org/pipermail/xml-sig/2005-July/011157.html > its-not-about-namespaces-its-about-automagic-ly'yrs Well, with the automagic, all DOM users get the once in a lifetime chance to exchange those lead boots for concrete ones. I'm sure there are all sorts of interesting reasons for assigning namespaces to nodes, serialising the document, and then not getting all the document information back when parsing it, but I'd rather be spared all the "amusement" behind all those reasons and just have life made easier for just about everyone concerned. I think the closing remarks in the following message say it pretty well: http://mail-archives.apache.org/mod_mbox/xml-security-dev/200409.mbox/<1095071819.17967.44.camel%40amida> And there are some interesting comments on this archived page, too: http://web.archive.org/web/20010211173643/http://xmlbastard.editthispage.com/discuss/msgReader$6 Anyway, thank you for your helpful commentary on this matter! Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Displaying error message in a try except?
Fredrik Lundh wrote: > assuming that "true" means "the message you would get if you hadn't > used a try/except", the traceback module is what you want: > > you can also inspect the exception status via the sys.exc_info() call. > e.g. > There is also the third way of catching an exception explicitly and printing it's arguments and class (doesn't give exactly the same information, but gives relevant informations nonetheless) -- >>> try: 1/0 except ZeroDivisionError, e: print e print e.args print repr(e) integer division or modulo by zero ('integer division or modulo by zero',) -- (catching Exception instead of ZeroDivisionError would yield the same result, but would also act as an Exception trap that voids any exception raised) -- http://mail.python.org/mailman/listinfo/python-list
Re: Using XML w/ Python...
some great suggestions. Ok, i am now understanding some of parseing and how to use it and nodes, things like that. But say i wanted to take the title of http://www.digg.com/rss/index.xml and XMLTramp seemed the most simple to understand. would the path be something like this? import xmltramp rssDigg = xmltramp.load("http://www.digg.com/rss/index.xml";) print note.rss.channel.item.title I think thats wat im having the most confusion on now, is how to direct to the path that i want... Suggestions? -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Steven D'Aprano <[EMAIL PROTECTED]> writes: > Of course, the IT world is full of people writing code and not testing > it, or at least not testing it correctly. That's why there are frequent > updates or upgrades to software that break features that worked in the > older version. That would be impossible in a test-driven methodology, at > least impossible to do by accident. That sentence is only true if your tests are bug-free. If not, it's possible to make a change that introduces a bug that passes testing because of a bug in the tests. Since tests are code, they're never bug-free. I will agree that the frequency of upgrades/updates breaking things means testing isn't being done properly. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Bruno Desthuilliers <[EMAIL PROTECTED]> writes: >> ^^ There is no functionality to check if a subclass correctly >> implements an inherited interface > > I don't know of any language that provide such a thing. At least for > my definition of "correctly". Well, since your definition of "correclty" is uknown, I won't use it. I will point out that the stated goal is impossible for some reasonable definitions of "correctly". My definition of "correctly" is "meets the published contracts for the methods." Languages with good support for design by contract will insure that subclasses either correctly implement the published contracts, or raise an exception when they fail to do so. They do that by checking the contracts for the super classes in an appropriate logical relationship, and raising an exception if the contract isn't met. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Dao Language v.0.9.6-beta is release!
Zeljko Vrba <[EMAIL PROTECTED]> writes: > An obvious defficieny of the current way we write code now is its inherent > tree-structure resulting from {}, indentation, begin/end markers or whatnot. > But the flow of code is often not a tree but a cycle.. Yet we are always > dealing with a tree-like representation of the code on screen. Except the the representation on the screen isn't tree-like, it's a two-dimenional array of characters. You can, of course, interpret that as tree-like structure. But you can also interpret it as generalized graph, cycles included. > I have no problem accepting that I'm in a minority. I have a problem with > offensive people using my example arguments to riducule me.. While they > even don't want to open their minds and accept that there might be a > remote possibility that indentation is not ideal. What surprises me is that people come in assuming that there must be one language for everything and everyone, and that Python should strive to be that language. Such a language doesn't exist, so there is no such thing as 'ideal'. A language that might be optimal for one person and task won't necessarily be optimal if you change either the person or the task. Yet some people intent on forcing one language to be ideal propose changing it to suit them, and then act surprised when people who've tried their proposed changes in other languages and found them lacking reject them. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Displaying error message in a try except?
On 11/12/05, Fredrik Lundh <[EMAIL PROTECTED]> wrote: [EMAIL PROTECTED] wrote:> Fairly new to python. In a try except how do you display the true> (raw) error message so it can be displayed back to the user? assuming that "true" means "the message you would get if you hadn'tused a try/except", the traceback module is what you want:import tracebacktry:raise SyntaxError("example") except:traceback.print_exc()printsTraceback (innermost last): File "module.py", line 4, in ?SyntaxError: examplemore here: http://effbot.org/librarybook/traceback.htmyou can also inspect the exception status via the sys.exc_info() call.e.g.import systry:1/0except:print "%s: %s" % sys.exc_info()[:2]printsexceptions.ZeroDivisionError: integer division or modulo by zero Or you can combine both, I find these 3 lines after the except most helpful during developement stages and liberally splatter them around prototype code >>> import sys, traceback >>> try: ... 1/0 ... except: ... print sys.exc_info()[0] ... print sys.exc_info()[1] ... print "LINE=",traceback.tb_lineno(sys.exc_info()[2]) ... exceptions.ZeroDivisionError integer division or modulo by zero LINE= 2>>> HTH :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Another newbie question
[EMAIL PROTECTED] (Alex Martelli) writes: > Mike Meyer <[EMAIL PROTECTED]> wrote: >... >> It's not my cherished example - it actually came from someone > You picked it to (try and fail to) show that there is DIFFICULTY, which > I showed there isn't. No, you showed you could change the example so there is no extra difficulty. >> else. That you can change the requirements so that there is no extra >> work is immaterial - all you've done is shown that there are examples >> where that don't require extra work. I never said that such examples >> didn't exist. All you've shown - in both the single concrete example >> and in a generalized case - is that any requirement can be changed so >> that it doesn't require any extra work. This doesn't change the fact >> that such cases exist, which is all that I claimed was the case. > Untrue: you claimed that the specific API (allowing attribute-setting) > "makes changing the object more difficult", not the obvious fact that > "there exist APIs so badly designed that they make changing more > difficult". Except you haven't shown that the API was badly designed. You can't show that it's badly designed, because you don't know the requirements that the API is meeting. > And I showed that, in the GENERAL case, since attributes > worth being made assignable are obviously also worth being made settable > in a constructor of some kind, But we're not dealing with a general case, we're dealing with a specific case. Just because you can't think of cases where an attribute being settable doesn't mean it needs to be settable in a constructor doesn't mean they don't exist. > So, I claim I have totally disproven your claims about difficulty > ("extra work", as you're trying to weaselword your way out, might be > writing one or two trivial lines of code, but that's not DIFFICULT, and > the claim you originally made was about DIFFICULTY, not tiny amounts of > trivially easy "extra work" -- as I already mentioned, obviously ANY > method you add is "extra work" for you compared to not adding it, but > the interesting question is whether that entails any DIFFICULTY). Actually, the original claim was "more difficult". You've done your usual trick of reaching an invalid conclusion from what someone said, then acting as if that's what they said. Congratulations, you've successfully beaten up the straw man you created. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: instance + classmethod question
Laszlo Zsolt Nagy <[EMAIL PROTECTED]> writes: > Is it possible to tell, which instance was used to call the > classmethod that is currently running? Ok, I read through what got to my nntp server, and I'm still completely confused. A class method isn't necessarilry called by an instance. That's why it's a class method. What should happen in that case? You provided an example where you passed self as an optional argument. If it's going to have self, shouldn't it be an instance method? I think I agree with Steven - you should use two methods. You deal with the issue of duplicated code by pulling the code that would be duplicated out into private methods. This would be a straightforward refactoring problem. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Pythonic XML library with XPath support for Jython?
A couple of years ago there wasn't one and the recommendation was to simply use Java libs. Have things changed since? I see ElementTree promises one in the future but are there any out now? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Dao Language v.0.9.6-beta is release!
On Sun, 11 Dec 2005, Steven D'Aprano wrote: On Sat, 10 Dec 2005 16:34:13 +, Tom Anderson wrote: On Sat, 10 Dec 2005, Sybren Stuvel wrote: Zeljko Vrba enlightened us with: Find me an editor which has folds like in VIM, regexp search/replace within two keystrokes (ESC,:), marks to easily navigate text in 2 keystrokes (mx, 'x), can handle indentation-level matching as well as VIM can handle {}()[], etc. And, unlike emacs, respects all (not just some) settings that are put in its config file. Something that works satisfactorily out-of-the box without having to learn a new programming language/platform (like emacs). Found it! VIM! ED IS THE STANDARD TEXT EDITOR. Huh! *Real* men edit their text files by changing bits on the hard disk by hand with a magnetized needle. Hard disk? HARD DISK? Hard disks are for losers who can't write tight code. *Real* mean keep everything in core. Unless it's something performance-critical, in which case they fit it in the cache. tom -- ø¤º°`°º¤øø¤º°`°º¤øø¤º°`°º¤øø¤º°`°º¤ø-- http://mail.python.org/mailman/listinfo/python-list
Re: Using XML w/ Python...
""" Ok, i am now understanding some of parseing and how to use it and nodes, things like that. But say i wanted to take the title of http://www.digg.com/rss/index.xml and XMLTramp seemed the most simple to understand. would the path be something like this? import xmltramp rssDigg = xmltramp.load("http://www.digg.com/rss/index.xml";) print note.rss.channel.item.title I think thats wat im having the most confusion on now, is how to direct to the path that i want... """ I suggest you read at least the front page information for the tools you are using. It's quite clear from the xmltramp Web site ( http://www.aaronsw.com/2002/xmltramp/ ) that you want tomething like (untested: the least homework you can do is to refine the example yourself): print rssDigg[rss.channel][item][title] BTW, in Amara, the API is pretty much exactly what you guessed: >>> import amara >>> rssDigg = amara.parse("http://www.digg.com/rss/index.xml";) >>> print rssDigg.rss.channel.item.title Video: Conan O'Brien iPod Ad Parody -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.nethttp://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Another newbie question
Mike Meyer <[EMAIL PROTECTED]> wrote: ... > Except you haven't shown that the API was badly designed. You can't > show that it's badly designed, because you don't know the requirements > that the API is meeting. I can show that an API is badly designed *whatever requirements it might be intended for* if it's self-contradictory: containing a way to CHANGE an attribute to some different value, but not containing any way to SET THAT ATTRIBUTE TO THE RIGHT VALUE from the beginning, is inherently an indicator of bad design, because it needlessly imposes more work on the API's user and forces objects to pass through a transient state in which their attributes are WRONG, or MEANINGLESS. > > And I showed that, in the GENERAL case, since attributes > > worth being made assignable are obviously also worth being made settable > > in a constructor of some kind, > > But we're not dealing with a general case, we're dealing with a > specific case. Just because you can't think of cases where an > attribute being settable doesn't mean it needs to be settable in a > constructor doesn't mean they don't exist. The burden of the proof is on you, of course: show a design situation where it's RIGHT to force API users to do extra work and lead objects through states they're *NOT* meant to be in, because there is no way to build the object correctly from the start, but rather the object must be built in a wrong state and then later coerce it to the state you knew was right since the beginning. There may be languages which are so feeble as to force such behavior (e.g., languages where every new instance has every attribute forced to null even where it makes no sense for a certain attribute to ever be null) but that applies to neither Eiffel nor Python, and all it shows is that some languages are seriously lacking in the tools to allow proper designs to be implemented, not that "all objects must always be generated in the WRONG state" can ever be the RIGHT design. > > So, I claim I have totally disproven your claims about difficulty > > ("extra work", as you're trying to weaselword your way out, might be > > writing one or two trivial lines of code, but that's not DIFFICULT, and > > the claim you originally made was about DIFFICULTY, not tiny amounts of > > trivially easy "extra work" -- as I already mentioned, obviously ANY > > method you add is "extra work" for you compared to not adding it, but > > the interesting question is whether that entails any DIFFICULTY). > > Actually, the original claim was "more difficult". You've done your > usual trick of reaching an invalid conclusion from what someone said, > then acting as if that's what they said. Congratulations, you've > successfully beaten up the straw man you created. Right: I claim, on the other hand, that YOU are weaselwording, by trying to claim that any class with one extra method is thereby "MORE DIFFICULT" to write -- equating having to write one or two lines of trivial code with "MORE DIFFICULT" would make the "more difficult" totally bereft of any useful meaning in whatever context. I'm currently in an interesting job role, known as "uber technical lead", which is meant to be a sort of a cross between technical manager and ubergeek-guru. Fortunately, my reports are all people of technical excellence as well as personal integrity, so, should I ever ask one of them to explain why he or she did X and not Y, I fully trust they won't try to explain that "doing Y would have been more difficult" when the reality is that it would have involved a line of two of trivial code... if they did, I can assure you that the consequences might be interesting. (Good think I can and do trust them to say, should such a situation ever arise, "DUH! -- I just didn't think of it!", and go fix their code forthwith... just as they've often heard ME say, apologetically, in the much more frequent situations where my objections to some design were misconceived... so, my modest management abilities will not be put to such a difficult test in the foreseeable future;-). Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
On Mon, 12 Dec 2005, Steven D'Aprano wrote: On Sun, 11 Dec 2005 05:48:00 -0800, bonono wrote: And I don't think Haskell make the programmer do a lot of work(just because of its static type checking at compile time). I could be wrong, but I think Haskell is *strongly* typed (just like Python), not *statically* typed. Haskell is strongly and statically typed - very strongly and very statically! However, what it's not is manifestly typed - you don't have to put the types in yourself; rather, the compiler works it out. For example, if i wrote code like this (using python syntax): def f(x): return 1 + x The compiler would think "well, he takes some value x, and he adds it to 1 and 1 is an integer, and the only thing you can add to an integer is another integer, so x must be an integer; he returns whatever 1 + x works out to, and 1 and x are both integers, and adding two integers makes an integer, so the return type must be integer", and concludes that you meant (using Guido's notation): def f(x: int) -> int: return 1 + x Note that this still buys you type safety: def g(a, b): c = "{" + a + "}" d = 1 + b return c + d The compiler works out that c must be a string and d must be an int, then, when it gets to the last line, finds an expression that must be wrong, and refuses to accept the code. This sounds like it wouldn't work for complex code, but somehow, it does. And somehow, it works for: def f(x): return x + 1 Too. I think this is due to the lack of polymorphic operator overloading. A key thing is that Haskell supports, and makes enormous use of, a powerful system of generic types; with: def h(a): return a + a There's no way to infer concrete types for h or a, so Haskell gets generic; it says "okay, so i don't know what type a is, but it's got to be something, so let's call it alpha; we're adding two alphas, and one thing i know about adding is that adding two things of some type makes a new thing of that type, so the type of some-alpha + some-alpha is alpha, so this function returns an alpha". ISTR that alpha gets written 'a, so this function is: def h(a: 'a) -> 'a: return a + a Although that syntax might be from ML. This extends to more complex cases, like: def i(a, b): return [a, b] In Haskell, you can only make lists of a homogenous type, so the compiler deduces that, although it doesn't know what type a and b are, they must be the same type, and the return value is a list of that type: def i(a: 'a, b: 'a) -> ['a]: return [a, b] And so on. I don't know Haskell, but i've had long conversations with a friend who does, which is where i've got this from. IANACS, and this could all be entirely wrong! At least the "What Is Haskell?" page at haskell.org describes the language as strongly typed, non-strict, and allowing polymorphic typing. When applied to functional languages, 'strict' (or 'eager'), ie that expressions are evaluated as soon as they are formed; 'non-strict' (or 'lazy') means that expressions can hang around as expressions for a while, or even not be evaluated all in one go. Laziness is really a property of the implementation, not the the language - in an idealised pure functional language, i believe that a program can't actually tell whether the implementation is eager or lazy. However, it matters in practice, since a lazy language can do things like manipulate infinite lists. tom -- ø¤º°`°º¤øø¤º°`°º¤øø¤º°`°º¤øø¤º°`°º¤ø-- http://mail.python.org/mailman/listinfo/python-list
newbie question about python and Tkinter
Hello, I am a newbie and have a few questions about Python and Tkinter. I would like to create the following layout in Python: *** * * * * * * * frame 1 * * * * * * * * * *** * * * * * * * * * *frame 3* frame 2* * * * * * * * * * *** I try to accomplish this with the following code: from Tkinter import * root = Tk() root.title("Critter World") MyFrame0 = Frame(root, background="brown") # One Parent Frame to rule them all MyFrame1 = Frame(MyFrame0, background = "yellow") MyFrame2 = Frame(MyFrame0, background = "red") MyFrame3 = Frame(MyFrame0, background = "green") b1 = Label(MyFrame1, text="World", background="yellow").pack(fill=BOTH, expand=YES) b2 = Label(MyFrame2, text="Info", background="red").pack(fill=BOTH, expand=YES) b3 = Label(MyFrame3, text="Control", background="green").pack(fill=BOTH, expand=YES) MyFrame1.pack(side=TOP, fill=BOTH, expand=YES) MyFrame2.pack(side=RIGHT, fill=BOTH, expand=YES) MyFrame3.pack(side=LEFT, fill=BOTH, expand=YES) MyFrame0.pack(fill=BOTH, expand=YES) raw_input() print "\n"*23 When the window resizes, it is only Frame1 that is resized. However, if I run the following: from Tkinter import * root = Tk() root.title("Critter World") MyFrame0 = Frame(root, background="brown") # One Parent Frame to rule them all MyFrame1 = Frame(MyFrame0, background="yellow") MyFrame2 = Frame(MyFrame0, background = "red") MyFrame3 = Frame(MyFrame0, background = "green") MyFrame4 = Frame(MyFrame0, background = "black") b1 = Label(MyFrame1, text="World", background="yellow").pack(fill=BOTH, expand=YES) b2 = Label(MyFrame2, text="Info", background="red").pack(fill=BOTH, expand=YES) b3 = Label(MyFrame3, text="Control", background="green").pack(fill=BOTH, expand=YES) b4 = Label(MyFrame3, text="NEXT 1", background="green").pack(fill=BOTH, expand=YES) MyFrame1.pack(side=TOP, fill=BOTH, expand=YES) MyFrame2.pack(side=RIGHT, fill=BOTH, expand=YES) MyFrame3.pack(side=LEFT, fill=BOTH, expand=YES) MyFrame4.pack(side=BOTTOM, fill=BOTH, expand=YES) MyFrame0.pack(fill=BOTH, expand=YES) raw_input() print "\n"*23 I get: *** * * * * * * * frame 1 * * * * * * * * * * * * * * * * * * * *** * * * * * * *frame 3* * * * * * * * * frame 2* * * * * * * *frame 4* * * * * * * * *** and when I resize, all frames are resized? Any idea why? A related question: Why does frame 4 not span the bottom ? i.e. *** * * * * * * * frame 1 * * * * * * * * * * * * * * * * * * * *** * * * * * * *frame 2*frame 3 * * * * * * * *